From 94b1d95b0610d60125b55b0b6f5ce0120ad533e6 Mon Sep 17 00:00:00 2001 From: jagadeeeshaby Date: Thu, 21 Sep 2023 22:16:04 -0700 Subject: [PATCH 1/3] Adding support for 3p cookies --- .gitignore | 2 + .prettierignore | 21 + README.md | 204 +- gulpfile.js | 66 - package-lock.json | 10691 +++--- package.json | 43 +- release/connect-streams-min.js | 2 +- release/connect-streams.js | 39008 ++++++--------------- src/core.js | 283 +- src/request-storage-access.js | 392 + test/unit/request-storage-access.spec.js | 379 + test/unit/test-setup.js | 1 + webpack/common.js | 17 + webpack/connect-streams-min.config.js | 27 + webpack/connect-streams.config.js | 63 + 15 files changed, 18680 insertions(+), 32519 deletions(-) create mode 100644 .prettierignore delete mode 100644 gulpfile.js create mode 100644 src/request-storage-access.js create mode 100644 test/unit/request-storage-access.spec.js create mode 100644 webpack/common.js create mode 100644 webpack/connect-streams-min.config.js create mode 100644 webpack/connect-streams.config.js diff --git a/.gitignore b/.gitignore index 036b7943..f918e4ee 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ node_modules /.pnp .pnp.js +.nyc_output + # testing /coverage diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..eeb97745 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,21 @@ +**/src/lib/* +**/src/md5.js +**/src/aws-client.js +**/src/core.js +**/src/event.js +**/src/log.js +**/src/ringtone.js +**/src/sprintf.js +**/src/transitions.js +**/src/util.js +**/src/worker.js +**/src/client.js +**/src/api.js +**/src/drCoordinator/* +**/src/agent-app/* +**/src/index.d.ts +**/src/softphone.js +**/src/task.js +**/src/streams.js +**/src/userMediaProvider.js +**/test/* \ No newline at end of file diff --git a/README.md b/README.md index c6afe640..9362e892 100644 --- a/README.md +++ b/README.md @@ -2,47 +2,52 @@ [![Build Status](https://travis-ci.org/amazon-connect/amazon-connect-streams.svg?branch=master)](https://travis-ci.org/amazon-connect/amazon-connect-streams) -The Amazon Connect Streams API (Streams) gives you the power to integrate your existing web applications with Amazon Connect. Streams lets you embed the Contact Control Panel (CCP) and Customer Profiles app UI into your page. It also enables you to handle agent and contact state events directly through an object oriented event driven interface. You can use the built in interface or build your own from scratch: Streams gives you the choice. +The Amazon Connect Streams API (Streams) gives you the power to integrate your existing web applications with Amazon Connect. Streams lets you embed the Contact Control Panel (CCP) and Customer Profiles app UI into your page. It also enables you to handle agent and contact state events directly through an object oriented event driven interface. You can use the built in interface or build your own from scratch: Streams gives you the choice. This library must be used in conjunction with [amazon-connect-chatjs](https://github.com/amazon-connect/amazon-connect-chatjs) or [amazon-connect-taskjs](https://github.com/amazon-connect/amazon-connect-taskjs) in order to utilize Amazon Connect's Chat or Task functionality. # Learn More + To learn more about Amazon Connect and its capabilities, please check out the [Amazon Connect User Guide](https://docs.aws.amazon.com/connect/latest/userguide/). # Usage -amazon-connect-streams is available from [npmjs.com](https://www.npmjs.com/package/amazon-connect-streams). If you'd like to download it here, you can use either of the files like `release/connect-streams*`. -Run `npm run release` to generate new release files. Full instructions for building locally with npm can be found [below](#build-your-own-with-npm). +amazon-connect-streams is available from [npmjs.com](https://www.npmjs.com/package/amazon-connect-streams). If you'd like to download it here, you can use either of the files like `release/connect-streams*`. + +Run `npm run release` to generate new release files. Full instructions for building locally with npm can be found [below](#build-your-own-with-npm). We also support `make` for legacy builds. # Important Announcements -1. September 2021 - 1.7.0 comes with changes needed to use Amazon Connect Voice ID, which launched on 9/27/2021. For customers who want to use Voice ID, please upgrade Streams to version 1.7.0 or later in the next 1 month, otherwise the Voice ID APIs will stop working by the end of October 2021. For more details on the Voice ID APIs, please look at [the Voice ID APIs section](Documentation.md#voice-id-apis). -2. July 2021 - We released a change to the CCP that lets agent set a next status such as Lunch or Offline while still on a contact, and indicate they don’t want to be routed new contacts while they finish up their remaining work. For more details on this feature, see the [Amazon Connect agent training guide](https://docs.aws.amazon.com/connect/latest/adminguide/set-next-status.html) and the feature's [release notes](https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-release-notes.html#july21-release-notes). If your agents interact directly with Connect’s out-of-the-box CCPV2 UX, they will be able to access this feature by default. Otherwise, if your streamsJS application calls `agent.setState()` to switch agent status, you will need to update your code to use this feature: - * **Agent.setState()** has been updated so you can pass an optional flag `enqueueNextState: true` to trigger the Next Status behavior. - * A new **agent.onEnqueuedNextState()** listener lets you subscribe to events for when agents have selected/successfully enqueued their next status. - * A new **agent.getNextState()** API returns a state object if the agent has successfully selected a next state, and null otherwise. - * If you want to use the Next Status feature via `agent.setState()`, please also ensure that your code is using `contact.clear()` and not `contact.complete()` when clearing After Contact Work off a contact. -3. December 2020 — 1.6.0 brings with it the release of a new Agent App API. In addition to the CCP, customers can now embed additional applications using connect.agentApp, including Customer Profiles and Wisdom. See the [updated documentation](Documentation.md#initialization-for-ccp-customer-profiles-and-wisdom) for details on usage. We are also introducing a preview release for Amazon Connect Voice ID. - * ### About Amazon Connect Customer Profiles - + Amazon Connect Customer Profiles provides pre-built integrations so you can quickly combine customer information from multiple external applications, with contact history from Amazon Connect. This allows you to create a customer profile that has all the information agents need during customer interactions in a single place. - * ### About Amazon Connect Wisdom - + With Amazon Connect Wisdom, agents can search and find content across multiple repositories, such as frequently asked questions (FAQs), wikis, articles, and step-by-step instructions for handling different customer issues. They can type questions or phrases in a search box (such as, "how long after purchase can handbags be exchanged?") without having to guess which keywords will work. - * ### About Amazon Connect Voice ID (The feature is in preview release for Amazon Connect and is subject to change) - + Amazon Connect Voice ID provides real-time caller authentication which makes voice interactions in contact centers more secure and efficient. Voice ID uses machine learning to verify the identity of genuine customers by analyzing a caller’s unique voice characteristics. This allows contact centers to use an additional security layer that doesn’t rely on the caller answering multiple security questions, and makes it easy to enroll and verify customers without changing the natural flow of their conversation. -4. July 2020 -- We recently changed the new, omnichannel, CCP's behavior when it encounters three voice-only agent states: `FailedConnectAgent`, `FailedConnectCustomer`, and `AfterCallWork`. - * `FailedConnectAgent` -- Previously, we required the agent to click the "Clear Contact" button to clear this state. When the agent clicked the "Clear Contact" button, the previous behavior took the agent back to the `Available` state without fail. Now the `FailedConnectAgent` state will be "auto-cleared", much like `FailedConnectCustomer` always has been. - * `FailedConnectAgent` and `FailedConnectCustomer` -- We are now using the `contact.clear()` API to auto-clear these states. As a result, the agent will be returned to their previous visible agent state (e.g. `Available`). Previously, the agent had always been set to `Available` as a result of this "auto-clearing" behavior. Note that even custom CCPs will behave differently with this update for `FailedConnectAgent` and `FailedConnectCustomer`. - * `AfterCallWork` -- As part of the new `contact.clear()` behavior, clicking "Clear Contact" while in `AfterCallWork` will return the agent to their previous visible agent state (e.g. `Available`, etc.). Note that custom CCPs that implement their own After Call Work behavior will not be affected by this change. - * We are putting `contact.complete()` on a deprecation path. Therefore, you should start using `contact.clear()` in its place. If you want to emulate CCP's After Call Work behavior in your customer CCP, then make sure you use `contact.clear()` when clearing voice contacts. - + +- September 2023 - Amazon Connect CCP uses cookies for authentication. As part of Google's [Privacy Sandbox](https://privacysandbox.com/open-web/#the-privacy-sandbox-timeline) initiative, Google Chrome has announced plans to block third-party cookies (that is, cookies passed between two top level domains). Version 1.7.6 comes with request storage access API implementation which allows CCP to continue using third party cookies. [Learn more](https://docs.aws.amazon.com/connect/latest/adminguide/admin-3pcookies.html#implement-streams-upgrade). + +- September 2021 - 1.7.0 comes with changes needed to use Amazon Connect Voice ID, which launched on 9/27/2021. For customers who want to use Voice ID, please upgrade Streams to version 1.7.0 or later in the next 1 month, otherwise the Voice ID APIs will stop working by the end of October 2021. For more details on the Voice ID APIs, please look at [the Voice ID APIs section](Documentation.md#voice-id-apis). + +- July 2021 - We released a change to the CCP that lets agent set a next status such as Lunch or Offline while still on a contact, and indicate they don’t want to be routed new contacts while they finish up their remaining work. For more details on this feature, see the [Amazon Connect agent training guide](https://docs.aws.amazon.com/connect/latest/adminguide/set-next-status.html) and the feature's [release notes](https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-release-notes.html#july21-release-notes). If your agents interact directly with Connect’s out-of-the-box CCPV2 UX, they will be able to access this feature by default. Otherwise, if your streamsJS application calls `agent.setState()` to switch agent status, you will need to update your code to use this feature: + _ **Agent.setState()** has been updated so you can pass an optional flag `enqueueNextState: true` to trigger the Next Status behavior. + _ A new **agent.onEnqueuedNextState()** listener lets you subscribe to events for when agents have selected/successfully enqueued their next status. + _ A new **agent.getNextState()** API returns a state object if the agent has successfully selected a next state, and null otherwise. + _ If you want to use the Next Status feature via `agent.setState()`, please also ensure that your code is using `contact.clear()` and not `contact.complete()` when clearing After Contact Work off a contact. + +- December 2020 — 1.6.0 brings with it the release of a new Agent App API. In addition to the CCP, customers can now embed additional applications using connect.agentApp, including Customer Profiles and Wisdom. See the [updated documentation](Documentation.md#initialization-for-ccp-customer-profiles-and-wisdom) for details on usage. We are also introducing a preview release for Amazon Connect Voice ID. + _ ### About Amazon Connect Customer Profiles + Amazon Connect Customer Profiles provides pre-built integrations so you can quickly combine customer information from multiple external applications, with contact history from Amazon Connect. This allows you to create a customer profile that has all the information agents need during customer interactions in a single place. + _ ### About Amazon Connect Wisdom + With Amazon Connect Wisdom, agents can search and find content across multiple repositories, such as frequently asked questions (FAQs), wikis, articles, and step-by-step instructions for handling different customer issues. They can type questions or phrases in a search box (such as, "how long after purchase can handbags be exchanged?") without having to guess which keywords will work. + _ ### About Amazon Connect Voice ID (The feature is in preview release for Amazon Connect and is subject to change) + Amazon Connect Voice ID provides real-time caller authentication which makes voice interactions in contact centers more secure and efficient. Voice ID uses machine learning to verify the identity of genuine customers by analyzing a caller’s unique voice characteristics. This allows contact centers to use an additional security layer that doesn’t rely on the caller answering multiple security questions, and makes it easy to enroll and verify customers without changing the natural flow of their conversation. + . July 2020 -- We recently changed the new, omnichannel, CCP's behavior when it encounters three voice-only agent states: `FailedConnectAgent`, `FailedConnectCustomer`, and `AfterCallWork`. + _ `FailedConnectAgent` -- Previously, we required the agent to click the "Clear Contact" button to clear this state. When the agent clicked the "Clear Contact" button, the previous behavior took the agent back to the `Available` state without fail. Now the `FailedConnectAgent` state will be "auto-cleared", much like `FailedConnectCustomer` always has been. + _ `FailedConnectAgent` and `FailedConnectCustomer` -- We are now using the `contact.clear()` API to auto-clear these states. As a result, the agent will be returned to their previous visible agent state (e.g. `Available`). Previously, the agent had always been set to `Available` as a result of this "auto-clearing" behavior. Note that even custom CCPs will behave differently with this update for `FailedConnectAgent` and `FailedConnectCustomer`. + _ `AfterCallWork` -- As part of the new `contact.clear()` behavior, clicking "Clear Contact" while in `AfterCallWork` will return the agent to their previous visible agent state (e.g. `Available`, etc.). Note that custom CCPs that implement their own After Call Work behavior will not be affected by this change. \* We are putting `contact.complete()` on a deprecation path. Therefore, you should start using `contact.clear()` in its place. If you want to emulate CCP's After Call Work behavior in your customer CCP, then make sure you use `contact.clear()` when clearing voice contacts. + ## Getting Started ### Upgrading to the OmniChannel CCP (AKA CCPv2)? + If you are migrating to the new CCP, we encourage you to upgrade to the latest version of this repository. You should also upgrade to [the latest version of RTC-JS](https://github.com/aws/connect-rtc-js) as well, if you are using it. For a complete migration guide to the new CCP, and to fully understand the differences when using Streams with the new CCP, please see this post: https://docs.aws.amazon.com/connect/latest/adminguide/upgrade-to-latest-ccp.html ### Allowlisting + The first step to using Streams is to allowlist the pages you wish to embed. For our customer's security, we require that all domains which embed the CCP for a particular instance are explicitly allowlisted. Each domain entry identifies @@ -61,18 +66,21 @@ To allowlist your pages: website is hosted on a non-standard port. #### A few things to note: -* Allowlisted domains must be HTTPS. -* All of the pages that attempt to initialize the Streams library must be hosted + +- Allowlisted domains must be HTTPS. +- All of the pages that attempt to initialize the Streams library must be hosted on domains that are allowlisted as per the above steps. -* All open tabs that contain an initialized Streams library or any other CCP +- All open tabs that contain an initialized Streams library or any other CCP tabs opened will be synchronized. This means that state changes made in one open window will be communicated to all open windows. -* Using multiple browsers at the same time for the same connect instance is not supported, and causes issues with the rtc communication. +- Using multiple browsers at the same time for the same connect instance is not supported, and causes issues with the rtc communication. ## Downloading Streams with npm + `npm install amazon-connect-streams` ## Importing Streams with npm and ES6 + `import "amazon-connect-streams";` This will make the `connect` variable available in the current context. @@ -83,10 +91,13 @@ This will make the `connect` variable available in the current context. ```ts import "amazon-connect-streams"; -connect.core.initCCP({ /* ... */ }); +connect.core.initCCP({ + /* ... */ +}); ``` ## Downloading Streams from Github + The next step to embedding Connect into your application is to download the Streams library from GitHub. You can do that by cloning our public repository here: @@ -107,10 +118,10 @@ Connect Streams API which you will want to include in your page. You can serve `connect-streams-${VERSION}.js` with your web application. ## Build your own with NPM + Install latest LTS version of [NodeJS](https://nodejs.org) ``` -$ npm install -g gulp $ git clone https://github.com/aws/amazon-connect-streams $ cd amazon-connect-streams $ npm install @@ -120,23 +131,27 @@ $ npm run release Find build artifacts in **release** directory - This will generate a file called `connect-streams.js` and the minified version of the same `connect-streams-min.js` - this is the full Connect Streams API which you will want to include in your page. To run unit tests specifically: + ``` -$ npm run gulp-test +$ npm run test-mocha ``` ## Using the AWS SDK and Streams + Streams has a "baked-in" version of the AWS-SDK in the `./src/aws-client.js` file. Make sure that you import Streams before the AWS SDK so that the `AWS` object bound to the `Window` is the object from your manually included SDK, and not from Streams. ## Initialization + Initializing the Streams API is the first step to verify that you have everything setup correctly and that you will be able to listen for events. ### `connect.core.initCCP()` + ```html - + @@ -144,115 +159,124 @@ everything setup correctly and that you will be able to listen for events.
``` + Integrates with Connect by loading the pre-built CCP located at `ccpUrl` into an iframe and placing it into the `containerDiv` provided. API requests are funneled through this CCP and agent and contact updates are published through it and made available to your JS client code. -* `ccpUrl`: The URL of the CCP. This is the page you would normally navigate to + +- `ccpUrl`: The URL of the CCP. This is the page you would normally navigate to in order to use the CCP in a standalone page, it is different for each instance. -* `region`: Amazon connect instance region. ex: `us-west-2`. only required for chat channel. -* `loginPopup`: Optional, defaults to `true`. Set to `false` to disable the login popup +- `region`: Amazon connect instance region. ex: `us-west-2`. only required for chat channel. +- `loginPopup`: Optional, defaults to `true`. Set to `false` to disable the login popup which is shown when the user's authentication expires. -* `loginOptions`: Optional, only valid when `loginPopup` is set to `true`. - Provide an object with the following properties to open loginpopup in a new window instead of a - new tab. - * `autoClose`: Optional, defaults to `false`. Set to `true` to automatically - close the login popup after the user logs in. - * `height`: This allows you to define the height of the login pop-up window. - * `width`: This allows you to define the width of the login pop-up window. - * `top`: This allows you to define the top of the login pop-up window. - * `left`: This allows you to define the left of the login pop-up window. -* `loginPopupAutoClose`: Optional, defaults to `false`. Set to `true` in conjunction with the - `loginPopup` parameter to automatically close the login Popup window once the authentication step - has completed. If the login page opened in a new tab, this parameter will also auto-close that - tab. This can also be set in `loginOptions` if those options are used. -* `loginUrl`: Optional. Allows custom URL to be used to initiate the ccp, as in +- `loginOptions`: Optional, only valid when `loginPopup` is set to `true`. + Provide an object with the following properties to open loginpopup in a new window instead of a + new tab. + - `autoClose`: Optional, defaults to `false`. Set to `true` to automatically + close the login popup after the user logs in. + - `height`: This allows you to define the height of the login pop-up window. + - `width`: This allows you to define the width of the login pop-up window. + - `top`: This allows you to define the top of the login pop-up window. + - `left`: This allows you to define the left of the login pop-up window. +- `loginPopupAutoClose`: Optional, defaults to `false`. Set to `true` in conjunction with the + `loginPopup` parameter to automatically close the login Popup window once the authentication step + has completed. If the login page opened in a new tab, this parameter will also auto-close that + tab. This can also be set in `loginOptions` if those options are used. +- `loginUrl`: Optional. Allows custom URL to be used to initiate the ccp, as in the case of SAML authentication. -* `softphone`: This object is optional and allows you to specify some settings +- `softphone`: This object is optional and allows you to specify some settings surrounding the softphone feature of Connect. - * `allowFramedSoftphone`: Normally, the softphone microphone and speaker + - `allowFramedSoftphone`: Normally, the softphone microphone and speaker components are not allowed to be hosted in an iframe. This is because the softphone must be hosted in a single window or tab. The window hosting the softphone session must not be closed during the course of a softphone call or the call will be disconnected. If `allowFramedSoftphone` is `true`, the softphone components will be allowed to be hosted in this window or tab. - * `disableRingtone`: This option allows you to completely disable the built-in + - `disableRingtone`: This option allows you to completely disable the built-in ringtone audio that is played when a call is incoming. - * `ringtoneUrl`: If the ringtone is not disabled, this allows for overriding + - `ringtoneUrl`: If the ringtone is not disabled, this allows for overriding the ringtone with any browser-supported audio file accessible by the user. -* `pageOptions`: This object is optional and allows you to configure which configuration sections are displayed in the settings tab. - * `enableAudioDeviceSettings`: If `true`, the settings tab will display a section for configuring audio input and output devices for the agent's local - machine. If `false`, or if `pageOptions` is not provided, the agent will not be able to change audio device settings from the settings tab. will not be - 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. -* `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. +- `pageOptions`: This object is optional and allows you to configure which configuration sections are displayed in the settings tab. + - `enableAudioDeviceSettings`: If `true`, the settings tab will display a section for configuring audio input and output devices for the agent's local + machine. If `false`, or if `pageOptions` is not provided, the agent will not be able to change audio device settings from the settings tab. will not be + 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. +- `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. + #### A few things to note: -* You have the option to show or hide the pre-built UI by showing or hiding the -`containerDiv` into which you place the iframe, or applying a CSS rule like -this: + +- You have the option to show or hide the pre-built UI by showing or hiding the + `containerDiv` into which you place the iframe, or applying a CSS rule like + this: + ```css #container-div iframe { display: none; } ``` -* The CCP UI is rendered in an iframe under the container element provided. + +- The CCP UI is rendered in an iframe under the container element provided. The iframe fills its container element with `width: 100%; height: 100%`. To customize the size of the CCP, set the width and height for the container element. -* The CCP is designed to be responsive (used in various sizes). +- The CCP is designed to be responsive (used in various sizes). The smallest size we design for is 320px x 460px. For a good user experience, we recommend that you do not go smaller than this size. -* CSS styles you add to your site will NOT be applied to the CCP because it is +- CSS styles you add to your site will NOT be applied to the CCP because it is rendered in an iframe. -* If you are trying to use chat specific functionalities, please also include +- If you are trying to use chat specific functionalities, please also include [ChatJS](https://github.com/amazon-connect/amazon-connect-chatjs) in your code. We omit ChatJS from the Makefile so that streams can be used without ChatJS. Streams only needs ChatJS when it is being used for chat. Note that when including ChatJS, it must be imported after StreamsJS, or there will be AWS SDK issues (ChatJS relies on the ConnectParticipant Service, which is not in the Streams AWS SDK). -* If you are using task functionalities you must include [TaskJS](https://github.com/amazon-connect/amazon-connect-taskjs). TaskJS should be imported after Streams. -* If you'd like access to the WebRTC session to further customize the softphone experience +- If you are using task functionalities you must include [TaskJS](https://github.com/amazon-connect/amazon-connect-taskjs). TaskJS should be imported after Streams. +- If you'd like access to the WebRTC session to further customize the softphone experience you can use [connect-rtc-js](https://github.com/aws/connect-rtc-js). Please refer to the connect-rtc-js readme for detailed instructions on integrating connect-rtc-js with Streams. ## Where to go from here + Check out the full documentation [here](Documentation.md) to read more about subscribing to events and enacting state changes programmatically. - - diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index b2369e9b..00000000 --- a/gulpfile.js +++ /dev/null @@ -1,66 +0,0 @@ -var istanbul = require('gulp-istanbul'), - mocha = require('gulp-mocha'), - concat = require('gulp-concat'), - gulp = require('gulp'), - uglify = require('gulp-uglify'), - rename = require('gulp-rename'), - jshint = require('gulp-jshint'), - replace = require('gulp-replace'), - pump = require('pump'); - fs = require('fs'); - path = require('path'); - -var source = [ "src/aws-client.js", - "src/sprintf.js", - "src/log.js", - "src/util.js", - "src/event.js", - "src/streams.js", - "src/client.js", - "src/transitions.js", - "src/api.js", - "src/lib/amazon-connect-websocket-manager.js", - "src/core.js", - "src/ringtone.js", - "src/softphone.js", - "src/worker.js", - "src/mediaControllers/*", - "src/agent-app/agent-app.js", - "src/agent-app/app-registry.js" - -]; - -gulp.task('pre-test', function () { - return gulp.src(['./src/*.js']) - // Covering files - .pipe(istanbul({includeUntested: false})) - // Force `require` to return covered files - .pipe(istanbul.hookRequire()); -}); - -gulp.task('test', gulp.series('pre-test', function (cb) { - return gulp.src(['test/unit/**/*.spec.js']) - .pipe(mocha({exit: true, showStack:true})) - .on('error', (err) => cb(err)) - // Creating the reports after tests ran - .pipe(istanbul.writeReports()); -})); - -gulp.task('watch', function() { - gulp.watch('src/*.js', gulp.series('script')); -}); - -gulp.task('script', function (cb) { - pump([ - gulp.src(source), - jshint(), - replace("STREAMS_VERSION", process.env.npm_package_version), - concat('connect-streams.js'), - gulp.dest('./release/'), - rename('connect-streams-min.js'), - uglify(), - gulp.dest('./release/') - ], cb); -}); - -gulp.task('default', gulp.series('script', 'test')); diff --git a/package-lock.json b/package-lock.json index 962d093e..2db43635 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,2808 +1,5169 @@ { "name": "amazon-connect-streams", - "version": "1.7.5", - "lockfileVersion": 1, + "version": "1.7.6", + "lockfileVersion": 3, "requires": true, - "dependencies": { - "@sinonjs/commons": { - "version": "1.8.3", - "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", + "packages": { + "": { + "name": "amazon-connect-streams", + "version": "1.7.6", + "license": "Apache-2.0", + "devDependencies": { + "@babel/preset-env": "^7.21.4", + "@babel/preset-typescript": "^7.21.4", + "@typescript-eslint/eslint-plugin": "^5.59.1", + "@typescript-eslint/parser": "^5.59.1", + "babel": "^6.23.0", + "babel-loader": "^9.1.2", + "chai": "^4.3.7", + "jshint": "^2.13.6", + "mocha": "^10.2.0", + "mocha-jsdom": "^2.0.0", + "nyc": "^15.1.0", + "prettier": "^2.8.8", + "pump": "^3.0.0", + "sinon": "^12.0.0", + "terser-webpack-plugin": "^5.3.7", + "typescript": "^5.0.4", + "webpack": "^5.8.0", + "webpack-cli": "^4.9.1", + "webpack-plugin-replace": "^1.2.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@aashutoshrathi/word-wrap": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz", + "integrity": "sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", + "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.22.13", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", + "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", + "dev": true, + "dependencies": { + "@babel/highlight": "^7.22.13", + "chalk": "^2.4.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.22.20.tgz", + "integrity": "sha512-BQYjKbpXjoXwFW5jGqiizJQQT/aC7pFm9Ok1OWssonuguICi264lbgMzRp2ZMmRSlfkX6DsWDDcsrctK8Rwfiw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.22.20.tgz", + "integrity": "sha512-Y6jd1ahLubuYweD/zJH+vvOY141v4f9igNQAQ+MBgq9JlHS2iTsZKn1aMsb3vGccZsXI16VzTBw52Xx0DWmtnA==", + "dev": true, + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.22.13", + "@babel/generator": "^7.22.15", + "@babel/helper-compilation-targets": "^7.22.15", + "@babel/helper-module-transforms": "^7.22.20", + "@babel/helpers": "^7.22.15", + "@babel/parser": "^7.22.16", + "@babel/template": "^7.22.15", + "@babel/traverse": "^7.22.20", + "@babel/types": "^7.22.19", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.22.15.tgz", + "integrity": "sha512-Zu9oWARBqeVOW0dZOjXc3JObrzuqothQ3y/n1kUtrjCoCPLkXUwMvOo/F/TCfoHMbWIFlWwpZtkZVb9ga4U2pA==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.15", + "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.22.5.tgz", + "integrity": "sha512-LvBTxu8bQSQkcyKOU+a1btnNFQ1dMAd0R6PyW3arXes06F6QLWLIrd681bxRPIXlrMGR3XYnW9JyML7dP3qgxg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-builder-binary-assignment-operator-visitor": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.22.15.tgz", + "integrity": "sha512-QkBXwGgaoC2GtGZRoma6kv7Szfv06khvhFav67ZExau2RaXzy8MpHSMO2PNoP2XtmQphJQRHFfg77Bq731Yizw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.22.15.tgz", + "integrity": "sha512-y6EEzULok0Qvz8yyLkCvVX+02ic+By2UdOhylwUOvOn9dvYc9mKICJuuU1n1XBI02YWsNsnrY1kc6DVbjcXbtw==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.22.9", + "@babel/helper-validator-option": "^7.22.15", + "browserslist": "^4.21.9", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.22.15.tgz", + "integrity": "sha512-jKkwA59IXcvSaiK2UN45kKwSC9o+KuoXsBDvHvU/7BecYIp8GQ2UwrVvFgJASUT+hBnwJx6MhvMCuMzwZZ7jlg==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-environment-visitor": "^7.22.5", + "@babel/helper-function-name": "^7.22.5", + "@babel/helper-member-expression-to-functions": "^7.22.15", + "@babel/helper-optimise-call-expression": "^7.22.5", + "@babel/helper-replace-supers": "^7.22.9", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.22.15.tgz", + "integrity": "sha512-29FkPLFjn4TPEa3RE7GpW+qbE8tlsu3jntNYNfcGsc49LphF1PQIiD+vMZ1z1xVOKt+93khA9tc2JBs3kBjA7w==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "regexpu-core": "^5.3.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-define-polyfill-provider": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.4.2.tgz", + "integrity": "sha512-k0qnnOqHn5dK9pZpfD5XXZ9SojAITdCKRn2Lp6rnDGzIbaP0rHyMPk/4wsSxVBVz4RfN0q6VpXWP2pDGIoQ7hw==", + "dev": true, + "dependencies": { + "@babel/helper-compilation-targets": "^7.22.6", + "@babel/helper-plugin-utils": "^7.22.5", + "debug": "^4.1.1", + "lodash.debounce": "^4.0.8", + "resolve": "^1.14.2" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.22.5.tgz", + "integrity": "sha512-wtHSq6jMRE3uF2otvfuD3DIvVhOsSNshQl0Qrd7qC9oQJzHvOL4qQXlQn2916+CXGywIjpGuIkoyZRRxHPiNQQ==", + "dev": true, + "dependencies": { + "@babel/template": "^7.22.5", + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.22.15.tgz", + "integrity": "sha512-qLNsZbgrNh0fDQBCPocSL8guki1hcPvltGDv/NxvUoABwFq7GkKSu1nRXeJkVZc+wJvne2E0RKQz+2SQrz6eAA==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", + "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.22.20.tgz", + "integrity": "sha512-dLT7JVWIUUxKOs1UnJUBR3S70YK+pKX6AbJgB2vMIvEkZkrfJDbYDJesnPshtKV4LhDOR3Oc5YULeDizRek+5A==", + "dev": true, + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-module-imports": "^7.22.15", + "@babel/helper-simple-access": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/helper-validator-identifier": "^7.22.20" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.22.5.tgz", + "integrity": "sha512-HBwaojN0xFRx4yIvpwGqxiV2tUfl7401jlok564NgB9EHS1y6QT17FmKWm4ztqjeVdXLuC4fSvHc5ePpQjoTbw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", + "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-remap-async-to-generator": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.22.20.tgz", + "integrity": "sha512-pBGyV4uBqOns+0UvhsTO8qgl8hO89PmiDYv+/COyp1aeMcmfrfruz+/nCMFiYyFF/Knn0yfrC85ZzNFjembFTw==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-wrap-function": "^7.22.20" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.22.20.tgz", + "integrity": "sha512-qsW0In3dbwQUbK8kejJ4R7IHVGwHJlV6lpG6UA7a9hSa2YEiAib+N1T2kr6PEeUT+Fl7najmSOS6SmAwCHK6Tw==", + "dev": true, + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-member-expression-to-functions": "^7.22.15", + "@babel/helper-optimise-call-expression": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", + "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.22.5.tgz", + "integrity": "sha512-tK14r66JZKiC43p8Ki33yLBVJKlQDFoA8GYN67lWCDCqoL6EMMSuM9b+Iff2jHaM/RRFYl7K+iiru7hbRqNx8Q==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", + "dev": true, + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", + "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.22.15.tgz", + "integrity": "sha512-bMn7RmyFjY/mdECUbgn9eoSY4vqvacUnS9i9vGAGttgFWesO6B4CYWA7XlpbWgBt71iv/hfbPlynohStqnu5hA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-wrap-function": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.22.20.tgz", + "integrity": "sha512-pms/UwkOpnQe/PDAEdV/d7dVCoBbB+R4FvYoHGZz+4VPcg7RtYy2KP7S2lbuWM6FCSgob5wshfGESbC/hzNXZw==", + "dev": true, + "dependencies": { + "@babel/helper-function-name": "^7.22.5", + "@babel/template": "^7.22.15", + "@babel/types": "^7.22.19" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.22.15.tgz", + "integrity": "sha512-7pAjK0aSdxOwR+CcYAqgWOGy5dcfvzsTIfFTb2odQqW47MDfv14UaJDY6eng8ylM2EaeKXdxaSWESbkmaQHTmw==", + "dev": true, + "dependencies": { + "@babel/template": "^7.22.15", + "@babel/traverse": "^7.22.15", + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", + "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.22.16", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.22.16.tgz", + "integrity": "sha512-+gPfKv8UWeKKeJTUxe59+OobVcrYHETCsORl61EmSkmgymguYk/X5bp7GuUIXaFsc6y++v8ZxPsLSSuujqDphA==", + "dev": true, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.22.15.tgz", + "integrity": "sha512-FB9iYlz7rURmRJyXRKEnalYPPdn87H5no108cyuQQyMwlpJ2SJtpIUBI27kdTin956pz+LPypkPVPUTlxOmrsg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.22.15.tgz", + "integrity": "sha512-Hyph9LseGvAeeXzikV88bczhsrLrIZqDPxO+sSmAunMPaGrBGhfMWzCPYTtiW9t+HzSE2wtV8e5cc5P6r1xMDQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", + "@babel/plugin-transform-optional-chaining": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.13.0" + } + }, + "node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", + "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "dev": true, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-dynamic-import": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz", + "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-export-namespace-from": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-export-namespace-from/-/plugin-syntax-export-namespace-from-7.8.3.tgz", + "integrity": "sha512-MXf5laXo6c1IbEbegDmzGPwGNTsHZmEy6QGznu5Sh2UCWvueywb2ee+CCE4zQiZstxU9BMoQO9i6zUFSY0Kj0Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-assertions": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.22.5.tgz", + "integrity": "sha512-rdV97N7KqsRzeNGoWUOK6yUsWarLjE5Su/Snk9IYPU9CwkWHs4t+rTGOvffTR8XGkJMTAdLfO0xVnXm8wugIJg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.22.5.tgz", + "integrity": "sha512-KwvoWDeNKPETmozyFE0P2rOLqh39EoQHNjqizrI5B8Vt0ZNS7M56s7dAiAqbYfiAYOuIzIh96z3iR2ktgu3tEg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.22.5.tgz", + "integrity": "sha512-gvyP4hZrgrs/wWMaocvxZ44Hw0b3W8Pe+cMxc8V1ULQ07oh8VNbIRaoD1LRZVTvD+0nieDKjfgKg89sD7rrKrg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.22.5.tgz", + "integrity": "sha512-1mS2o03i7t1c6VzH6fdQ3OA8tcEIxwG18zIPRp+UY1Ihv6W+XZzBCVxExF9upussPXJ0xE9XRHwMoNs1ep/nRQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-unicode-sets-regex": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz", + "integrity": "sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.18.6", + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.22.5.tgz", + "integrity": "sha512-26lTNXoVRdAnsaDXPpvCNUq+OVWEVC6bx7Vvz9rC53F2bagUWW4u4ii2+h8Fejfh7RYqPxn+libeFBBck9muEw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-generator-functions": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.22.15.tgz", + "integrity": "sha512-jBm1Es25Y+tVoTi5rfd5t1KLmL8ogLKpXszboWOTTtGFGz2RKnQe2yn7HbZ+kb/B8N0FVSGQo874NSlOU1T4+w==", + "dev": true, + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-remap-async-to-generator": "^7.22.9", + "@babel/plugin-syntax-async-generators": "^7.8.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-to-generator": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.22.5.tgz", + "integrity": "sha512-b1A8D8ZzE/VhNDoV1MSJTnpKkCG5bJo+19R4o4oy03zM7ws8yEMK755j61Dc3EyvdysbqH5BOOTquJ7ZX9C6vQ==", + "dev": true, + "dependencies": { + "@babel/helper-module-imports": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-remap-async-to-generator": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoped-functions": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.22.5.tgz", + "integrity": "sha512-tdXZ2UdknEKQWKJP1KMNmuF5Lx3MymtMN/pvA+p/VEkhK8jVcQ1fzSy8KM9qRYhAf2/lV33hoMPKI/xaI9sADA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoping": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.22.15.tgz", + "integrity": "sha512-G1czpdJBZCtngoK1sJgloLiOHUnkb/bLZwqVZD8kXmq0ZnVfTTWUcs9OWtp0mBtYJ+4LQY1fllqBkOIPhXmFmw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-properties": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.22.5.tgz", + "integrity": "sha512-nDkQ0NfkOhPTq8YCLiWNxp1+f9fCobEjCb0n8WdbNUBc4IB5V7P1QnX9IjpSoquKrXF5SKojHleVNs2vGeHCHQ==", + "dev": true, + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-static-block": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.22.11.tgz", + "integrity": "sha512-GMM8gGmqI7guS/llMFk1bJDkKfn3v3C4KHK9Yg1ey5qcHcOlKb0QvcMrgzvxo+T03/4szNh5lghY+fEC98Kq9g==", + "dev": true, + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.22.11", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-class-static-block": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0" + } + }, + "node_modules/@babel/plugin-transform-classes": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.22.15.tgz", + "integrity": "sha512-VbbC3PGjBdE0wAWDdHM9G8Gm977pnYI0XpqMd6LrKISj8/DJXEsWqgRuTYaNE9Bv0JGhTZUzHDlMk18IpOuoqw==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-compilation-targets": "^7.22.15", + "@babel/helper-environment-visitor": "^7.22.5", + "@babel/helper-function-name": "^7.22.5", + "@babel/helper-optimise-call-expression": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-replace-supers": "^7.22.9", + "@babel/helper-split-export-declaration": "^7.22.6", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-computed-properties": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.22.5.tgz", + "integrity": "sha512-4GHWBgRf0krxPX+AaPtgBAlTgTeZmqDynokHOX7aqqAB4tHs3U2Y02zH6ETFdLZGcg9UQSD1WCmkVrE9ErHeOg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/template": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-destructuring": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.22.15.tgz", + "integrity": "sha512-HzG8sFl1ZVGTme74Nw+X01XsUTqERVQ6/RLHo3XjGRzm7XD6QTtfS3NJotVgCGy8BzkDqRjRBD8dAyJn5TuvSQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dotall-regex": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.22.5.tgz", + "integrity": "sha512-5/Yk9QxCQCl+sOIB1WelKnVRxTJDSAIxtJLL2/pqL14ZVlbH0fUQUZa/T5/UnQtBNgghR7mfB8ERBKyKPCi7Vw==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-keys": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.22.5.tgz", + "integrity": "sha512-dEnYD+9BBgld5VBXHnF/DbYGp3fqGMsyxKbtD1mDyIA7AkTSpKXFhCVuj/oQVOoALfBs77DudA0BE4d5mcpmqw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dynamic-import": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-7.22.11.tgz", + "integrity": "sha512-g/21plo58sfteWjaO0ZNVb+uEOkJNjAaHhbejrnBmu011l/eNDScmkbjCC3l4FKb10ViaGU4aOkFznSu2zRHgA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-dynamic-import": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-exponentiation-operator": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.22.5.tgz", + "integrity": "sha512-vIpJFNM/FjZ4rh1myqIya9jXwrwwgFRHPjT3DkUA9ZLHuzox8jiXkOLvwm1H+PQIP3CqfC++WPKeuDi0Sjdj1g==", + "dev": true, + "dependencies": { + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-export-namespace-from": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-7.22.11.tgz", + "integrity": "sha512-xa7aad7q7OiT8oNZ1mU7NrISjlSkVdMbNxn9IuLZyL9AJEhs1Apba3I+u5riX1dIkdptP5EKDG5XDPByWxtehw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-for-of": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.22.15.tgz", + "integrity": "sha512-me6VGeHsx30+xh9fbDLLPi0J1HzmeIIyenoOQHuw2D4m2SAU3NrspX5XxJLBpqn5yrLzrlw2Iy3RA//Bx27iOA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-function-name": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.22.5.tgz", + "integrity": "sha512-UIzQNMS0p0HHiQm3oelztj+ECwFnj+ZRV4KnguvlsD2of1whUeM6o7wGNj6oLwcDoAXQ8gEqfgC24D+VdIcevg==", + "dev": true, + "dependencies": { + "@babel/helper-compilation-targets": "^7.22.5", + "@babel/helper-function-name": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-json-strings": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.22.11.tgz", + "integrity": "sha512-CxT5tCqpA9/jXFlme9xIBCc5RPtdDq3JpkkhgHQqtDdiTnTI0jtZ0QzXhr5DILeYifDPp2wvY2ad+7+hLMW5Pw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-json-strings": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-literals": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.22.5.tgz", + "integrity": "sha512-fTLj4D79M+mepcw3dgFBTIDYpbcB9Sm0bpm4ppXPaO+U+PKFFyV9MGRvS0gvGw62sd10kT5lRMKXAADb9pWy8g==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-logical-assignment-operators": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.22.11.tgz", + "integrity": "sha512-qQwRTP4+6xFCDV5k7gZBF3C31K34ut0tbEcTKxlX/0KXxm9GLcO14p570aWxFvVzx6QAfPgq7gaeIHXJC8LswQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-member-expression-literals": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.22.5.tgz", + "integrity": "sha512-RZEdkNtzzYCFl9SE9ATaUMTj2hqMb4StarOJLrZRbqqU4HSBE7UlBw9WBWQiDzrJZJdUWiMTVDI6Gv/8DPvfew==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-amd": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.22.5.tgz", + "integrity": "sha512-R+PTfLTcYEmb1+kK7FNkhQ1gP4KgjpSO6HfH9+f8/yfp2Nt3ggBjiVpRwmwTlfqZLafYKJACy36yDXlEmI9HjQ==", + "dev": true, + "dependencies": { + "@babel/helper-module-transforms": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.22.15.tgz", + "integrity": "sha512-jWL4eh90w0HQOTKP2MoXXUpVxilxsB2Vl4ji69rSjS3EcZ/v4sBmn+A3NpepuJzBhOaEBbR7udonlHHn5DWidg==", + "dev": true, + "dependencies": { + "@babel/helper-module-transforms": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-simple-access": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-systemjs": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.22.11.tgz", + "integrity": "sha512-rIqHmHoMEOhI3VkVf5jQ15l539KrwhzqcBO6wdCNWPWc/JWt9ILNYNUssbRpeq0qWns8svuw8LnMNCvWBIJ8wA==", + "dev": true, + "dependencies": { + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-module-transforms": "^7.22.9", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-umd": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.22.5.tgz", + "integrity": "sha512-+S6kzefN/E1vkSsKx8kmQuqeQsvCKCd1fraCM7zXm4SFoggI099Tr4G8U81+5gtMdUeMQ4ipdQffbKLX0/7dBQ==", + "dev": true, + "dependencies": { + "@babel/helper-module-transforms": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.22.5.tgz", + "integrity": "sha512-YgLLKmS3aUBhHaxp5hi1WJTgOUb/NCuDHzGT9z9WTt3YG+CPRhJs6nprbStx6DnWM4dh6gt7SU3sZodbZ08adQ==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-new-target": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.22.5.tgz", + "integrity": "sha512-AsF7K0Fx/cNKVyk3a+DW0JLo+Ua598/NxMRvxDnkpCIGFh43+h/v2xyhRUYf6oD8gE4QtL83C7zZVghMjHd+iw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.22.11.tgz", + "integrity": "sha512-YZWOw4HxXrotb5xsjMJUDlLgcDXSfO9eCmdl1bgW4+/lAGdkjaEvOnQ4p5WKKdUgSzO39dgPl0pTnfxm0OAXcg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-numeric-separator": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.22.11.tgz", + "integrity": "sha512-3dzU4QGPsILdJbASKhF/V2TVP+gJya1PsueQCxIPCEcerqF21oEcrob4mzjsp2Py/1nLfF5m+xYNMDpmA8vffg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-numeric-separator": "^7.10.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-rest-spread": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.22.15.tgz", + "integrity": "sha512-fEB+I1+gAmfAyxZcX1+ZUwLeAuuf8VIg67CTznZE0MqVFumWkh8xWtn58I4dxdVf080wn7gzWoF8vndOViJe9Q==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.22.9", + "@babel/helper-compilation-targets": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-transform-parameters": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-super": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.22.5.tgz", + "integrity": "sha512-klXqyaT9trSjIUrcsYIfETAzmOEZL3cBYqOYLJxBHfMFFggmXOv+NYSX/Jbs9mzMVESw/WycLFPRx8ba/b2Ipw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-replace-supers": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-catch-binding": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.22.11.tgz", + "integrity": "sha512-rli0WxesXUeCJnMYhzAglEjLWVDF6ahb45HuprcmQuLidBJFWjNnOzssk2kuc6e33FlLaiZhG/kUIzUMWdBKaQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-chaining": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.22.15.tgz", + "integrity": "sha512-ngQ2tBhq5vvSJw2Q2Z9i7ealNkpDMU0rGWnHPKqRZO0tzZ5tlaoz4hDvhXioOoaE0X2vfNss1djwg0DXlfu30A==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", + "@babel/plugin-syntax-optional-chaining": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-parameters": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.22.15.tgz", + "integrity": "sha512-hjk7qKIqhyzhhUvRT683TYQOFa/4cQKwQy7ALvTpODswN40MljzNDa0YldevS6tGbxwaEKVn502JmY0dP7qEtQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-methods": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.22.5.tgz", + "integrity": "sha512-PPjh4gyrQnGe97JTalgRGMuU4icsZFnWkzicB/fUtzlKUqvsWBKEpPPfr5a2JiyirZkHxnAqkQMO5Z5B2kK3fA==", + "dev": true, + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-property-in-object": { + "version": "7.22.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.22.11.tgz", + "integrity": "sha512-sSCbqZDBKHetvjSwpyWzhuHkmW5RummxJBVbYLkGkaiTOWGxml7SXt0iWa03bzxFIx7wOj3g/ILRd0RcJKBeSQ==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-create-class-features-plugin": "^7.22.11", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-property-literals": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.22.5.tgz", + "integrity": "sha512-TiOArgddK3mK/x1Qwf5hay2pxI6wCZnvQqrFSqbtg1GLl2JcNMitVH/YnqjP+M31pLUeTfzY1HAXFDnUBV30rQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regenerator": { + "version": "7.22.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.22.10.tgz", + "integrity": "sha512-F28b1mDt8KcT5bUyJc/U9nwzw6cV+UmTeRlXYIl2TNqMMJif0Jeey9/RQ3C4NOd2zp0/TRsDns9ttj2L523rsw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "regenerator-transform": "^0.15.2" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-reserved-words": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.22.5.tgz", + "integrity": "sha512-DTtGKFRQUDm8svigJzZHzb/2xatPc6TzNvAIJ5GqOKDsGFYgAskjRulbR/vGsPKq3OPqtexnz327qYpP57RFyA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-shorthand-properties": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.22.5.tgz", + "integrity": "sha512-vM4fq9IXHscXVKzDv5itkO1X52SmdFBFcMIBZ2FRn2nqVYqw6dBexUgMvAjHW+KXpPPViD/Yo3GrDEBaRC0QYA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-spread": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.22.5.tgz", + "integrity": "sha512-5ZzDQIGyvN4w8+dMmpohL6MBo+l2G7tfC/O2Dg7/hjpgeWvUx8FzfeOKxGog9IimPa4YekaQ9PlDqTLOljkcxg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-sticky-regex": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.22.5.tgz", + "integrity": "sha512-zf7LuNpHG0iEeiyCNwX4j3gDg1jgt1k3ZdXBKbZSoA3BbGQGvMiSvfbZRR3Dr3aeJe3ooWFZxOOG3IRStYp2Bw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-template-literals": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.22.5.tgz", + "integrity": "sha512-5ciOehRNf+EyUeewo8NkbQiUs4d6ZxiHo6BcBcnFlgiJfu16q0bQUw9Jvo0b0gBKFG1SMhDSjeKXSYuJLeFSMA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typeof-symbol": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.22.5.tgz", + "integrity": "sha512-bYkI5lMzL4kPii4HHEEChkD0rkc+nvnlR6+o/qdqR6zrm0Sv/nodmyLhlq2DO0YKLUNd2VePmPRjJXSBh9OIdA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typescript": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.22.15.tgz", + "integrity": "sha512-1uirS0TnijxvQLnlv5wQBwOX3E1wCFX7ITv+9pBV2wKEk4K+M5tqDaoNXnTH8tjEIYHLO98MwiTWO04Ggz4XuA==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-create-class-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-typescript": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-escapes": { + "version": "7.22.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.22.10.tgz", + "integrity": "sha512-lRfaRKGZCBqDlRU3UIFovdp9c9mEvlylmpod0/OatICsSfuQ9YFthRo1tpTkGsklEefZdqlEFdY4A2dwTb6ohg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-property-regex": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.22.5.tgz", + "integrity": "sha512-HCCIb+CbJIAE6sXn5CjFQXMwkCClcOfPCzTlilJ8cUatfzwHlWQkbtV0zD338u9dZskwvuOYTuuaMaA8J5EI5A==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-regex": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.22.5.tgz", + "integrity": "sha512-028laaOKptN5vHJf9/Arr/HiJekMd41hOEZYvNsrsXqJ7YPYuX2bQxh31fkZzGmq3YqHRJzYFFAVYvKfMPKqyg==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-sets-regex": { + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.22.5.tgz", + "integrity": "sha512-lhMfi4FC15j13eKrh3DnYHjpGj6UKQHtNKTbtc1igvAhRy4+kLhV07OpLcsN0VgDEw/MjAvJO4BdMJsHwMhzCg==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/preset-env": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.22.20.tgz", + "integrity": "sha512-11MY04gGC4kSzlPHRfvVkNAZhUxOvm7DCJ37hPDnUENwe06npjIRAfInEMTGSb4LZK5ZgDFkv5hw0lGebHeTyg==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.22.20", + "@babel/helper-compilation-targets": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-validator-option": "^7.22.15", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.22.15", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.22.15", + "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3", + "@babel/plugin-syntax-import-assertions": "^7.22.5", + "@babel/plugin-syntax-import-attributes": "^7.22.5", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5", + "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", + "@babel/plugin-transform-arrow-functions": "^7.22.5", + "@babel/plugin-transform-async-generator-functions": "^7.22.15", + "@babel/plugin-transform-async-to-generator": "^7.22.5", + "@babel/plugin-transform-block-scoped-functions": "^7.22.5", + "@babel/plugin-transform-block-scoping": "^7.22.15", + "@babel/plugin-transform-class-properties": "^7.22.5", + "@babel/plugin-transform-class-static-block": "^7.22.11", + "@babel/plugin-transform-classes": "^7.22.15", + "@babel/plugin-transform-computed-properties": "^7.22.5", + "@babel/plugin-transform-destructuring": "^7.22.15", + "@babel/plugin-transform-dotall-regex": "^7.22.5", + "@babel/plugin-transform-duplicate-keys": "^7.22.5", + "@babel/plugin-transform-dynamic-import": "^7.22.11", + "@babel/plugin-transform-exponentiation-operator": "^7.22.5", + "@babel/plugin-transform-export-namespace-from": "^7.22.11", + "@babel/plugin-transform-for-of": "^7.22.15", + "@babel/plugin-transform-function-name": "^7.22.5", + "@babel/plugin-transform-json-strings": "^7.22.11", + "@babel/plugin-transform-literals": "^7.22.5", + "@babel/plugin-transform-logical-assignment-operators": "^7.22.11", + "@babel/plugin-transform-member-expression-literals": "^7.22.5", + "@babel/plugin-transform-modules-amd": "^7.22.5", + "@babel/plugin-transform-modules-commonjs": "^7.22.15", + "@babel/plugin-transform-modules-systemjs": "^7.22.11", + "@babel/plugin-transform-modules-umd": "^7.22.5", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.22.5", + "@babel/plugin-transform-new-target": "^7.22.5", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.22.11", + "@babel/plugin-transform-numeric-separator": "^7.22.11", + "@babel/plugin-transform-object-rest-spread": "^7.22.15", + "@babel/plugin-transform-object-super": "^7.22.5", + "@babel/plugin-transform-optional-catch-binding": "^7.22.11", + "@babel/plugin-transform-optional-chaining": "^7.22.15", + "@babel/plugin-transform-parameters": "^7.22.15", + "@babel/plugin-transform-private-methods": "^7.22.5", + "@babel/plugin-transform-private-property-in-object": "^7.22.11", + "@babel/plugin-transform-property-literals": "^7.22.5", + "@babel/plugin-transform-regenerator": "^7.22.10", + "@babel/plugin-transform-reserved-words": "^7.22.5", + "@babel/plugin-transform-shorthand-properties": "^7.22.5", + "@babel/plugin-transform-spread": "^7.22.5", + "@babel/plugin-transform-sticky-regex": "^7.22.5", + "@babel/plugin-transform-template-literals": "^7.22.5", + "@babel/plugin-transform-typeof-symbol": "^7.22.5", + "@babel/plugin-transform-unicode-escapes": "^7.22.10", + "@babel/plugin-transform-unicode-property-regex": "^7.22.5", + "@babel/plugin-transform-unicode-regex": "^7.22.5", + "@babel/plugin-transform-unicode-sets-regex": "^7.22.5", + "@babel/preset-modules": "0.1.6-no-external-plugins", + "@babel/types": "^7.22.19", + "babel-plugin-polyfill-corejs2": "^0.4.5", + "babel-plugin-polyfill-corejs3": "^0.8.3", + "babel-plugin-polyfill-regenerator": "^0.5.2", + "core-js-compat": "^3.31.0", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-modules": { + "version": "0.1.6-no-external-plugins", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz", + "integrity": "sha512-HrcgcIESLm9aIR842yhJ5RWan/gebQUJ6E/E5+rf0y9o6oj7w0Br+sWuL6kEQ/o/AdfvR1Je9jG18/gnpwjEyA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/preset-typescript": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.22.15.tgz", + "integrity": "sha512-HblhNmh6yM+cU4VwbBRpxFhxsTdfS1zsvH9W+gEjD0ARV9+8B4sNfpI6GuhePti84nuvhiwKS539jKPFHskA9A==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-validator-option": "^7.22.15", + "@babel/plugin-syntax-jsx": "^7.22.5", + "@babel/plugin-transform-modules-commonjs": "^7.22.15", + "@babel/plugin-transform-typescript": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/regjsgen": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@babel/regjsgen/-/regjsgen-0.8.0.tgz", + "integrity": "sha512-x/rqGMdzj+fWZvCOYForTghzbtqPDZ5gPwaoNGHdgDfF2QA/XZbCBp4Moo5scrkAMPhB7z26XM/AaHuIJdgauA==", + "dev": true + }, + "node_modules/@babel/runtime": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.15.tgz", + "integrity": "sha512-T0O+aa+4w0u06iNmapipJXMV4HoUir03hpx3/YqXXhu9xim3w+dVphjFWl1OH8NbZHw5Lbm9k45drDkgq2VNNA==", + "dev": true, + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.22.20.tgz", + "integrity": "sha512-eU260mPZbU7mZ0N+X10pxXhQFMGTeLb9eFS0mxehS8HZp9o1uSnFeWQuG1UPrlxgA7QoUzFhOnilHDp0AXCyHw==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.22.13", + "@babel/generator": "^7.22.15", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.22.5", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.22.16", + "@babel/types": "^7.22.19", + "debug": "^4.1.0", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.22.19", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.22.19.tgz", + "integrity": "sha512-P7LAw/LbojPzkgp5oznjE6tQEIWbp4PkkfrZDINTro9zgBRtI324/EYsiSI7lhPbpIQ+DCeR2NNmMWANGGfZsg==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.19", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@discoveryjs/json-ext": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz", + "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==", + "dev": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", + "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.8.1.tgz", + "integrity": "sha512-PWiOzLIUAjN/w5K17PoF4n6sKBw0gqLHPhywmYHP4t1VFQQVYeb1yWsJwnMVEMl3tUHME7X/SJPZLmtG7XBDxQ==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.2.tgz", + "integrity": "sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g==", + "dev": true, + "peer": true, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "13.22.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.22.0.tgz", + "integrity": "sha512-H1Ddc/PbZHTDVJSnj8kWptIRSD6AM3pK+mKytuIVF4uoBV7rshFlhhvA58ceJ5wp3Er58w6zj7bykMpYXt3ETw==", + "dev": true, + "peer": true, + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/eslintrc/node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "8.49.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.49.0.tgz", + "integrity": "sha512-1S8uAY/MTJqVx0SC4epBq+N2yhuwtNwLbJYNZyhL2pO1ZVKn5HFXav5T41Ryzy9K9V7ZId2JB2oy/W4aCd9/2w==", + "dev": true, + "peer": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.11.11", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.11.tgz", + "integrity": "sha512-N2brEuAadi0CcdeMXUkhbZB84eskAc8MEX1By6qEchoVywSgXPIjou4rYsl0V3Hj0ZnuGycGCjdNgockbzeWNA==", + "dev": true, + "peer": true, + "dependencies": { + "@humanwhocodes/object-schema": "^1.2.1", + "debug": "^4.1.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", + "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", + "dev": true, + "peer": true + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.5.tgz", + "integrity": "sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", + "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@sinonjs/commons": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.6.tgz", + "integrity": "sha512-Ky+XkAkqPZSm3NLBeUng77EBQl3cmeJhITaGHdYH8kjVB+aun3S4XBRti2zt17mtt0mIUDiNxYeoJm6drVvBJQ==", "dev": true, - "requires": { + "dependencies": { "type-detect": "4.0.8" } }, - "@sinonjs/fake-timers": { - "version": "6.0.1", - "integrity": "sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA==", + "node_modules/@sinonjs/fake-timers": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-8.1.0.tgz", + "integrity": "sha512-OAPJUAtgeINhh/TAlUID4QTs53Njm7xzddaVlEs/SXwgtiD1tW22zAB/W1wdqfrpmikgaWQ9Fw6Ws+hsiRm5Vg==", "dev": true, - "requires": { + "dependencies": { "@sinonjs/commons": "^1.7.0" } }, - "@sinonjs/samsam": { - "version": "5.3.1", - "integrity": "sha512-1Hc0b1TtyfBu8ixF/tpfSHTVWKwCBLY4QJbkgnE7HcwyvT2xArDxb4K7dMgqRm3szI+LJbzmW/s4xxEhv6hwDg==", + "node_modules/@sinonjs/samsam": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-6.1.3.tgz", + "integrity": "sha512-nhOb2dWPeb1sd3IQXL/dVPnKHDOAFfvichtBf4xV00/rU1QbPCQqKMbvIheIjqwVjh7qIgf2AHTHi391yMOMpQ==", "dev": true, - "requires": { + "dependencies": { "@sinonjs/commons": "^1.6.0", "lodash.get": "^4.4.2", "type-detect": "^4.0.8" } }, - "@sinonjs/text-encoding": { - "version": "0.7.1", - "integrity": "sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==", + "node_modules/@sinonjs/text-encoding": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz", + "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==", "dev": true }, - "@types/expect": { - "version": "1.20.4", - "integrity": "sha512-Q5Vn3yjTDyCMV50TB6VRIbQNxSE4OmZR86VSbGaNpfUolm0iePBB4KdEEHmxoY5sT2+2DIvXW0rvMDP2nHZ4Mg==", + "node_modules/@types/eslint": { + "version": "8.44.2", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.2.tgz", + "integrity": "sha512-sdPRb9K6iL5XZOmBubg8yiFp5yS/JdUDQsq5e6h95km91MCYMuvp7mh1fjPEYUhvHepKpZOjnEaMBR4PxjWDzg==", + "dev": true, + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.4", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.4.tgz", + "integrity": "sha512-9K4zoImiZc3HlIp6AVUDE4CWYx22a+lhSZMYNpbjW04+YF0KWj4pJXnEMjdnFTiQibFFmElcsasJXDbdI/EPhA==", + "dev": true, + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.1.tgz", + "integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==", "dev": true }, - "@types/node": { - "version": "14.17.21", - "integrity": "sha512-zv8ukKci1mrILYiQOwGSV4FpkZhyxQtuFWGya2GujWg+zVAeRQ4qbaMmWp9vb9889CFA8JECH7lkwCL6Ygg8kA==", + "node_modules/@types/json-schema": { + "version": "7.0.13", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.13.tgz", + "integrity": "sha512-RbSSoHliUbnXj3ny0CNFOoxrIDV6SUGyStHsvDqosw6CkdPV8TtWGlfecuK4ToyMEAql6pzNxgCFKanovUzlgQ==", "dev": true }, - "@types/vinyl": { - "version": "2.0.6", - "integrity": "sha512-ayJ0iOCDNHnKpKTgBG6Q6JOnHTj9zFta+3j2b8Ejza0e4cvRyMn0ZoLEmbPrTHe5YYRlDYPvPWVdV4cTaRyH7g==", + "node_modules/@types/node": { + "version": "20.6.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.6.3.tgz", + "integrity": "sha512-HksnYH4Ljr4VQgEy2lTStbCKv/P590tmPe5HqOnv9Gprffgv5WXAY+Y5Gqniu0GGqeTCUdBnzC3QSrzPkBkAMA==", + "dev": true + }, + "node_modules/@types/semver": { + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.2.tgz", + "integrity": "sha512-7aqorHYgdNO4DM36stTiGO3DvKoex9TQRwsJU6vMaFGyqpBA1MNZkz+PG3gaNUPpTAOYhT1WR7M1JyA3fbS9Cw==", + "dev": true + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", + "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.4.0", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/type-utils": "5.62.0", + "@typescript-eslint/utils": "5.62.0", + "debug": "^4.3.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "natural-compare-lite": "^1.4.0", + "semver": "^7.3.7", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^5.0.0", + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, - "requires": { - "@types/expect": "^1.20.4", - "@types/node": "*" + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" } }, - "abab": { - "version": "2.0.5", - "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", + "node_modules/@typescript-eslint/eslint-plugin/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "abbrev": { - "version": "1.0.9", - "integrity": "sha1-kbR5JYinc4wl813W9jdSovh3YTU=", + "node_modules/@typescript-eslint/parser": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", + "dev": true, + "dependencies": { + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", + "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", + "dev": true, + "dependencies": { + "@typescript-eslint/typescript-estree": "5.62.0", + "@typescript-eslint/utils": "5.62.0", + "debug": "^4.3.4", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/types": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "acorn": { - "version": "5.7.4", - "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", + "node_modules/@typescript-eslint/utils": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz", + "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@types/json-schema": "^7.0.9", + "@types/semver": "^7.3.12", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "eslint-scope": "^5.1.1", + "semver": "^7.3.7" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "acorn-globals": { - "version": "4.3.4", - "integrity": "sha512-clfQEh21R+D0leSbUdWf3OcfqyaCSAQ8Ryq00bofSekfr9W8u1jyYZo6ir0xu9Gtcf7BjcHJpnbZH7JOCpP60A==", + "node_modules/@typescript-eslint/visitor-keys": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", "dev": true, - "requires": { - "acorn": "^6.0.1", - "acorn-walk": "^6.0.1" + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "eslint-visitor-keys": "^3.3.0" }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz", + "integrity": "sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==", + "dev": true, "dependencies": { - "acorn": { - "version": "6.4.2", - "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", - "dev": true - } + "@webassemblyjs/helper-numbers": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6" } }, - "acorn-walk": { - "version": "6.2.0", - "integrity": "sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA==", + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz", + "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==", "dev": true }, - "ajv": { - "version": "6.12.6", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz", + "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.6.tgz", + "integrity": "sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz", + "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==", "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.6", + "@webassemblyjs/helper-api-error": "1.11.6", + "@xtuc/long": "4.2.2" } }, - "amdefine": { - "version": "1.0.1", - "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz", + "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.6.tgz", + "integrity": "sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==", "dev": true, - "optional": true + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-buffer": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/wasm-gen": "1.11.6" + } }, - "ansi-colors": { - "version": "1.1.0", - "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==", + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz", + "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==", "dev": true, - "requires": { - "ansi-wrap": "^0.1.0" + "dependencies": { + "@xtuc/ieee754": "^1.2.0" } }, - "ansi-cyan": { - "version": "0.1.1", - "integrity": "sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=", + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz", + "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==", "dev": true, - "requires": { - "ansi-wrap": "0.1.0" + "dependencies": { + "@xtuc/long": "4.2.2" } }, - "ansi-gray": { - "version": "0.1.1", - "integrity": "sha1-KWLPVOyXksSFEKPetSRDaGHvclE=", + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz", + "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==", + "dev": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.6.tgz", + "integrity": "sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==", "dev": true, - "requires": { - "ansi-wrap": "0.1.0" + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-buffer": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/helper-wasm-section": "1.11.6", + "@webassemblyjs/wasm-gen": "1.11.6", + "@webassemblyjs/wasm-opt": "1.11.6", + "@webassemblyjs/wasm-parser": "1.11.6", + "@webassemblyjs/wast-printer": "1.11.6" } }, - "ansi-red": { - "version": "0.1.1", - "integrity": "sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=", + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.6.tgz", + "integrity": "sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==", "dev": true, - "requires": { - "ansi-wrap": "0.1.0" + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" } }, - "ansi-regex": { - "version": "2.1.1", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.6.tgz", + "integrity": "sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-buffer": "1.11.6", + "@webassemblyjs/wasm-gen": "1.11.6", + "@webassemblyjs/wasm-parser": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.6.tgz", + "integrity": "sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-api-error": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.6.tgz", + "integrity": "sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webpack-cli/configtest": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.2.0.tgz", + "integrity": "sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg==", + "dev": true, + "peerDependencies": { + "webpack": "4.x.x || 5.x.x", + "webpack-cli": "4.x.x" + } + }, + "node_modules/@webpack-cli/info": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.5.0.tgz", + "integrity": "sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==", + "dev": true, + "dependencies": { + "envinfo": "^7.7.3" + }, + "peerDependencies": { + "webpack-cli": "4.x.x" + } + }, + "node_modules/@webpack-cli/serve": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.7.0.tgz", + "integrity": "sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==", + "dev": true, + "peerDependencies": { + "webpack-cli": "4.x.x" + }, + "peerDependenciesMeta": { + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", "dev": true }, - "ansi-styles": { - "version": "3.2.1", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "node_modules/abab": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", + "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", + "dev": true + }, + "node_modules/acorn": { + "version": "8.10.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", + "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", "dev": true, - "requires": { - "color-convert": "^1.9.0" + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-globals": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-4.3.4.tgz", + "integrity": "sha512-clfQEh21R+D0leSbUdWf3OcfqyaCSAQ8Ryq00bofSekfr9W8u1jyYZo6ir0xu9Gtcf7BjcHJpnbZH7JOCpP60A==", + "dev": true, + "dependencies": { + "acorn": "^6.0.1", + "acorn-walk": "^6.0.1" + } + }, + "node_modules/acorn-globals/node_modules/acorn": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.2.tgz", + "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-assertions": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz", + "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==", + "dev": true, + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "peer": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/acorn-walk": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-6.2.0.tgz", + "integrity": "sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "dev": true, + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" } }, - "ansi-wrap": { - "version": "0.1.0", - "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", - "dev": true - }, - "anymatch": { - "version": "2.0.0", - "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", "dev": true, - "requires": { - "micromatch": "^3.1.4", - "normalize-path": "^2.1.1" - }, "dependencies": { - "normalize-path": { - "version": "2.1.1", - "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", - "dev": true, - "requires": { - "remove-trailing-separator": "^1.0.1" - } + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true } } }, - "append-buffer": { - "version": "1.0.2", - "integrity": "sha1-2CIM9GYIFSXv6lBhTz3mUU36WPE=", + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "requires": { - "buffer-equal": "^1.0.0" + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" } }, - "archy": { + "node_modules/ajv-formats/node_modules/json-schema-traverse": { "version": "1.0.0", - "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "dev": true }, - "argparse": { - "version": "1.0.10", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", "dev": true, - "requires": { - "sprintf-js": "~1.0.2" + "peerDependencies": { + "ajv": "^6.9.1" } }, - "arr-diff": { - "version": "4.0.0", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true - }, - "arr-filter": { - "version": "1.1.2", - "integrity": "sha1-Q/3d0JHo7xGqTEXZzcGOLf8XEe4=", + "node_modules/ansi-colors": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", "dev": true, - "requires": { - "make-iterator": "^1.0.0" + "engines": { + "node": ">=6" } }, - "arr-flatten": { - "version": "1.1.0", - "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", - "dev": true - }, - "arr-map": { - "version": "2.0.2", - "integrity": "sha1-Onc0X/wc814qkYJWAfnljy4kysQ=", + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, - "requires": { - "make-iterator": "^1.0.0" + "engines": { + "node": ">=8" } }, - "arr-union": { - "version": "3.1.0", - "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", - "dev": true - }, - "array-each": { - "version": "1.0.1", - "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", - "dev": true - }, - "array-equal": { - "version": "1.0.0", - "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", - "dev": true - }, - "array-initial": { - "version": "1.1.0", - "integrity": "sha1-L6dLJnOTccOUe9enrcc74zSz15U=", + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, - "requires": { - "array-slice": "^1.0.0", - "is-number": "^4.0.0" - }, "dependencies": { - "is-number": { - "version": "4.0.0", - "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", - "dev": true - } + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" } }, - "array-last": { - "version": "1.3.0", - "integrity": "sha512-eOCut5rXlI6aCOS7Z7kCplKRKyiFQ6dHFBem4PwlwKeNFk2/XxTrhRh5T9PyaEWGy/NHTZWbY+nsZlNFJu9rYg==", + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", "dev": true, - "requires": { - "is-number": "^4.0.0" + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-transform": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-2.0.0.tgz", + "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", + "dev": true, "dependencies": { - "is-number": { - "version": "4.0.0", - "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", - "dev": true - } + "default-require-extensions": "^3.0.0" + }, + "engines": { + "node": ">=8" } }, - "array-slice": { - "version": "1.1.0", - "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==", + "node_modules/archy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", + "integrity": "sha512-Xg+9RwCg/0p32teKdGMPTPnVXKD0w3DfHnFTficozsAgsvq2XenPJq/MYpzzQ/v8zrOyJn6Ds39VA4JIDwFfqw==", + "dev": true + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, - "array-sort": { + "node_modules/array-equal": { "version": "1.0.0", - "integrity": "sha512-ihLeJkonmdiAsD7vpgN3CRcx2J2S0TiYW+IS/5zHBI7mKUq3ySvBdzzBfD236ubDBQFiiyG3SWCPc+msQ9KoYg==", + "resolved": "https://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", + "integrity": "sha512-H3LU5RLiSsGXPhN+Nipar0iR0IofH+8r89G2y1tBKxQ/agagKyAjhkAFDRBfodP2caPrNKHpAWNIM/c9yeL7uA==", + "dev": true + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", "dev": true, - "requires": { - "default-compare": "^1.0.0", - "get-value": "^2.0.6", - "kind-of": "^5.0.2" - }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", - "dev": true - } + "engines": { + "node": ">=8" } }, - "array-unique": { - "version": "0.3.2", - "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", - "dev": true - }, - "asn1": { - "version": "0.2.4", - "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", "dev": true, - "requires": { + "dependencies": { "safer-buffer": "~2.1.0" } }, - "assert-plus": { + "node_modules/assert-plus": { "version": "1.0.0", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", - "dev": true + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "dev": true, + "engines": { + "node": ">=0.8" + } }, - "assertion-error": { + "node_modules/assertion-error": { "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", - "dev": true + "dev": true, + "engines": { + "node": "*" + } }, - "assign-symbols": { - "version": "1.0.0", - "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "node_modules/async-limiter": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz", + "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==", "dev": true }, - "async": { - "version": "1.5.2", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "dev": true }, - "async-done": { - "version": "1.3.2", - "integrity": "sha512-uYkTP8dw2og1tu1nmza1n1CMW0qb8gWWlwqMmLb7MhBVs4BXrFziT6HXUd+/RlRA/i4H9AkofYloUbs1fwMqlw==", + "node_modules/aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==", "dev": true, - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.2", - "process-nextick-args": "^2.0.0", - "stream-exhaust": "^1.0.1" + "engines": { + "node": "*" } }, - "async-each": { - "version": "1.0.3", - "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==", - "dev": true - }, - "async-limiter": { - "version": "1.0.1", - "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==", + "node_modules/aws4": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.12.0.tgz", + "integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg==", "dev": true }, - "async-settle": { - "version": "1.0.0", - "integrity": "sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs=", + "node_modules/babel": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel/-/babel-6.23.0.tgz", + "integrity": "sha512-ZDcCaI8Vlct8PJ3DvmyqUz+5X2Ylz3ZuuItBe/74yXosk2dwyVo/aN7MCJ8HJzhnnJ+6yP4o+lDgG9MBe91DLA==", + "deprecated": "In 6.x, the babel package has been deprecated in favor of babel-cli. Check https://opencollective.com/babel to support the Babel maintainers", "dev": true, - "requires": { - "async-done": "^1.2.2" + "bin": { + "babel": "lib/cli.js", + "babel-external-helpers": "lib/cli.js", + "babel-node": "lib/cli.js" } }, - "asynckit": { - "version": "0.4.0", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", - "dev": true - }, - "atob": { - "version": "2.1.2", - "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", - "dev": true + "node_modules/babel-loader": { + "version": "9.1.3", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-9.1.3.tgz", + "integrity": "sha512-xG3ST4DglodGf8qSwv0MdeWLhrDsw/32QMdTO5T1ZIp9gQur0HkCyFs7Awskr10JKXFXwpAhiCuYX5oGXnRGbw==", + "dev": true, + "dependencies": { + "find-cache-dir": "^4.0.0", + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 14.15.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0", + "webpack": ">=5" + } }, - "aws-sign2": { - "version": "0.7.0", - "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", - "dev": true + "node_modules/babel-plugin-polyfill-corejs2": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.5.tgz", + "integrity": "sha512-19hwUH5FKl49JEsvyTcoHakh6BE0wgXLLptIyKZ3PijHc/Ci521wygORCUCCred+E/twuqRyAkE02BAWPmsHOg==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.22.6", + "@babel/helper-define-polyfill-provider": "^0.4.2", + "semver": "^6.3.1" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } }, - "aws4": { - "version": "1.11.0", - "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", - "dev": true + "node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.8.3.tgz", + "integrity": "sha512-z41XaniZL26WLrvjy7soabMXrfPWARN25PZoriDEiLMxAp50AUW3t35BGQUMg5xK3UrpVTtagIDklxYa+MhiNA==", + "dev": true, + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.4.2", + "core-js-compat": "^3.31.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } }, - "bach": { - "version": "1.2.0", - "integrity": "sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA=", + "node_modules/babel-plugin-polyfill-regenerator": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.5.2.tgz", + "integrity": "sha512-tAlOptU0Xj34V1Y2PNTL4Y0FOJMDB6bZmoW39FeCQIhigGLkqu3Fj6uiXpxIf6Ij274ENdYx64y6Au+ZKlb1IA==", "dev": true, - "requires": { - "arr-filter": "^1.1.1", - "arr-flatten": "^1.0.1", - "arr-map": "^2.0.0", - "array-each": "^1.0.0", - "array-initial": "^1.0.0", - "array-last": "^1.1.1", - "async-done": "^1.2.2", - "async-settle": "^1.0.0", - "now-and-later": "^2.0.0" + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.4.2" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" } }, - "balanced-match": { + "node_modules/balanced-match": { "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, - "base": { - "version": "0.11.2", - "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", - "dev": true, - "requires": { - "cache-base": "^1.0.1", - "class-utils": "^0.3.5", - "component-emitter": "^1.2.1", - "define-property": "^1.0.0", - "isobject": "^3.0.1", - "mixin-deep": "^1.2.0", - "pascalcase": "^0.1.1" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "dev": true, - "requires": { - "is-descriptor": "^1.0.0" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-descriptor": { - "version": "1.0.2", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "^1.0.0", - "is-data-descriptor": "^1.0.0", - "kind-of": "^6.0.2" - } - } - } - }, - "bcrypt-pbkdf": { + "node_modules/bcrypt-pbkdf": { "version": "1.0.2", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", "dev": true, - "requires": { + "dependencies": { "tweetnacl": "^0.14.3" } }, - "binary-extensions": { - "version": "1.13.1", - "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==", - "dev": true - }, - "binaryextensions": { - "version": "2.3.0", - "integrity": "sha512-nAihlQsYGyc5Bwq6+EsubvANYGExeJKHDO3RjnvwU042fawQTQfM3Kxn7IHUXQOz4bzfwsGYYHGSvXyW4zOGLg==", - "dev": true - }, - "bindings": { - "version": "1.5.0", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", "dev": true, - "optional": true, - "requires": { - "file-uri-to-path": "1.0.0" + "engines": { + "node": ">=8" } }, - "brace-expansion": { + "node_modules/brace-expansion": { "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, - "requires": { + "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, - "braces": { - "version": "2.3.2", - "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", - "dev": true, - "requires": { - "arr-flatten": "^1.1.0", - "array-unique": "^0.3.2", - "extend-shallow": "^2.0.1", - "fill-range": "^4.0.0", - "isobject": "^3.0.1", - "repeat-element": "^1.1.2", - "snapdragon": "^0.8.1", - "snapdragon-node": "^2.0.1", - "split-string": "^3.0.2", - "to-regex": "^3.0.1" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - } + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" } }, - "browser-process-hrtime": { + "node_modules/browser-process-hrtime": { "version": "1.0.0", + "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, - "browser-stdout": { + "node_modules/browser-stdout": { "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", "dev": true }, - "buffer-equal": { - "version": "1.0.0", - "integrity": "sha1-WWFrSYME1Var1GaWayLu2j7KX74=", - "dev": true + "node_modules/browserslist": { + "version": "4.21.11", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.11.tgz", + "integrity": "sha512-xn1UXOKUz7DjdGlg9RrUr0GGiWzI97UQJnugHtH0OLDfJB7jMgoIkYvRIEO1l9EeEERVqeqLYOcFBW9ldjypbQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "caniuse-lite": "^1.0.30001538", + "electron-to-chromium": "^1.4.526", + "node-releases": "^2.0.13", + "update-browserslist-db": "^1.0.13" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } }, - "buffer-from": { + "node_modules/buffer-from": { "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, - "cache-base": { - "version": "1.0.1", - "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "node_modules/caching-transform": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/caching-transform/-/caching-transform-4.0.0.tgz", + "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", "dev": true, - "requires": { - "collection-visit": "^1.0.0", - "component-emitter": "^1.2.1", - "get-value": "^2.0.6", - "has-value": "^1.0.0", - "isobject": "^3.0.1", - "set-value": "^2.0.0", - "to-object-path": "^0.3.0", - "union-value": "^1.0.0", - "unset-value": "^1.0.0" + "dependencies": { + "hasha": "^5.0.0", + "make-dir": "^3.0.0", + "package-hash": "^4.0.0", + "write-file-atomic": "^3.0.0" + }, + "engines": { + "node": ">=8" } }, - "call-bind": { - "version": "1.0.2", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, - "requires": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" + "peer": true, + "engines": { + "node": ">=6" } }, - "camelcase": { - "version": "3.0.0", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", - "dev": true + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001538", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001538.tgz", + "integrity": "sha512-HWJnhnID+0YMtGlzcp3T9drmBJUVDchPJ08tpUGFLs9CYlwWPH2uLgpHn8fND5pCgXVtnGS3H4QR9XLMHVNkHw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] }, - "caseless": { + "node_modules/caseless": { "version": "0.12.0", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", "dev": true }, - "chai": { - "version": "4.3.4", - "integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==", + "node_modules/chai": { + "version": "4.3.8", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.8.tgz", + "integrity": "sha512-vX4YvVVtxlfSZ2VecZgFUTU5qPCYsobVI2O9FmwEXBhDigYGQA6jRXCycIs1yJnnWbZ6/+a2zNIF5DfVCcJBFQ==", "dev": true, - "requires": { + "dependencies": { "assertion-error": "^1.1.0", "check-error": "^1.0.2", - "deep-eql": "^3.0.1", + "deep-eql": "^4.1.2", "get-func-name": "^2.0.0", + "loupe": "^2.3.1", "pathval": "^1.1.1", "type-detect": "^4.0.5" + }, + "engines": { + "node": ">=4" } }, - "chalk": { + "node_modules/chalk": { "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, - "requires": { + "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" }, - "dependencies": { - "has-flag": { - "version": "3.0.0", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } + "engines": { + "node": ">=4" } }, - "check-error": { + "node_modules/check-error": { "version": "1.0.2", - "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", - "dev": true - }, - "chokidar": { - "version": "2.1.8", - "integrity": "sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg==", - "dev": true, - "requires": { - "anymatch": "^2.0.0", - "async-each": "^1.0.1", - "braces": "^2.3.2", - "fsevents": "^1.2.7", - "glob-parent": "^3.1.0", - "inherits": "^2.0.3", - "is-binary-path": "^1.0.0", - "is-glob": "^4.0.0", - "normalize-path": "^3.0.0", - "path-is-absolute": "^1.0.0", - "readdirp": "^2.2.1", - "upath": "^1.1.1" + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "dev": true, + "engines": { + "node": "*" } }, - "class-utils": { - "version": "0.3.6", - "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", "dev": true, - "requires": { - "arr-union": "^3.1.0", - "define-property": "^0.2.5", - "isobject": "^3.0.0", - "static-extend": "^0.1.1" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" } }, - "cli": { - "version": "1.0.1", - "integrity": "sha1-IoF1NPJL+klQw01TLUjsvGIbjBQ=", + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, - "requires": { - "exit": "0.1.2", - "glob": "^7.1.1" + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" } }, - "cliui": { - "version": "3.2.0", - "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", + "node_modules/chrome-trace-event": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", + "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", "dev": true, - "requires": { - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1", - "wrap-ansi": "^2.0.0" + "engines": { + "node": ">=6.0" } }, - "clone": { - "version": "2.1.2", - "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", - "dev": true - }, - "clone-buffer": { - "version": "1.0.0", - "integrity": "sha1-4+JbIHrE5wGvch4staFnksrD3Fg=", - "dev": true - }, - "clone-stats": { - "version": "1.0.0", - "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", - "dev": true - }, - "cloneable-readable": { - "version": "1.1.3", - "integrity": "sha512-2EF8zTQOxYq70Y4XKtorQupqF0m49MBz2/yf5Bj+MHjvpG3Hy7sImifnqD6UA+TKYxeSV+u6qqQPawN5UvnpKQ==", + "node_modules/clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", "dev": true, - "requires": { - "inherits": "^2.0.1", - "process-nextick-args": "^2.0.0", - "readable-stream": "^2.3.5" + "engines": { + "node": ">=6" } }, - "code-point-at": { - "version": "1.1.0", - "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", - "dev": true + "node_modules/cli": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz", + "integrity": "sha512-41U72MB56TfUMGndAKK8vJ78eooOD4Z5NOL4xEfjc0c23s+6EYKXlXsmACBVclLP1yOfWCgEganVzddVrSNoTg==", + "dev": true, + "dependencies": { + "exit": "0.1.2", + "glob": "^7.1.1" + }, + "engines": { + "node": ">=0.2.5" + } }, - "collection-map": { - "version": "1.0.0", - "integrity": "sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw=", + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, - "requires": { - "arr-map": "^2.0.2", - "for-own": "^1.0.0", - "make-iterator": "^1.0.0" + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" } }, - "collection-visit": { - "version": "1.0.0", - "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "node_modules/clone-deep": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", + "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", "dev": true, - "requires": { - "map-visit": "^1.0.0", - "object-visit": "^1.0.0" + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" } }, - "color-convert": { + "node_modules/color-convert": { "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, - "requires": { + "dependencies": { "color-name": "1.1.3" } }, - "color-name": { + "node_modules/color-name": { "version": "1.1.3", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", "dev": true }, - "color-support": { - "version": "1.1.3", - "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", "dev": true }, - "combined-stream": { + "node_modules/combined-stream": { "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, - "requires": { + "dependencies": { "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" } }, - "component-emitter": { - "version": "1.3.0", - "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "dev": true }, - "concat-map": { - "version": "0.0.1", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "node_modules/common-path-prefix": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-3.0.0.tgz", + "integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==", "dev": true }, - "concat-stream": { - "version": "1.6.2", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^2.2.2", - "typedarray": "^0.0.6" - } + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true }, - "concat-with-sourcemaps": { - "version": "1.1.0", - "integrity": "sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg==", - "dev": true, - "requires": { - "source-map": "^0.6.1" - }, - "dependencies": { - "source-map": { - "version": "0.6.1", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } - } + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true }, - "console-browserify": { + "node_modules/console-browserify": { "version": "1.1.0", - "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "integrity": "sha512-duS7VP5pvfsNLDvL1O4VOEbw37AI3A4ZUQYemvDlnpGrNu9tprR7BYWpDYwC0Xia0Zxz5ZupdiIrUp0GH1aXfg==", "dev": true, - "requires": { + "dependencies": { "date-now": "^0.1.4" } }, - "convert-source-map": { - "version": "1.8.0", - "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.1" - } - }, - "copy-descriptor": { - "version": "0.1.1", - "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", "dev": true }, - "copy-props": { - "version": "2.0.5", - "integrity": "sha512-XBlx8HSqrT0ObQwmSzM7WE5k8FxTV75h1DX1Z3n6NhQ/UYYAvInWYmG06vFt7hQZArE2fuO62aihiWIVQwh1sw==", + "node_modules/core-js-compat": { + "version": "3.32.2", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.32.2.tgz", + "integrity": "sha512-+GjlguTDINOijtVRUxrQOv3kfu9rl+qPNdX2LTbJ/ZyVTuxK+ksVSAGX1nHstu4hrv1En/uPTtWgq2gI5wt4AQ==", "dev": true, - "requires": { - "each-props": "^1.3.2", - "is-plain-object": "^5.0.0" - }, "dependencies": { - "is-plain-object": { - "version": "5.0.0", - "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", - "dev": true - } + "browserslist": "^4.21.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" } }, - "core-util-is": { + "node_modules/core-util-is": { "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "dev": true }, - "cross-spawn": { + "node_modules/cross-spawn": { "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, - "requires": { + "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" }, - "dependencies": { - "which": { - "version": "2.0.2", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "requires": { - "isexe": "^2.0.0" - } - } + "engines": { + "node": ">= 8" } }, - "cssom": { + "node_modules/cssom": { "version": "0.3.8", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true }, - "cssstyle": { + "node_modules/cssstyle": { "version": "1.4.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-1.4.0.tgz", "integrity": "sha512-GBrLZYZ4X4x6/QEoBnIrqb8B/f5l4+8me2dkom/j1Gtbxy0kBv6OGzKuAsGM75bkGwGAFkt56Iwg28S3XTZgSA==", "dev": true, - "requires": { + "dependencies": { "cssom": "0.3.x" } }, - "d": { - "version": "1.0.1", - "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==", - "dev": true, - "requires": { - "es5-ext": "^0.10.50", - "type": "^1.0.1" - } - }, - "dargs": { - "version": "7.0.0", - "integrity": "sha512-2iy1EkLdlBzQGvbweYRFxmFath8+K7+AKB0TlhHWkNuH+TmovaMH/Wp7V7R4u7f4SnX3OgLsU9t1NI9ioDnUpg==", - "dev": true - }, - "dashdash": { + "node_modules/dashdash": { "version": "1.14.1", - "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", "dev": true, - "requires": { + "dependencies": { "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" } }, - "data-urls": { + "node_modules/data-urls": { "version": "1.1.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-1.1.0.tgz", "integrity": "sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==", "dev": true, - "requires": { + "dependencies": { "abab": "^2.0.0", "whatwg-mimetype": "^2.2.0", "whatwg-url": "^7.0.0" - }, + } + }, + "node_modules/data-urls/node_modules/whatwg-url": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.1.0.tgz", + "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==", + "dev": true, "dependencies": { - "whatwg-url": { - "version": "7.1.0", - "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==", - "dev": true, - "requires": { - "lodash.sortby": "^4.7.0", - "tr46": "^1.0.1", - "webidl-conversions": "^4.0.2" - } - } + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" } }, - "date-now": { + "node_modules/date-now": { "version": "0.1.4", - "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "integrity": "sha512-AsElvov3LoNB7tf5k37H2jYSB+ZZPMT5sG2QjJCcdlV5chIv6htBUBUui2IKRjgtKAKtCBN7Zbwa+MtwLjSeNw==", "dev": true }, - "debug": { - "version": "2.6.9", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, - "requires": { - "ms": "2.0.0" + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "decamelize": { + "node_modules/decamelize": { "version": "1.2.0", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - }, - "decode-uri-component": { - "version": "0.2.0", - "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", - "dev": true + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "deep-eql": { - "version": "3.0.1", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", "dev": true, - "requires": { + "dependencies": { "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" } }, - "deep-is": { + "node_modules/deep-is": { "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, - "default-compare": { - "version": "1.0.0", - "integrity": "sha512-QWfXlM0EkAbqOCbD/6HjdwT19j7WCkMyiRhWilc4H9/5h/RzTF9gv5LYh1+CmDV5d1rki6KAWLtQale0xt20eQ==", + "node_modules/default-require-extensions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-3.0.1.tgz", + "integrity": "sha512-eXTJmRbm2TIt9MgWTsOH1wEuhew6XGZcMeGKCtLedIg/NCsg1iBePXkceTdK4Fii7pzmN9tGsZhKzZ4h7O/fxw==", "dev": true, - "requires": { - "kind-of": "^5.0.2" - }, "dependencies": { - "kind-of": { - "version": "5.1.0", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", - "dev": true - } + "strip-bom": "^4.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "default-resolution": { - "version": "2.0.0", - "integrity": "sha1-vLgrqnKtebQmp2cy8aga1t8m1oQ=", - "dev": true + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } }, - "define-properties": { - "version": "1.1.3", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "node_modules/diff": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", "dev": true, - "requires": { - "object-keys": "^1.0.12" + "engines": { + "node": ">=0.3.1" } }, - "define-property": { - "version": "2.0.2", - "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", "dev": true, - "requires": { - "is-descriptor": "^1.0.2", - "isobject": "^3.0.1" - }, "dependencies": { - "is-accessor-descriptor": { - "version": "1.0.0", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-descriptor": { - "version": "1.0.2", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "^1.0.0", - "is-data-descriptor": "^1.0.0", - "kind-of": "^6.0.2" - } - } + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "delayed-stream": { - "version": "1.0.0", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", - "dev": true - }, - "detect-file": { - "version": "1.0.0", - "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", - "dev": true - }, - "diff": { - "version": "3.5.0", - "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", - "dev": true + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "peer": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } }, - "dom-serializer": { + "node_modules/dom-serializer": { "version": "0.2.2", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.2.2.tgz", "integrity": "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g==", "dev": true, - "requires": { + "dependencies": { "domelementtype": "^2.0.1", "entities": "^2.0.0" - }, - "dependencies": { - "domelementtype": { - "version": "2.2.0", - "integrity": "sha512-DtBMo82pv1dFtUmHyr48beiuq792Sxohr+8Hm9zoxklYPfa6n0Z3Byjj2IV7bmr2IyqClnqEQhfgHJJ5QF0R5A==", - "dev": true - }, - "entities": { - "version": "2.2.0", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "dev": true + } + }, + "node_modules/dom-serializer/node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" } + ] + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" } }, - "domelementtype": { + "node_modules/domelementtype": { "version": "1.3.1", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", "dev": true }, - "domexception": { + "node_modules/domexception": { "version": "1.0.1", + "resolved": "https://registry.npmjs.org/domexception/-/domexception-1.0.1.tgz", "integrity": "sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==", "dev": true, - "requires": { + "dependencies": { "webidl-conversions": "^4.0.2" } }, - "domhandler": { + "node_modules/domhandler": { "version": "2.3.0", - "integrity": "sha1-LeWaCCLVAn+r/28DLCsloqir5zg=", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.3.0.tgz", + "integrity": "sha512-q9bUwjfp7Eif8jWxxxPSykdRZAb6GkguBGSgvvCrhI9wB71W2K/Kvv4E61CF/mcCfnVJDeDWx/Vb/uAqbDj6UQ==", "dev": true, - "requires": { + "dependencies": { "domelementtype": "1" } }, - "domutils": { + "node_modules/domutils": { "version": "1.5.1", - "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha512-gSu5Oi/I+3wDENBsOWBiRK1eoGxcywYSqg3rR960/+EfY0CF4EX1VPkgHOZ3WiS/Jg2DtliF6BhWcHlfpYUcGw==", "dev": true, - "requires": { + "dependencies": { "dom-serializer": "0", "domelementtype": "1" } }, - "duplexify": { - "version": "3.7.1", - "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==", - "dev": true, - "requires": { - "end-of-stream": "^1.0.0", - "inherits": "^2.0.1", - "readable-stream": "^2.0.0", - "stream-shift": "^1.0.0" - } - }, - "each-props": { - "version": "1.3.2", - "integrity": "sha512-vV0Hem3zAGkJAyU7JSjixeU66rwdynTAa1vofCrSA5fEln+m67Az9CcnkVD776/fsN/UjIWmBDoNRS6t6G9RfA==", - "dev": true, - "requires": { - "is-plain-object": "^2.0.1", - "object.defaults": "^1.1.0" - } - }, - "ecc-jsbn": { + "node_modules/ecc-jsbn": { "version": "0.1.2", - "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", "dev": true, - "requires": { + "dependencies": { "jsbn": "~0.1.0", "safer-buffer": "^2.1.0" } }, - "emoji-regex": { - "version": "7.0.3", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "node_modules/electron-to-chromium": { + "version": "1.4.527", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.527.tgz", + "integrity": "sha512-EafxEiEDzk2aLrdbtVczylHflHdHkNrpGNHIgDyA63sUQLQVS2ayj2hPw3RsVB42qkwURH+T2OxV7kGPUuYszA==", + "dev": true + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, - "end-of-stream": { + "node_modules/end-of-stream": { "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", "dev": true, - "requires": { + "dependencies": { "once": "^1.4.0" } }, - "entities": { + "node_modules/enhanced-resolve": { + "version": "5.15.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz", + "integrity": "sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/entities": { "version": "1.0.0", - "integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY=", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz", + "integrity": "sha512-LbLqfXgJMmy81t+7c14mnulFHJ170cM6E+0vMXR9k/ZiZwgX8i5pNgjTCX3SO4VeUsFLV+8InixoretwU+MjBQ==", "dev": true }, - "error-ex": { - "version": "1.3.2", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "requires": { - "is-arrayish": "^0.2.1" - } - }, - "es-abstract": { - "version": "1.19.1", - "integrity": "sha512-2vJ6tjA/UfqLm2MPs7jxVybLoB8i1t1Jd9R3kISld20sIxPcTbLuggQOUxeWeAvIUkduv/CfMjuh4WmiXr2v9w==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "get-intrinsic": "^1.1.1", - "get-symbol-description": "^1.0.0", - "has": "^1.0.3", - "has-symbols": "^1.0.2", - "internal-slot": "^1.0.3", - "is-callable": "^1.2.4", - "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.4", - "is-shared-array-buffer": "^1.0.1", - "is-string": "^1.0.7", - "is-weakref": "^1.0.1", - "object-inspect": "^1.11.0", - "object-keys": "^1.1.1", - "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.4", - "string.prototype.trimstart": "^1.0.4", - "unbox-primitive": "^1.0.1" - } - }, - "es-to-primitive": { - "version": "1.2.1", - "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "node_modules/envinfo": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.10.0.tgz", + "integrity": "sha512-ZtUjZO6l5mwTHvc1L9+1q5p/R3wTopcfqMW8r5t8SJSKqeVI/LtajORwRFEKpEFuekjD0VBjwu1HMxL4UalIRw==", + "dev": true, + "bin": { + "envinfo": "dist/cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.3.1.tgz", + "integrity": "sha512-JUFAyicQV9mXc3YRxPnDlrfBKpqt6hUYzz9/boprUJHs4e4KVr3XwOF70doO6gwXUor6EWZJAyWAfKki84t20Q==", + "dev": true + }, + "node_modules/es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "dev": true + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", "dev": true, - "requires": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" + "engines": { + "node": ">=6" } }, - "es5-ext": { - "version": "0.10.53", - "integrity": "sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q==", + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, - "requires": { - "es6-iterator": "~2.0.3", - "es6-symbol": "~3.1.3", - "next-tick": "~1.0.0" + "engines": { + "node": ">=0.8.0" } }, - "es6-iterator": { - "version": "2.0.3", - "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", + "node_modules/escodegen": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", + "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", "dev": true, - "requires": { - "d": "1", - "es5-ext": "^0.10.35", - "es6-symbol": "^3.1.1" + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=4.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" } }, - "es6-symbol": { - "version": "3.1.3", - "integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==", + "node_modules/escodegen/node_modules/levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", "dev": true, - "requires": { - "d": "^1.0.1", - "ext": "^1.1.2" + "dependencies": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + }, + "engines": { + "node": ">= 0.8.0" } }, - "es6-weak-map": { - "version": "2.0.3", - "integrity": "sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==", + "node_modules/escodegen/node_modules/optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", "dev": true, - "requires": { - "d": "1", - "es5-ext": "^0.10.46", - "es6-iterator": "^2.0.3", - "es6-symbol": "^3.1.1" + "dependencies": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + }, + "engines": { + "node": ">= 0.8.0" } }, - "escape-string-regexp": { - "version": "1.0.5", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true + "node_modules/escodegen/node_modules/prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/escodegen/node_modules/type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", + "dev": true, + "dependencies": { + "prelude-ls": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } }, - "escodegen": { - "version": "1.8.1", - "integrity": "sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg=", + "node_modules/eslint": { + "version": "8.49.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.49.0.tgz", + "integrity": "sha512-jw03ENfm6VJI0jA9U+8H5zfl5b+FvuU3YYvZRdZHOlU2ggJkxrlkJH4HcDrZpj6YwD8kuYqvQM8LyesoazrSOQ==", "dev": true, - "requires": { - "esprima": "^2.7.1", - "estraverse": "^1.9.1", + "peer": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.2", + "@eslint/js": "8.49.0", + "@humanwhocodes/config-array": "^0.11.11", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", "esutils": "^2.0.2", - "optionator": "^0.8.1", - "source-map": "~0.2.0" - }, - "dependencies": { - "source-map": { - "version": "0.2.0", - "integrity": "sha1-2rc/vPwrqBm03gO9b26qSBZLP50=", - "dev": true, - "optional": true, - "requires": { - "amdefine": ">=0.0.4" - } - } + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "esprima": { - "version": "2.7.3", - "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", - "dev": true + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } }, - "estraverse": { - "version": "1.9.3", - "integrity": "sha1-r2fy3JIlgkFZUJJgkaQAXSnJu0Q=", - "dev": true + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } }, - "esutils": { - "version": "2.0.3", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true + "node_modules/eslint/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "peer": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } }, - "execa": { - "version": "2.1.0", - "integrity": "sha512-Y/URAVapfbYy2Xp/gb6A0E7iR8xeqOCXsuuaoMn7A5PzrXUK84E1gyiEfq0wQd/GHA6GsoHWwhNq8anb0mleIw==", + "node_modules/eslint/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, - "requires": { - "cross-spawn": "^7.0.0", - "get-stream": "^5.0.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^3.0.0", - "onetime": "^5.1.0", - "p-finally": "^2.0.0", - "signal-exit": "^3.0.2", - "strip-final-newline": "^2.0.0" + "peer": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "exit": { - "version": "0.1.2", - "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", - "dev": true + "node_modules/eslint/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "peer": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } }, - "expand-brackets": { - "version": "2.1.4", - "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", - "dev": true, - "requires": { - "debug": "^2.3.3", - "define-property": "^0.2.5", - "extend-shallow": "^2.0.1", - "posix-character-classes": "^0.1.0", - "regex-not": "^1.0.0", - "snapdragon": "^0.8.1", - "to-regex": "^3.0.1" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - }, - "extend-shallow": { - "version": "2.0.1", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - } + "node_modules/eslint/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "peer": true + }, + "node_modules/eslint/node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "expand-range": { - "version": "1.8.2", - "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", + "node_modules/eslint/node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", "dev": true, - "requires": { - "fill-range": "^2.1.0" + "peer": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/eslint/node_modules/globals": { + "version": "13.22.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.22.0.tgz", + "integrity": "sha512-H1Ddc/PbZHTDVJSnj8kWptIRSD6AM3pK+mKytuIVF4uoBV7rshFlhhvA58ceJ5wp3Er58w6zj7bykMpYXt3ETw==", + "dev": true, + "peer": true, "dependencies": { - "fill-range": { - "version": "2.2.4", - "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==", - "dev": true, - "requires": { - "is-number": "^2.1.0", - "isobject": "^2.0.0", - "randomatic": "^3.0.0", - "repeat-element": "^1.1.2", - "repeat-string": "^1.5.2" - } - }, - "is-number": { - "version": "2.1.0", - "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", - "dev": true, - "requires": { - "kind-of": "^3.0.2" - } - }, - "isobject": { - "version": "2.1.0", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "dev": true, - "requires": { - "isarray": "1.0.0" - } - }, - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "expand-tilde": { - "version": "2.0.2", - "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "node_modules/eslint/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/eslint/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, - "requires": { - "homedir-polyfill": "^1.0.1" + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "ext": { - "version": "1.6.0", - "integrity": "sha512-sdBImtzkq2HpkdRLtlLWDa6w4DX22ijZLKx8BMPUuKe1c5lbN6xwQDQCxSfxBQnHZ13ls/FH0MQZx/q/gr6FQg==", + "node_modules/eslint/node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true, - "requires": { - "type": "^2.5.0" + "peer": true, + "engines": { + "node": ">=10" }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "dev": true, + "peer": true, "dependencies": { - "type": { - "version": "2.5.0", - "integrity": "sha512-180WMDQaIMm3+7hGXWf12GtdniDEy7nYcyFMKJn/eZz/6tSLXrUN9V0wKSbMjej0I1WHWbpREDEKHtqPQa9NNw==", - "dev": true - } + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "extend": { - "version": "3.0.2", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", - "dev": true + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } }, - "extend-shallow": { - "version": "3.0.2", - "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "node_modules/esquery": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", + "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", "dev": true, - "requires": { - "assign-symbols": "^1.0.0", - "is-extendable": "^1.0.1" + "peer": true, + "dependencies": { + "estraverse": "^5.1.0" }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esquery/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, "dependencies": { - "is-extendable": { - "version": "1.0.1", - "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", - "dev": true, - "requires": { - "is-plain-object": "^2.0.4" - } - } + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" } }, - "extglob": { - "version": "2.0.4", - "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", - "dev": true, - "requires": { - "array-unique": "^0.3.2", - "define-property": "^1.0.0", - "expand-brackets": "^2.1.4", - "extend-shallow": "^2.0.1", - "fragment-cache": "^0.2.1", - "regex-not": "^1.0.0", - "snapdragon": "^0.8.1", - "to-regex": "^3.0.1" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "dev": true, - "requires": { - "is-descriptor": "^1.0.0" - } - }, - "extend-shallow": { - "version": "2.0.1", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-descriptor": { - "version": "1.0.2", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "^1.0.0", - "is-data-descriptor": "^1.0.0", - "kind-of": "^6.0.2" - } - } + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true, + "engines": { + "node": ">= 0.8.0" } }, - "extsprintf": { - "version": "1.3.0", - "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, - "fancy-log": { - "version": "1.3.3", - "integrity": "sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw==", + "node_modules/extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==", "dev": true, - "requires": { - "ansi-gray": "^0.1.1", - "color-support": "^1.1.3", - "parse-node-version": "^1.0.0", - "time-stamp": "^1.0.0" - } + "engines": [ + "node >=0.6.0" + ] }, - "fast-deep-equal": { + "node_modules/fast-deep-equal": { "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, - "fast-json-stable-stringify": { + "node_modules/fast-glob": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, - "fast-levenshtein": { - "version": "1.1.4", - "integrity": "sha1-5qdUzI8V5YmHqpy9J69m/W9OWvk=", + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", "dev": true }, - "file-uri-to-path": { - "version": "1.0.0", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "node_modules/fastest-levenshtein": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", + "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", "dev": true, - "optional": true - }, - "filename-regex": { - "version": "2.0.1", - "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", - "dev": true - }, - "fill-range": { - "version": "4.0.0", - "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", - "dev": true, - "requires": { - "extend-shallow": "^2.0.1", - "is-number": "^3.0.0", - "repeat-string": "^1.6.1", - "to-regex-range": "^2.1.0" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - } + "engines": { + "node": ">= 4.9.1" } }, - "find-up": { - "version": "1.1.2", - "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "node_modules/fastq": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", + "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", "dev": true, - "requires": { - "path-exists": "^2.0.0", - "pinkie-promise": "^2.0.0" + "dependencies": { + "reusify": "^1.0.4" } }, - "findup-sync": { - "version": "3.0.0", - "integrity": "sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg==", + "node_modules/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", "dev": true, - "requires": { - "detect-file": "^1.0.0", - "is-glob": "^4.0.0", - "micromatch": "^3.0.4", - "resolve-dir": "^1.0.1" + "peer": true, + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" } }, - "fined": { - "version": "1.2.0", - "integrity": "sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng==", + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "dev": true, - "requires": { - "expand-tilde": "^2.0.2", - "is-plain-object": "^2.0.3", - "object.defaults": "^1.1.0", - "object.pick": "^1.2.0", - "parse-filepath": "^1.0.1" + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" } }, - "first-chunk-stream": { - "version": "2.0.0", - "integrity": "sha1-G97NuOCDwGZLkZRVgVd6Q6nzHXA=", + "node_modules/find-cache-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-4.0.0.tgz", + "integrity": "sha512-9ZonPT4ZAK4a+1pUPVPZJapbi7O5qbbJPdYw/NOQWZZbVLdDTYM3A4R9z/DpAM08IDaFGsvPgiGZ82WEwUDWjg==", "dev": true, - "requires": { - "readable-stream": "^2.0.2" + "dependencies": { + "common-path-prefix": "^3.0.0", + "pkg-dir": "^7.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "flagged-respawn": { - "version": "1.0.1", - "integrity": "sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q==", - "dev": true - }, - "flat": { - "version": "4.1.1", - "integrity": "sha512-FmTtBsHskrU6FJ2VxCnsDb84wu9zhmO3cUX2kGFb5tuwhfXxGciiT0oRY+cck35QmG+NmGh5eLz6lLCpWTqwpA==", + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, - "requires": { - "is-buffer": "~2.0.3" - }, "dependencies": { - "is-buffer": { - "version": "2.0.5", - "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==", - "dev": true - } + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "flush-write-stream": { - "version": "1.1.1", - "integrity": "sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==", + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", "dev": true, - "requires": { - "inherits": "^2.0.3", - "readable-stream": "^2.3.6" + "bin": { + "flat": "cli.js" } }, - "for-in": { - "version": "1.0.2", - "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", - "dev": true + "node_modules/flat-cache": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.1.0.tgz", + "integrity": "sha512-OHx4Qwrrt0E4jEIcI5/Xb+f+QmJYNj2rrK8wiIdQOIrB9WrrJL8cjZvXdXuBTkkEwEqLycb5BeZDV1o2i9bTew==", + "dev": true, + "peer": true, + "dependencies": { + "flatted": "^3.2.7", + "keyv": "^4.5.3", + "rimraf": "^3.0.2" + }, + "engines": { + "node": ">=12.0.0" + } }, - "for-own": { - "version": "1.0.0", - "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", + "node_modules/flatted": { + "version": "3.2.9", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz", + "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==", + "dev": true, + "peer": true + }, + "node_modules/foreground-child": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", + "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, - "requires": { - "for-in": "^1.0.1" + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8.0.0" } }, - "forever-agent": { + "node_modules/forever-agent": { "version": "0.6.1", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", - "dev": true + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==", + "dev": true, + "engines": { + "node": "*" + } }, - "form-data": { + "node_modules/form-data": { "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", "dev": true, - "requires": { + "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.6", "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" } }, - "fragment-cache": { - "version": "0.2.1", - "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", - "dev": true, - "requires": { - "map-cache": "^0.2.2" - } - }, - "fs-mkdirp-stream": { - "version": "1.0.0", - "integrity": "sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes=", + "node_modules/fromentries": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fromentries/-/fromentries-1.3.2.tgz", + "integrity": "sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg==", "dev": true, - "requires": { - "graceful-fs": "^4.1.11", - "through2": "^2.0.3" - } + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, - "fs.realpath": { + "node_modules/fs.realpath": { "version": "1.0.0", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true }, - "fsevents": { - "version": "1.2.13", - "integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==", + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, + "hasInstallScript": true, "optional": true, - "requires": { - "bindings": "^1.5.0", - "nan": "^2.12.1" + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "function-bind": { + "node_modules/function-bind": { "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, - "get-caller-file": { - "version": "1.0.3", - "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", - "dev": true - }, - "get-func-name": { - "version": "2.0.0", - "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", - "dev": true - }, - "get-intrinsic": { - "version": "1.1.1", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" + "engines": { + "node": ">=6.9.0" } }, - "get-stream": { - "version": "5.2.0", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true, - "requires": { - "pump": "^3.0.0" + "engines": { + "node": "6.* || 8.* || >= 10.*" } }, - "get-symbol-description": { - "version": "1.0.0", - "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==", + "node_modules/get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", "dev": true, - "requires": { - "call-bind": "^1.0.2", - "get-intrinsic": "^1.1.1" + "engines": { + "node": "*" } }, - "get-value": { - "version": "2.0.6", - "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", - "dev": true + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true, + "engines": { + "node": ">=8.0.0" + } }, - "getpass": { + "node_modules/getpass": { "version": "0.1.7", - "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", "dev": true, - "requires": { + "dependencies": { "assert-plus": "^1.0.0" } }, - "glob": { - "version": "7.2.0", - "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "dev": true, - "requires": { + "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" - } - }, - "glob-base": { - "version": "0.3.0", - "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", - "dev": true, - "requires": { - "glob-parent": "^2.0.0", - "is-glob": "^2.0.0" }, - "dependencies": { - "glob-parent": { - "version": "2.0.0", - "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", - "dev": true, - "requires": { - "is-glob": "^2.0.0" - } - }, - "is-extglob": { - "version": "1.0.0", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", - "dev": true - }, - "is-glob": { - "version": "2.0.1", - "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", - "dev": true, - "requires": { - "is-extglob": "^1.0.0" - } - } + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "glob-parent": { - "version": "3.1.0", - "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, - "requires": { - "is-glob": "^3.1.0", - "path-dirname": "^1.0.0" - }, + "peer": true, "dependencies": { - "is-glob": { - "version": "3.1.0", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "^2.1.0" - } - } - } - }, - "glob-stream": { - "version": "6.1.0", - "integrity": "sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ=", - "dev": true, - "requires": { - "extend": "^3.0.0", - "glob": "^7.1.1", - "glob-parent": "^3.1.0", - "is-negated-glob": "^1.0.0", - "ordered-read-streams": "^1.0.0", - "pumpify": "^1.3.5", - "readable-stream": "^2.1.5", - "remove-trailing-separator": "^1.0.1", - "to-absolute-glob": "^2.0.0", - "unique-stream": "^2.0.2" - } - }, - "glob-watcher": { - "version": "5.0.5", - "integrity": "sha512-zOZgGGEHPklZNjZQaZ9f41i7F2YwE+tS5ZHrDhbBCk3stwahn5vQxnFmBJZHoYdusR6R1bLSXeGUy/BhctwKzw==", - "dev": true, - "requires": { - "anymatch": "^2.0.0", - "async-done": "^1.2.0", - "chokidar": "^2.0.0", - "is-negated-glob": "^1.0.0", - "just-debounce": "^1.0.0", - "normalize-path": "^3.0.0", - "object.defaults": "^1.1.0" + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" } }, - "global-modules": { - "version": "1.0.0", - "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", - "dev": true, - "requires": { - "global-prefix": "^1.0.1", - "is-windows": "^1.0.1", - "resolve-dir": "^1.0.0" - } + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true }, - "global-prefix": { - "version": "1.0.2", - "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", "dev": true, - "requires": { - "expand-tilde": "^2.0.2", - "homedir-polyfill": "^1.0.1", - "ini": "^1.3.4", - "is-windows": "^1.0.1", - "which": "^1.2.14" + "engines": { + "node": ">=4" } }, - "glogg": { - "version": "1.0.2", - "integrity": "sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA==", + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", "dev": true, - "requires": { - "sparkles": "^1.0.0" + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "graceful-fs": { - "version": "4.2.8", - "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==", + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "dev": true }, - "growl": { - "version": "1.10.5", - "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, - "gulp": { - "version": "4.0.2", - "integrity": "sha512-dvEs27SCZt2ibF29xYgmnwwCYZxdxhQ/+LFWlbAW8y7jt68L/65402Lz3+CKy0Ov4rOs+NERmDq7YlZaDqUIfA==", + "node_modules/har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==", "dev": true, - "requires": { - "glob-watcher": "^5.0.3", - "gulp-cli": "^2.2.0", - "undertaker": "^1.2.1", - "vinyl-fs": "^3.0.0" + "engines": { + "node": ">=4" } }, - "gulp-cli": { - "version": "2.3.0", - "integrity": "sha512-zzGBl5fHo0EKSXsHzjspp3y5CONegCm8ErO5Qh0UzFzk2y4tMvzLWhoDokADbarfZRL2pGpRp7yt6gfJX4ph7A==", - "dev": true, - "requires": { - "ansi-colors": "^1.0.1", - "archy": "^1.0.0", - "array-sort": "^1.0.0", - "color-support": "^1.1.3", - "concat-stream": "^1.6.0", - "copy-props": "^2.0.1", - "fancy-log": "^1.3.2", - "gulplog": "^1.0.0", - "interpret": "^1.4.0", - "isobject": "^3.0.1", - "liftoff": "^3.1.0", - "matchdep": "^2.0.0", - "mute-stdout": "^1.0.0", - "pretty-hrtime": "^1.0.0", - "replace-homedir": "^1.0.0", - "semver-greatest-satisfied-range": "^1.1.0", - "v8flags": "^3.2.0", - "yargs": "^7.1.0" - } - }, - "gulp-concat": { - "version": "2.6.1", - "integrity": "sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M=", - "dev": true, - "requires": { - "concat-with-sourcemaps": "^1.0.0", - "through2": "^2.0.0", - "vinyl": "^2.0.0" - } - }, - "gulp-istanbul": { - "version": "1.1.3", - "integrity": "sha512-uMLSdqPDnBAV/B9rNyOgVMgrVC1tPbe+5GH6P13UOyxbRDT/w4sKYHWftPMA8j9om+NFvfeRlqpDXL2fixFWNA==", + "node_modules/har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "deprecated": "this library is no longer supported", "dev": true, - "requires": { - "istanbul": "^0.4.0", - "istanbul-threshold-checker": "^0.2.1", - "lodash": "^4.0.0", - "plugin-error": "^0.1.2", - "through2": "^2.0.0", - "vinyl-sourcemaps-apply": "^0.2.1" + "dependencies": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + }, + "engines": { + "node": ">=6" } }, - "gulp-jshint": { - "version": "2.1.0", - "integrity": "sha512-sP3NK8Y/1e58O0PH9t6s7DAr/lKDSUbIY207oWSeufM6/VclB7jJrIBcPCsyhrFTCDUl9DauePbt6VqP2vPM5w==", + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, - "requires": { - "lodash": "^4.12.0", - "minimatch": "^3.0.3", - "plugin-error": "^0.1.2", - "rcloader": "^0.2.2", - "through2": "^2.0.0" + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" } }, - "gulp-mocha": { - "version": "7.0.2", - "integrity": "sha512-ZXBGN60TXYnFhttr19mfZBOtlHYGx9SvCSc+Kr/m2cMIGloUe176HBPwvPqlakPuQgeTGVRS47NmcdZUereKMQ==", + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "dev": true, - "requires": { - "dargs": "^7.0.0", - "execa": "^2.0.4", - "mocha": "^6.2.0", - "plugin-error": "^1.0.1", - "supports-color": "^7.0.0", - "through2": "^3.0.1" - }, - "dependencies": { - "has-flag": { - "version": "4.0.0", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "plugin-error": { - "version": "1.0.1", - "integrity": "sha512-L1zP0dk7vGweZME2i+EeakvUNqSrdiI3F91TwEoYiGrAfUXmVv6fJIq4g82PAXxNsWOp0J7ZqQy/3Szz0ajTxA==", - "dev": true, - "requires": { - "ansi-colors": "^1.0.1", - "arr-diff": "^4.0.0", - "arr-union": "^3.1.0", - "extend-shallow": "^3.0.2" - } - }, - "supports-color": { - "version": "7.2.0", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - }, - "through2": { - "version": "3.0.2", - "integrity": "sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==", - "dev": true, - "requires": { - "inherits": "^2.0.4", - "readable-stream": "2 || 3" - } - } + "engines": { + "node": ">=4" } }, - "gulp-rename": { - "version": "1.4.0", - "integrity": "sha512-swzbIGb/arEoFK89tPY58vg3Ok1bw+d35PfUNwWqdo7KM4jkmuGA78JiDNqR+JeZFaeeHnRg9N7aihX3YPmsyg==", - "dev": true - }, - "gulp-replace": { - "version": "1.1.3", - "integrity": "sha512-HcPHpWY4XdF8zxYkDODHnG2+7a3nD/Y8Mfu3aBgMiCFDW3X2GiOKXllsAmILcxe3KZT2BXoN18WrpEFm48KfLQ==", + "node_modules/hasha": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/hasha/-/hasha-5.2.2.tgz", + "integrity": "sha512-Hrp5vIK/xr5SkeN2onO32H0MgNZ0f17HRNH39WfL0SYUNOTZ5Lz1TJ8Pajo/87dYGEFlLMm7mIc/k/s6Bvz9HQ==", "dev": true, - "requires": { - "@types/node": "^14.14.41", - "@types/vinyl": "^2.0.4", - "istextorbinary": "^3.0.0", - "replacestream": "^4.0.3", - "yargs-parser": ">=5.0.0-security.0" + "dependencies": { + "is-stream": "^2.0.0", + "type-fest": "^0.8.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "gulp-rev": { - "version": "8.1.1", - "integrity": "sha1-sRBr+qVlMQahHRYS6wz/3lQMsZY=", + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", "dev": true, - "requires": { - "modify-filename": "^1.1.0", - "plugin-error": "^0.1.2", - "rev-hash": "^2.0.0", - "rev-path": "^2.0.0", - "sort-keys": "^2.0.0", - "through2": "^2.0.0", - "vinyl": "^2.1.0", - "vinyl-file": "^3.0.0" + "bin": { + "he": "bin/he" } }, - "gulp-uglify": { - "version": "3.0.2", - "integrity": "sha512-gk1dhB74AkV2kzqPMQBLA3jPoIAPd/nlNzP2XMDSG8XZrqnlCiDGAqC+rZOumzFvB5zOphlFh6yr3lgcAb/OOg==", - "dev": true, - "requires": { - "array-each": "^1.0.1", - "extend-shallow": "^3.0.2", - "gulplog": "^1.0.0", - "has-gulplog": "^0.1.0", - "isobject": "^3.0.1", - "make-error-cause": "^1.1.1", - "safe-buffer": "^5.1.2", - "through2": "^2.0.0", - "uglify-js": "^3.0.5", - "vinyl-sourcemaps-apply": "^0.2.0" + "node_modules/html-encoding-sniffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz", + "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", + "dev": true, + "dependencies": { + "whatwg-encoding": "^1.0.1" } }, - "gulp-watch": { - "version": "5.0.1", - "integrity": "sha512-HnTSBdzAOFIT4wmXYPDUn783TaYAq9bpaN05vuZNP5eni3z3aRx0NAKbjhhMYtcq76x4R1wf4oORDGdlrEjuog==", - "dev": true, - "requires": { - "ansi-colors": "1.1.0", - "anymatch": "^1.3.0", - "chokidar": "^2.0.0", - "fancy-log": "1.3.2", - "glob-parent": "^3.0.1", - "object-assign": "^4.1.0", - "path-is-absolute": "^1.0.1", - "plugin-error": "1.0.1", - "readable-stream": "^2.2.2", - "slash": "^1.0.0", - "vinyl": "^2.1.0", - "vinyl-file": "^2.0.0" - }, - "dependencies": { - "anymatch": { - "version": "1.3.2", - "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", - "dev": true, - "requires": { - "micromatch": "^2.1.5", - "normalize-path": "^2.0.0" - } - }, - "arr-diff": { - "version": "2.0.0", - "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", - "dev": true, - "requires": { - "arr-flatten": "^1.0.1" - } - }, - "array-unique": { - "version": "0.2.1", - "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", - "dev": true - }, - "braces": { - "version": "1.8.5", - "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", - "dev": true, - "requires": { - "expand-range": "^1.8.1", - "preserve": "^0.2.0", - "repeat-element": "^1.1.2" - } - }, - "clone": { - "version": "1.0.4", - "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", - "dev": true - }, - "clone-stats": { - "version": "0.0.1", - "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", - "dev": true - }, - "expand-brackets": { - "version": "0.1.5", - "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", - "dev": true, - "requires": { - "is-posix-bracket": "^0.1.0" - } - }, - "extglob": { - "version": "0.3.2", - "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", - "dev": true, - "requires": { - "is-extglob": "^1.0.0" - } - }, - "fancy-log": { - "version": "1.3.2", - "integrity": "sha1-9BEl49hPLn2JpD0G2VjI94vha+E=", - "dev": true, - "requires": { - "ansi-gray": "^0.1.1", - "color-support": "^1.1.3", - "time-stamp": "^1.0.0" - } - }, - "is-extglob": { - "version": "1.0.0", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", - "dev": true - }, - "is-glob": { - "version": "2.0.1", - "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", - "dev": true, - "requires": { - "is-extglob": "^1.0.0" - } - }, - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - }, - "micromatch": { - "version": "2.3.11", - "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", - "dev": true, - "requires": { - "arr-diff": "^2.0.0", - "array-unique": "^0.2.1", - "braces": "^1.8.2", - "expand-brackets": "^0.1.4", - "extglob": "^0.3.1", - "filename-regex": "^2.0.0", - "is-extglob": "^1.0.0", - "is-glob": "^2.0.1", - "kind-of": "^3.0.2", - "normalize-path": "^2.0.1", - "object.omit": "^2.0.0", - "parse-glob": "^3.0.4", - "regex-cache": "^0.4.2" - } - }, - "normalize-path": { - "version": "2.1.1", - "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", - "dev": true, - "requires": { - "remove-trailing-separator": "^1.0.1" - } - }, - "plugin-error": { - "version": "1.0.1", - "integrity": "sha512-L1zP0dk7vGweZME2i+EeakvUNqSrdiI3F91TwEoYiGrAfUXmVv6fJIq4g82PAXxNsWOp0J7ZqQy/3Szz0ajTxA==", - "dev": true, - "requires": { - "ansi-colors": "^1.0.1", - "arr-diff": "^4.0.0", - "arr-union": "^3.1.0", - "extend-shallow": "^3.0.2" - }, - "dependencies": { - "arr-diff": { - "version": "4.0.0", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true - } - } - }, - "replace-ext": { - "version": "0.0.1", - "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", - "dev": true - }, - "vinyl-file": { - "version": "2.0.0", - "integrity": "sha1-p+v1/779obfRjRQPyweyI++2dRo=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "pify": "^2.3.0", - "pinkie-promise": "^2.0.0", - "strip-bom": "^2.0.0", - "strip-bom-stream": "^2.0.0", - "vinyl": "^1.1.0" - }, - "dependencies": { - "vinyl": { - "version": "1.2.0", - "integrity": "sha1-XIgDbPVl5d8FVYv8kR+GVt8hiIQ=", - "dev": true, - "requires": { - "clone": "^1.0.0", - "clone-stats": "^0.0.1", - "replace-ext": "0.0.1" - } - } - } - } - } + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true }, - "gulplog": { - "version": "1.0.0", - "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", + "node_modules/htmlparser2": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.8.3.tgz", + "integrity": "sha512-hBxEg3CYXe+rPIua8ETe7tmG3XDn9B0edOE/e9wH2nLczxzgdu0m0aNHY+5wFZiviLWLdANPJTssa92dMcXQ5Q==", "dev": true, - "requires": { - "glogg": "^1.0.0" + "dependencies": { + "domelementtype": "1", + "domhandler": "2.3", + "domutils": "1.5", + "entities": "1.0", + "readable-stream": "1.1" } }, - "handlebars": { - "version": "4.7.7", - "integrity": "sha512-aAcXm5OAfE/8IXkcZvCepKU3VzW1/39Fb5ZuqMtgI/hT8X2YgoMvBY5dLhq/cpOvw7Lk1nK/UF71aLG/ZnVYRA==", + "node_modules/http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", "dev": true, - "requires": { - "minimist": "^1.2.5", - "neo-async": "^2.6.0", - "source-map": "^0.6.1", - "uglify-js": "^3.1.4", - "wordwrap": "^1.0.0" - }, "dependencies": { - "source-map": { - "version": "0.6.1", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.3.7" } }, - "har-schema": { - "version": "2.0.0", - "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", - "dev": true - }, - "har-validator": { - "version": "5.1.5", - "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, - "requires": { - "ajv": "^6.12.3", - "har-schema": "^2.0.0" + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" } }, - "has": { - "version": "1.0.3", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "node_modules/ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true, - "requires": { - "function-bind": "^1.1.1" + "engines": { + "node": ">= 4" } }, - "has-bigints": { - "version": "1.0.1", - "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", - "dev": true - }, - "has-flag": { - "version": "1.0.0", - "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", - "dev": true - }, - "has-gulplog": { - "version": "0.1.0", - "integrity": "sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=", + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", "dev": true, - "requires": { - "sparkles": "^1.0.0" + "peer": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "has-symbols": { - "version": "1.0.2", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, - "has-tostringtag": { - "version": "1.0.0", - "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "node_modules/import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", "dev": true, - "requires": { - "has-symbols": "^1.0.2" + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "has-value": { - "version": "1.0.0", - "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "node_modules/import-local/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, - "requires": { - "get-value": "^2.0.6", - "has-values": "^1.0.0", - "isobject": "^3.0.0" + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "has-values": { - "version": "1.0.0", - "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "node_modules/import-local/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, - "requires": { - "is-number": "^3.0.0", - "kind-of": "^4.0.0" - }, "dependencies": { - "kind-of": { - "version": "4.0.0", - "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" } }, - "he": { - "version": "1.2.0", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", - "dev": true - }, - "homedir-polyfill": { - "version": "1.0.3", - "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "node_modules/import-local/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, - "requires": { - "parse-passwd": "^1.0.0" + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "hosted-git-info": { - "version": "2.8.9", - "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", - "dev": true - }, - "html-encoding-sniffer": { - "version": "1.0.2", - "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", + "node_modules/import-local/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, - "requires": { - "whatwg-encoding": "^1.0.1" + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" } }, - "htmlparser2": { - "version": "3.8.3", - "integrity": "sha1-mWwosZFRaovoZQGn15dX5ccMEGg=", + "node_modules/import-local/node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, - "requires": { - "domelementtype": "1", - "domhandler": "2.3", - "domutils": "1.5", - "entities": "1.0", - "readable-stream": "1.1" - }, "dependencies": { - "isarray": { - "version": "0.0.1", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "readable-stream": { - "version": "1.1.14", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "dev": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" - } - }, - "string_decoder": { - "version": "0.10.31", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - } + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "http-signature": { - "version": "1.2.0", - "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, - "requires": { - "assert-plus": "^1.0.0", - "jsprim": "^1.2.2", - "sshpk": "^1.7.0" + "engines": { + "node": ">=0.8.19" } }, - "iconv-lite": { - "version": "0.4.24", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", "dev": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3" + "engines": { + "node": ">=8" } }, - "inflight": { + "node_modules/inflight": { "version": "1.0.6", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "dev": true, - "requires": { + "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, - "inherits": { + "node_modules/inherits": { "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, - "ini": { - "version": "1.3.8", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true - }, - "internal-slot": { - "version": "1.0.3", - "integrity": "sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA==", + "node_modules/interpret": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz", + "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==", "dev": true, - "requires": { - "get-intrinsic": "^1.1.0", - "has": "^1.0.3", - "side-channel": "^1.0.4" + "engines": { + "node": ">= 0.10" } }, - "interpret": { - "version": "1.4.0", - "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==", - "dev": true - }, - "invert-kv": { - "version": "1.0.0", - "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", - "dev": true - }, - "is-absolute": { - "version": "1.0.0", - "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dev": true, - "requires": { - "is-relative": "^1.0.0", - "is-windows": "^1.0.1" + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" } }, - "is-accessor-descriptor": { - "version": "0.1.6", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "node_modules/is-core-module": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.0.tgz", + "integrity": "sha512-Z7dk6Qo8pOCp3l4tsX2C5ZVas4V+UxwQodwZhLopL91TX8UyyHEXafPcyoeeWuLrwzHcr3igO78wNLwHJHsMCQ==", "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, "dependencies": { - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "is-arrayish": { - "version": "0.2.1", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - }, - "is-bigint": { - "version": "1.0.4", - "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "dev": true, - "requires": { - "has-bigints": "^1.0.1" + "engines": { + "node": ">=0.10.0" } }, - "is-binary-path": { - "version": "1.0.1", - "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, - "requires": { - "binary-extensions": "^1.0.0" + "engines": { + "node": ">=8" } }, - "is-boolean-object": { - "version": "1.1.2", - "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, - "requires": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" } }, - "is-buffer": { - "version": "1.1.6", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-callable": { - "version": "1.2.4", - "integrity": "sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w==", - "dev": true + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } }, - "is-core-module": { - "version": "2.7.0", - "integrity": "sha512-ByY+tjCciCr+9nLryBYcSD50EOGWt95c7tIsKTG1J2ixKKXPvF7Ej3AVd+UfDydAJom3biBGDBALaO79ktwgEQ==", + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", "dev": true, - "requires": { - "has": "^1.0.3" + "peer": true, + "engines": { + "node": ">=8" } }, - "is-data-descriptor": { - "version": "0.1.4", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "node_modules/is-plain-obj": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", + "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "engines": { + "node": ">=8" } }, - "is-date-object": { - "version": "1.0.5", - "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", "dev": true, - "requires": { - "has-tostringtag": "^1.0.0" + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" } }, - "is-descriptor": { - "version": "0.1.6", - "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true, - "requires": { - "is-accessor-descriptor": "^0.1.6", - "is-data-descriptor": "^0.1.4", - "kind-of": "^5.0.0" + "engines": { + "node": ">=8" }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", - "dev": true - } + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "is-dotfile": { - "version": "1.0.3", - "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=", + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", "dev": true }, - "is-equal-shallow": { - "version": "0.1.3", - "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", "dev": true, - "requires": { - "is-primitive": "^2.0.0" + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "is-extendable": { - "version": "0.1.1", - "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", - "dev": true + "node_modules/is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "is-extglob": { - "version": "2.1.1", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "node_modules/isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==", "dev": true }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "dev": true, - "requires": { - "number-is-nan": "^1.0.0" - } + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true }, - "is-glob": { - "version": "4.0.3", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", "dev": true, - "requires": { - "is-extglob": "^2.1.1" + "engines": { + "node": ">=0.10.0" } }, - "is-negated-glob": { - "version": "1.0.0", - "integrity": "sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI=", + "node_modules/isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==", "dev": true }, - "is-negative-zero": { - "version": "2.0.1", - "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", - "dev": true + "node_modules/istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true, + "engines": { + "node": ">=8" + } }, - "is-number": { + "node_modules/istanbul-lib-hook": { "version": "3.0.0", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-3.0.0.tgz", + "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, "dependencies": { - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "append-transform": "^2.0.0" + }, + "engines": { + "node": ">=8" } }, - "is-number-object": { - "version": "1.0.6", - "integrity": "sha512-bEVOqiRcvo3zO1+G2lVMy+gkkEm9Yh7cDMRusKKu5ZJKPUYSJwICTKZrNKHA2EbSP0Tu0+6B/emsYNHZyn6K8g==", + "node_modules/istanbul-lib-instrument": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz", + "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", "dev": true, - "requires": { - "has-tostringtag": "^1.0.0" + "dependencies": { + "@babel/core": "^7.7.5", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.0.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" } }, - "is-plain-obj": { - "version": "1.1.0", - "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", - "dev": true - }, - "is-plain-object": { - "version": "2.0.4", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "node_modules/istanbul-lib-processinfo": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.3.tgz", + "integrity": "sha512-NkwHbo3E00oybX6NGJi6ar0B29vxyvNwoC7eJ4G4Yq28UfY758Hgn/heV8VRFhevPED4LXfFz0DQ8z/0kw9zMg==", "dev": true, - "requires": { - "isobject": "^3.0.1" + "dependencies": { + "archy": "^1.0.0", + "cross-spawn": "^7.0.3", + "istanbul-lib-coverage": "^3.2.0", + "p-map": "^3.0.0", + "rimraf": "^3.0.0", + "uuid": "^8.3.2" + }, + "engines": { + "node": ">=8" } }, - "is-posix-bracket": { - "version": "0.1.1", - "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", - "dev": true - }, - "is-primitive": { - "version": "2.0.0", - "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", - "dev": true - }, - "is-regex": { - "version": "1.1.4", - "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", "dev": true, - "requires": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" } }, - "is-relative": { - "version": "1.0.0", - "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "node_modules/istanbul-lib-report/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "requires": { - "is-unc-path": "^1.0.0" + "engines": { + "node": ">=8" } }, - "is-shared-array-buffer": { - "version": "1.0.1", - "integrity": "sha512-IU0NmyknYZN0rChcKhRO1X8LYz5Isj/Fsqh8NJOSf+N/hCOTwy29F32Ik7a+QszE63IdvmwdTPDd6cZ5pg4cwA==", - "dev": true - }, - "is-stream": { - "version": "2.0.1", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true - }, - "is-string": { - "version": "1.0.7", - "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "node_modules/istanbul-lib-report/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, - "requires": { - "has-tostringtag": "^1.0.0" + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" } }, - "is-symbol": { - "version": "1.0.4", - "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "node_modules/istanbul-lib-report/node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", "dev": true, - "requires": { - "has-symbols": "^1.0.2" + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "is-typedarray": { - "version": "1.0.0", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", - "dev": true - }, - "is-unc-path": { - "version": "1.0.0", - "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "node_modules/istanbul-lib-report/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, - "requires": { - "unc-path-regex": "^0.1.2" + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, - "is-utf8": { - "version": "0.2.1", - "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", - "dev": true - }, - "is-valid-glob": { - "version": "1.0.0", - "integrity": "sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao=", - "dev": true - }, - "is-weakref": { - "version": "1.0.1", - "integrity": "sha512-b2jKc2pQZjaeFYWEf7ScFj+Be1I+PXmlu572Q8coTXZ+LD/QQZ7ShPMst8h16riVgyXTQwUsFEl74mDvc/3MHQ==", + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, - "requires": { - "call-bind": "^1.0.0" + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "is-windows": { - "version": "1.0.2", - "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", - "dev": true - }, - "isarray": { - "version": "1.0.0", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", - "dev": true - }, - "isexe": { - "version": "2.0.0", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, - "isobject": { - "version": "3.0.1", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "node_modules/istanbul-lib-report/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "isstream": { - "version": "0.1.2", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", - "dev": true + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } }, - "istanbul": { - "version": "0.4.5", - "integrity": "sha1-ZcfXPUxNqE1POsMQuRj7C4Azczs=", - "dev": true, - "requires": { - "abbrev": "1.0.x", - "async": "1.x", - "escodegen": "1.8.x", - "esprima": "2.7.x", - "glob": "^5.0.15", - "handlebars": "^4.0.1", - "js-yaml": "3.x", - "mkdirp": "0.5.x", - "nopt": "3.x", - "once": "1.x", - "resolve": "1.1.x", - "supports-color": "^3.1.0", - "which": "^1.1.1", - "wordwrap": "^1.0.0" - }, - "dependencies": { - "glob": { - "version": "5.0.15", - "integrity": "sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=", - "dev": true, - "requires": { - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "2 || 3", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "resolve": { - "version": "1.1.7", - "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", - "dev": true - } + "node_modules/istanbul-reports": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz", + "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==", + "dev": true, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" } }, - "istanbul-threshold-checker": { - "version": "0.2.1", - "integrity": "sha1-xdyU6PLMXNP/0zVFL4S1U8QkgzE=", + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", "dev": true, - "requires": { - "istanbul": "~0.4.5", - "lodash": "~4.17.2" + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" } }, - "istextorbinary": { - "version": "3.3.0", - "integrity": "sha512-Tvq1W6NAcZeJ8op+Hq7tdZ434rqnMx4CCZ7H0ff83uEloDvVbqAwaMTZcafKGJT0VHkYzuXUiCY4hlXQg6WfoQ==", + "node_modules/jest-worker/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "requires": { - "binaryextensions": "^2.2.0", - "textextensions": "^3.2.0" + "engines": { + "node": ">=8" } }, - "js-yaml": { - "version": "3.14.1", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "dependencies": { + "has-flag": "^4.0.0" }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, "dependencies": { - "esprima": { - "version": "4.0.1", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true - } + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" } }, - "jsbn": { + "node_modules/jsbn": { "version": "0.1.1", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==", "dev": true }, - "jsdom": { + "node_modules/jsdom": { "version": "11.12.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-11.12.0.tgz", "integrity": "sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==", "dev": true, - "requires": { + "dependencies": { "abab": "^2.0.0", "acorn": "^5.5.3", "acorn-globals": "^4.1.0", @@ -2829,1395 +5190,1447 @@ "whatwg-url": "^6.4.1", "ws": "^5.2.0", "xml-name-validator": "^3.0.0" + } + }, + "node_modules/jsdom/node_modules/acorn": { + "version": "5.7.4", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz", + "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" }, - "dependencies": { - "escodegen": { - "version": "1.14.3", - "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", - "dev": true, - "requires": { - "esprima": "^4.0.1", - "estraverse": "^4.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1", - "source-map": "~0.6.1" - } - }, - "esprima": { - "version": "4.0.1", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true - }, - "estraverse": { - "version": "4.3.0", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true - }, - "source-map": { - "version": "0.6.1", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "optional": true - } + "engines": { + "node": ">=0.4.0" } }, - "jshint": { - "version": "2.13.1", - "integrity": "sha512-vymzfR3OysF5P774x6zYv0bD4EpH6NWRxpq54wO9mA9RuY49yb1teKSICkLx2Ryx+mfzlVVNNbTBtsRtg78t7g==", + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "dev": true, - "requires": { + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/jshint": { + "version": "2.13.6", + "resolved": "https://registry.npmjs.org/jshint/-/jshint-2.13.6.tgz", + "integrity": "sha512-IVdB4G0NTTeQZrBoM8C5JFVLjV2KtZ9APgybDA1MK73xb09qFs0jCXyQLnCOp1cSZZZbvhq/6mfXHUTaDkffuQ==", + "dev": true, + "dependencies": { "cli": "~1.0.0", "console-browserify": "1.1.x", "exit": "0.1.x", "htmlparser2": "3.8.x", "lodash": "~4.17.21", "minimatch": "~3.0.2", - "shelljs": "0.3.x", "strip-json-comments": "1.0.x" }, + "bin": { + "jshint": "bin/jshint" + } + }, + "node_modules/jshint/node_modules/minimatch": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.8.tgz", + "integrity": "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q==", + "dev": true, "dependencies": { - "strip-json-comments": { - "version": "1.0.4", - "integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E=", - "dev": true - } + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jshint/node_modules/strip-json-comments": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", + "integrity": "sha512-AOPG8EBc5wAikaG1/7uFCNFJwnKOuQwFTpYBdTW6OvWHeZBQBrAA/amefHGrEiOnCPcLFZK6FUPtWVKpQVIRgg==", + "dev": true, + "bin": { + "strip-json-comments": "cli.js" + }, + "engines": { + "node": ">=0.8.0" } }, - "json-schema": { - "version": "0.2.3", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "peer": true + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", "dev": true }, - "json-schema-traverse": { + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "dev": true + }, + "node_modules/json-schema-traverse": { "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, - "json-stable-stringify-without-jsonify": { + "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", - "dev": true + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "peer": true }, - "json-stringify-safe": { + "node_modules/json-stringify-safe": { "version": "5.0.1", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", "dev": true }, - "jsprim": { - "version": "1.4.1", - "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", "dev": true, - "requires": { + "dependencies": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", - "json-schema": "0.2.3", + "json-schema": "0.4.0", "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" } }, - "just-debounce": { - "version": "1.1.0", - "integrity": "sha512-qpcRocdkUmf+UTNBYx5w6dexX5J31AKK1OmPwH630a83DdVVUIngk55RSAiIGpQyoH0dlr872VHfPjnQnK1qDQ==", - "dev": true - }, - "just-extend": { + "node_modules/just-extend": { "version": "4.2.1", + "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-4.2.1.tgz", "integrity": "sha512-g3UB796vUFIY90VIv/WX3L2c8CS2MdWUww3CNrYmqza1Fg0DURc2K/O4YrnklBdQarSJ/y8JnJYDGc+1iumQjg==", "dev": true }, - "kind-of": { - "version": "6.0.3", - "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", - "dev": true - }, - "last-run": { - "version": "1.1.1", - "integrity": "sha1-RblpQsF7HHnHchmCWbqUO+v4yls=", - "dev": true, - "requires": { - "default-resolution": "^2.0.0", - "es6-weak-map": "^2.0.1" - } - }, - "lazystream": { - "version": "1.0.0", - "integrity": "sha1-9plf4PggOS9hOWvolGJAe7dxaOQ=", - "dev": true, - "requires": { - "readable-stream": "^2.0.5" - } - }, - "lcid": { - "version": "1.0.0", - "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "node_modules/keyv": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.3.tgz", + "integrity": "sha512-QCiSav9WaX1PgETJ+SpNnx2PRRapJ/oRSXM4VO5OGYGSjrxbKPVFVhB3l2OCbLCk329N8qyAtsJjSjvVBWzEug==", "dev": true, - "requires": { - "invert-kv": "^1.0.0" + "peer": true, + "dependencies": { + "json-buffer": "3.0.1" } }, - "lead": { - "version": "1.0.0", - "integrity": "sha1-bxT5mje+Op3XhPVJVpDlkDRm7kI=", + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "dev": true, - "requires": { - "flush-write-stream": "^1.0.2" + "engines": { + "node": ">=0.10.0" } }, - "left-pad": { + "node_modules/left-pad": { "version": "1.3.0", + "resolved": "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz", "integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==", + "deprecated": "use String.prototype.padStart()", "dev": true }, - "levn": { - "version": "0.3.0", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" - } - }, - "liftoff": { - "version": "3.1.0", - "integrity": "sha512-DlIPlJUkCV0Ips2zf2pJP0unEoT1kwYhiiPUGF3s/jtxTCjziNLoiVVh+jqWOWeFi6mmwQ5fNxvAUyPad4Dfog==", + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, - "requires": { - "extend": "^3.0.0", - "findup-sync": "^3.0.0", - "fined": "^1.0.1", - "flagged-respawn": "^1.0.0", - "is-plain-object": "^2.0.4", - "object.map": "^1.0.0", - "rechoir": "^0.6.2", - "resolve": "^1.1.7" + "peer": true, + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" } }, - "load-json-file": { - "version": "1.1.0", - "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", + "node_modules/loader-runner": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^2.2.0", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0", - "strip-bom": "^2.0.0" + "engines": { + "node": ">=6.11.5" } }, - "locate-path": { - "version": "3.0.0", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - }, "dependencies": { - "path-exists": { - "version": "3.0.0", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - } + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "lodash": { + "node_modules/lodash": { "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, - "lodash.assign": { - "version": "4.2.0", - "integrity": "sha1-DZnzzNem0mHRm9rrkkUAXShYCOc=", + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "dev": true }, - "lodash.clonedeep": { - "version": "4.5.0", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", + "node_modules/lodash.flattendeep": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz", + "integrity": "sha512-uHaJFihxmJcEX3kT4I23ABqKKalJ/zDrDg0lsFtc1h+3uw49SIJ5beyhx5ExVRti3AvKoOJngIj7xz3oylPdWQ==", "dev": true }, - "lodash.get": { + "node_modules/lodash.get": { "version": "4.4.2", - "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", - "dev": true - }, - "lodash.isobject": { - "version": "3.0.2", - "integrity": "sha1-PI+41bW/S/kK4G4U8qUwpO2TXh0=", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", "dev": true }, - "lodash.merge": { + "node_modules/lodash.merge": { "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true + "dev": true, + "peer": true }, - "lodash.sortby": { + "node_modules/lodash.sortby": { "version": "4.7.0", - "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==", "dev": true }, - "log-symbols": { - "version": "2.2.0", - "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==", + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", "dev": true, - "requires": { - "chalk": "^2.0.1" + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "make-error": { - "version": "1.3.6", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true + "node_modules/log-symbols/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } }, - "make-error-cause": { - "version": "1.2.2", - "integrity": "sha1-3wOI/NCzeBbf8KX7gQiTl3fcvJ0=", + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, - "requires": { - "make-error": "^1.2.0" + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "make-iterator": { - "version": "1.0.1", - "integrity": "sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw==", + "node_modules/log-symbols/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "requires": { - "kind-of": "^6.0.2" + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" } }, - "map-cache": { - "version": "0.2.2", - "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "node_modules/log-symbols/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, - "map-visit": { - "version": "1.0.0", - "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "node_modules/log-symbols/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "requires": { - "object-visit": "^1.0.0" + "engines": { + "node": ">=8" } }, - "matchdep": { - "version": "2.0.0", - "integrity": "sha1-xvNINKDY28OzfCfui7yyfHd1WC4=", - "dev": true, - "requires": { - "findup-sync": "^2.0.0", - "micromatch": "^3.0.4", - "resolve": "^1.4.0", - "stack-trace": "0.0.10" - }, - "dependencies": { - "findup-sync": { - "version": "2.0.0", - "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", - "dev": true, - "requires": { - "detect-file": "^1.0.0", - "is-glob": "^3.1.0", - "micromatch": "^3.0.4", - "resolve-dir": "^1.0.1" - } - }, - "is-glob": { - "version": "3.1.0", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "^2.1.0" - } - } + "node_modules/log-symbols/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "math-random": { - "version": "1.0.4", - "integrity": "sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A==", - "dev": true + "node_modules/loupe": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.0" + } }, - "merge-stream": { - "version": "2.0.0", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } }, - "micromatch": { - "version": "3.1.10", - "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", - "dev": true, - "requires": { - "arr-diff": "^4.0.0", - "array-unique": "^0.3.2", - "braces": "^2.3.1", - "define-property": "^2.0.2", - "extend-shallow": "^3.0.2", - "extglob": "^2.0.4", - "fragment-cache": "^0.2.1", - "kind-of": "^6.0.2", - "nanomatch": "^1.2.9", - "object.pick": "^1.3.0", - "regex-not": "^1.0.0", - "snapdragon": "^0.8.1", - "to-regex": "^3.0.2" + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "mime-db": { - "version": "1.50.0", - "integrity": "sha512-9tMZCDlYHqeERXEHO9f/hKfNXhre5dK2eE/krIvUjZbS2KPcqGDfNShIWS1uW9XOTKQKqK6qbeOci18rbfW77A==", + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, - "mime-types": { - "version": "2.1.33", - "integrity": "sha512-plLElXp7pRDd0bNZHw+nMd52vRYjLwQjygaNg7ddJ2uJtTlmnTCjWuPKxVu6//AdaRuME84SvLW91sIkBqGT0g==", + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "dev": true, - "requires": { - "mime-db": "1.50.0" + "engines": { + "node": ">= 8" } }, - "mimic-fn": { - "version": "2.1.0", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true - }, - "minimatch": { - "version": "3.0.4", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", "dev": true, - "requires": { - "brace-expansion": "^1.1.7" + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" } }, - "minimist": { - "version": "1.2.5", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "dev": true + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } }, - "mixin-deep": { - "version": "1.3.2", - "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, - "requires": { - "for-in": "^1.0.2", - "is-extendable": "^1.0.1" - }, "dependencies": { - "is-extendable": { - "version": "1.0.1", - "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", - "dev": true, - "requires": { - "is-plain-object": "^2.0.4" - } - } + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" } }, - "mkdirp": { - "version": "0.5.5", - "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, - "requires": { - "minimist": "^1.2.5" + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" } }, - "mocha": { - "version": "6.2.3", - "integrity": "sha512-0R/3FvjIGH3eEuG17ccFPk117XL2rWxatr81a57D+r/x2uTYZRbdZ4oVidEUMh2W2TJDa7MdAb12Lm2/qrKajg==", + "node_modules/mocha": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.2.0.tgz", + "integrity": "sha512-IDY7fl/BecMwFHzoqF2sg/SHHANeBoMMXFlS9r0OXKDssYE1M5O43wUY/9BVPeIvfH2zmEbBfseqN9gBQZzXkg==", "dev": true, - "requires": { - "ansi-colors": "3.2.3", + "dependencies": { + "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", - "debug": "3.2.6", - "diff": "3.5.0", - "escape-string-regexp": "1.0.5", - "find-up": "3.0.0", - "glob": "7.1.3", - "growl": "1.10.5", + "chokidar": "3.5.3", + "debug": "4.3.4", + "diff": "5.0.0", + "escape-string-regexp": "4.0.0", + "find-up": "5.0.0", + "glob": "7.2.0", "he": "1.2.0", - "js-yaml": "3.13.1", - "log-symbols": "2.2.0", - "minimatch": "3.0.4", - "mkdirp": "0.5.4", - "ms": "2.1.1", - "node-environment-flags": "1.0.5", - "object.assign": "4.1.0", - "strip-json-comments": "2.0.1", - "supports-color": "6.0.0", - "which": "1.3.1", - "wide-align": "1.1.3", - "yargs": "13.3.2", - "yargs-parser": "13.1.2", - "yargs-unparser": "1.6.0" - }, - "dependencies": { - "ansi-colors": { - "version": "3.2.3", - "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==", - "dev": true - }, - "ansi-regex": { - "version": "4.1.0", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "dev": true - }, - "camelcase": { - "version": "5.3.1", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, - "cliui": { - "version": "5.0.0", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", - "dev": true, - "requires": { - "string-width": "^3.1.0", - "strip-ansi": "^5.2.0", - "wrap-ansi": "^5.1.0" - } - }, - "debug": { - "version": "3.2.6", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "esprima": { - "version": "4.0.1", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true - }, - "find-up": { - "version": "3.0.0", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "get-caller-file": { - "version": "2.0.5", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true - }, - "glob": { - "version": "7.1.3", - "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "has-flag": { - "version": "3.0.0", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "js-yaml": { - "version": "3.13.1", - "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "mkdirp": { - "version": "0.5.4", - "integrity": "sha512-iG9AK/dJLtJ0XNgTuDbSyNS3zECqDlAhnQW4CsNxBG3LQJBbHmRX1egw39DmtOdCAqY+dKXV+sgPgilNWUKMVw==", - "dev": true, - "requires": { - "minimist": "^1.2.5" - } - }, - "ms": { - "version": "2.1.1", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, - "object.assign": { - "version": "4.1.0", - "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", - "dev": true, - "requires": { - "define-properties": "^1.1.2", - "function-bind": "^1.1.1", - "has-symbols": "^1.0.0", - "object-keys": "^1.0.11" - } - }, - "require-main-filename": { - "version": "2.0.0", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "dev": true - }, - "string-width": { - "version": "3.1.0", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", - "dev": true, - "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" - } - }, - "strip-ansi": { - "version": "5.2.0", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "requires": { - "ansi-regex": "^4.1.0" - } - }, - "supports-color": { - "version": "6.0.0", - "integrity": "sha512-on9Kwidc1IUQo+bQdhi8+Tijpo0e1SS6RoGo2guUwn5vdaxw8RXOF9Vb2ws+ihWOmh4JnCJOvaziZWP1VABaLg==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "which-module": { - "version": "2.0.0", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "dev": true - }, - "wrap-ansi": { - "version": "5.1.0", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" - } - }, - "y18n": { - "version": "4.0.3", - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", - "dev": true - }, - "yargs": { - "version": "13.3.2", - "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", - "dev": true, - "requires": { - "cliui": "^5.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^3.0.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^13.1.2" - } - }, - "yargs-parser": { - "version": "13.1.2", - "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - } + "js-yaml": "4.1.0", + "log-symbols": "4.1.0", + "minimatch": "5.0.1", + "ms": "2.1.3", + "nanoid": "3.3.3", + "serialize-javascript": "6.0.0", + "strip-json-comments": "3.1.1", + "supports-color": "8.1.1", + "workerpool": "6.2.1", + "yargs": "16.2.0", + "yargs-parser": "20.2.4", + "yargs-unparser": "2.0.0" + }, + "bin": { + "_mocha": "bin/_mocha", + "mocha": "bin/mocha.js" + }, + "engines": { + "node": ">= 14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mochajs" } }, - "mocha-jsdom": { + "node_modules/mocha-jsdom": { "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mocha-jsdom/-/mocha-jsdom-2.0.0.tgz", "integrity": "sha512-+3D++FPXHXEesbBD7Q/r4dkc3XzVFMPLJVIECaQ685dj9qKQYzliqX8IXyIUbUL4x1QfgD9h8Zao8cn03NKKEA==", "dev": true, - "requires": { + "dependencies": { "jsdom": "^11.11.0" + }, + "peerDependencies": { + "mocha": "*" } }, - "modify-filename": { - "version": "1.1.0", - "integrity": "sha1-mi3sg4Bvuy2XXyK+7IWcoms5OqE=", - "dev": true + "node_modules/mocha/node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "ms": { - "version": "2.0.0", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true + "node_modules/mocha/node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, - "mute-stdout": { - "version": "1.0.1", - "integrity": "sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg==", + "node_modules/mocha/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/mocha/node_modules/minimatch": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mocha/node_modules/minimatch/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/mocha/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true }, - "nan": { - "version": "2.15.0", - "integrity": "sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ==", + "node_modules/mocha/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, - "optional": true + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true }, - "nanomatch": { - "version": "1.2.13", - "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "node_modules/nanoid": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.3.tgz", + "integrity": "sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w==", "dev": true, - "requires": { - "arr-diff": "^4.0.0", - "array-unique": "^0.3.2", - "define-property": "^2.0.2", - "extend-shallow": "^3.0.2", - "fragment-cache": "^0.2.1", - "is-windows": "^1.0.2", - "kind-of": "^6.0.2", - "object.pick": "^1.3.0", - "regex-not": "^1.0.0", - "snapdragon": "^0.8.1", - "to-regex": "^3.0.1" + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, - "neo-async": { - "version": "2.6.2", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "peer": true + }, + "node_modules/natural-compare-lite": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz", + "integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==", "dev": true }, - "next-tick": { - "version": "1.0.0", - "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, - "nise": { - "version": "4.1.0", - "integrity": "sha512-eQMEmGN/8arp0xsvGoQ+B1qvSkR73B1nWSCh7nOt5neMCtwcQVYQGdzQMhcNscktTsWB54xnlSQFzOAPJD8nXA==", + "node_modules/nise": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.4.tgz", + "integrity": "sha512-8+Ib8rRJ4L0o3kfmyVCL7gzrohyDe0cMFTBa2d364yIrEGMEoetznKJx899YxjybU6bL9SQkYPSBBs1gyYs8Xg==", "dev": true, - "requires": { - "@sinonjs/commons": "^1.7.0", - "@sinonjs/fake-timers": "^6.0.0", + "dependencies": { + "@sinonjs/commons": "^2.0.0", + "@sinonjs/fake-timers": "^10.0.2", "@sinonjs/text-encoding": "^0.7.1", "just-extend": "^4.0.2", "path-to-regexp": "^1.7.0" } }, - "node-environment-flags": { - "version": "1.0.5", - "integrity": "sha512-VNYPRfGfmZLx0Ye20jWzHUjyTW/c+6Wq+iLhDzUI4XmhrDd9l/FozXV3F2xOaXjvp0co0+v1YSR3CMP6g+VvLQ==", - "dev": true, - "requires": { - "object.getownpropertydescriptors": "^2.0.3", - "semver": "^5.7.0" - } - }, - "nopt": { - "version": "3.0.6", - "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "node_modules/nise/node_modules/@sinonjs/commons": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-2.0.0.tgz", + "integrity": "sha512-uLa0j859mMrg2slwQYdO/AkrOfmH+X6LTVmNTS9CqexuE2IvVORIkSpJLqePAbEnKJ77aMmCwr1NUZ57120Xcg==", "dev": true, - "requires": { - "abbrev": "1" + "dependencies": { + "type-detect": "4.0.8" } }, - "normalize-package-data": { - "version": "2.5.0", - "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "node_modules/nise/node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", "dev": true, - "requires": { - "hosted-git-info": "^2.1.4", - "resolve": "^1.10.0", - "semver": "2 || 3 || 4 || 5", - "validate-npm-package-license": "^3.0.1" + "dependencies": { + "@sinonjs/commons": "^3.0.0" } }, - "normalize-path": { + "node_modules/nise/node_modules/@sinonjs/fake-timers/node_modules/@sinonjs/commons": { "version": "3.0.0", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true - }, - "now-and-later": { - "version": "2.0.1", - "integrity": "sha512-KGvQ0cB70AQfg107Xvs/Fbu+dGmZoTRJp2TaPwcwQm3/7PteUyN2BCgk8KBMPGBUXZdVwyWS8fDCGFygBm19UQ==", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", + "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", "dev": true, - "requires": { - "once": "^1.3.2" + "dependencies": { + "type-detect": "4.0.8" } }, - "npm-run-path": { - "version": "3.1.0", - "integrity": "sha512-Dbl4A/VfiVGLgQv29URL9xshU8XDY1GeLy+fsaZ1AA8JDSfjvr5P5+pzRbWqRSBxk6/DW7MIh8lTM/PaGnP2kg==", + "node_modules/node-preload": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/node-preload/-/node-preload-0.2.1.tgz", + "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", "dev": true, - "requires": { - "path-key": "^3.0.0" + "dependencies": { + "process-on-spawn": "^1.0.0" + }, + "engines": { + "node": ">=8" } }, - "number-is-nan": { - "version": "1.0.1", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - }, - "nwsapi": { - "version": "2.2.0", - "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", - "dev": true - }, - "oauth-sign": { - "version": "0.9.0", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", - "dev": true - }, - "object-assign": { - "version": "4.1.1", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "node_modules/node-releases": { + "version": "2.0.13", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", + "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", "dev": true }, - "object-copy": { - "version": "0.1.0", - "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "dev": true, - "requires": { - "copy-descriptor": "^0.1.0", - "define-property": "^0.2.5", - "kind-of": "^3.0.3" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - }, - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "engines": { + "node": ">=0.10.0" } }, - "object-inspect": { - "version": "1.11.0", - "integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==", + "node_modules/nwsapi": { + "version": "2.2.7", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.7.tgz", + "integrity": "sha512-ub5E4+FBPKwAZx0UwIQOjYWGHTEq5sPqHQNRN8Z9e4A7u3Tj1weLJsL59yH9vmvqEtBHaOmT6cYQKIZOxp35FQ==", "dev": true }, - "object-keys": { - "version": "1.1.1", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true + "node_modules/nyc": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/nyc/-/nyc-15.1.0.tgz", + "integrity": "sha512-jMW04n9SxKdKi1ZMGhvUTHBN0EICCRkHemEoE5jm6mTYcqcdas0ATzgUgejlQUHMvpnOZqGB5Xxsv9KxJW1j8A==", + "dev": true, + "dependencies": { + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "caching-transform": "^4.0.0", + "convert-source-map": "^1.7.0", + "decamelize": "^1.2.0", + "find-cache-dir": "^3.2.0", + "find-up": "^4.1.0", + "foreground-child": "^2.0.0", + "get-package-type": "^0.1.0", + "glob": "^7.1.6", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-hook": "^3.0.0", + "istanbul-lib-instrument": "^4.0.0", + "istanbul-lib-processinfo": "^2.0.2", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.0.2", + "make-dir": "^3.0.0", + "node-preload": "^0.2.1", + "p-map": "^3.0.0", + "process-on-spawn": "^1.0.0", + "resolve-from": "^5.0.0", + "rimraf": "^3.0.0", + "signal-exit": "^3.0.2", + "spawn-wrap": "^2.0.0", + "test-exclude": "^6.0.0", + "yargs": "^15.0.2" + }, + "bin": { + "nyc": "bin/nyc.js" + }, + "engines": { + "node": ">=8.9" + } }, - "object-visit": { - "version": "1.0.1", - "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "node_modules/nyc/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, - "requires": { - "isobject": "^3.0.0" + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "object.assign": { - "version": "4.1.2", - "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "node_modules/nyc/node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, - "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", - "object-keys": "^1.1.1" + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" } }, - "object.defaults": { - "version": "1.1.0", - "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", + "node_modules/nyc/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "requires": { - "array-each": "^1.0.1", - "array-slice": "^1.0.0", - "for-own": "^1.0.0", - "isobject": "^3.0.0" + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" } }, - "object.getownpropertydescriptors": { - "version": "2.1.3", - "integrity": "sha512-VdDoCwvJI4QdC6ndjpqFmoL3/+HxffFBbcJzKi5hwLLqqx3mdbedRpfZDdK0SrOSauj8X4GzBvnDZl4vTN7dOw==", + "node_modules/nyc/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/nyc/node_modules/find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.19.1" + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/avajs/find-cache-dir?sponsor=1" } }, - "object.map": { - "version": "1.0.1", - "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", + "node_modules/nyc/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, - "requires": { - "for-own": "^1.0.0", - "make-iterator": "^1.0.0" + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "object.omit": { - "version": "2.0.1", - "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", + "node_modules/nyc/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, - "requires": { - "for-own": "^0.1.4", - "is-extendable": "^0.1.1" + "dependencies": { + "p-locate": "^4.1.0" }, + "engines": { + "node": ">=8" + } + }, + "node_modules/nyc/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, "dependencies": { - "for-own": { - "version": "0.1.5", - "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", - "dev": true, - "requires": { - "for-in": "^1.0.1" - } - } + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "object.pick": { - "version": "1.3.0", - "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "node_modules/nyc/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, - "requires": { - "isobject": "^3.0.1" + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" } }, - "object.reduce": { - "version": "1.0.1", - "integrity": "sha1-b+NI8qx/oPlcpiEiZZkJaCW7A60=", + "node_modules/nyc/node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, - "requires": { - "for-own": "^1.0.0", - "make-iterator": "^1.0.0" + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "once": { - "version": "1.4.0", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "node_modules/nyc/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true, - "requires": { - "wrappy": "1" + "engines": { + "node": ">=8" } }, - "onetime": { - "version": "5.1.2", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "node_modules/nyc/node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, - "requires": { - "mimic-fn": "^2.1.0" + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" } }, - "optionator": { - "version": "0.8.3", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "node_modules/nyc/node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true + }, + "node_modules/nyc/node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, - "requires": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" }, + "engines": { + "node": ">=8" + } + }, + "node_modules/nyc/node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, "dependencies": { - "fast-levenshtein": { - "version": "2.0.6", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true - } + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" } }, - "ordered-read-streams": { - "version": "1.0.1", - "integrity": "sha1-d8DLN8QVJdZBZtmQ/61+xqDhNj4=", + "node_modules/oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", "dev": true, - "requires": { - "readable-stream": "^2.0.1" + "engines": { + "node": "*" } }, - "os-locale": { + "node_modules/once": { "version": "1.4.0", - "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", "dev": true, - "requires": { - "lcid": "^1.0.0" + "dependencies": { + "wrappy": "1" } }, - "p-finally": { - "version": "2.0.1", - "integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw==", - "dev": true + "node_modules/optionator": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", + "integrity": "sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==", + "dev": true, + "peer": true, + "dependencies": { + "@aashutoshrathi/word-wrap": "^1.2.3", + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } }, - "p-limit": { - "version": "2.3.0", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, - "requires": { - "p-try": "^2.0.0" + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "p-locate": { + "node_modules/p-map": { "version": "3.0.0", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-3.0.0.tgz", + "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", "dev": true, - "requires": { - "p-limit": "^2.0.0" + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=8" } }, - "p-try": { + "node_modules/p-try": { "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true - }, - "parse-filepath": { - "version": "1.0.2", - "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", "dev": true, - "requires": { - "is-absolute": "^1.0.0", - "map-cache": "^0.2.0", - "path-root": "^0.1.1" + "engines": { + "node": ">=6" } }, - "parse-glob": { - "version": "3.0.4", - "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", + "node_modules/package-hash": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-4.0.0.tgz", + "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", "dev": true, - "requires": { - "glob-base": "^0.3.0", - "is-dotfile": "^1.0.0", - "is-extglob": "^1.0.0", - "is-glob": "^2.0.0" - }, "dependencies": { - "is-extglob": { - "version": "1.0.0", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", - "dev": true - }, - "is-glob": { - "version": "2.0.1", - "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", - "dev": true, - "requires": { - "is-extglob": "^1.0.0" - } - } + "graceful-fs": "^4.1.15", + "hasha": "^5.0.0", + "lodash.flattendeep": "^4.4.0", + "release-zalgo": "^1.0.0" + }, + "engines": { + "node": ">=8" } }, - "parse-json": { - "version": "2.2.0", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, - "requires": { - "error-ex": "^1.2.0" + "peer": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" } }, - "parse-node-version": { - "version": "1.0.1", - "integrity": "sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==", - "dev": true - }, - "parse-passwd": { - "version": "1.0.0", - "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", - "dev": true - }, - "parse5": { + "node_modules/parse5": { "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", "dev": true }, - "pascalcase": { - "version": "0.1.1", - "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", - "dev": true - }, - "path-dirname": { - "version": "1.0.2", - "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", - "dev": true - }, - "path-exists": { - "version": "2.1.0", - "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, - "requires": { - "pinkie-promise": "^2.0.0" + "engines": { + "node": ">=8" } }, - "path-is-absolute": { + "node_modules/path-is-absolute": { "version": "1.0.1", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "path-key": { + "node_modules/path-key": { "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true - }, - "path-parse": { - "version": "1.0.7", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true - }, - "path-root": { - "version": "0.1.1", - "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", "dev": true, - "requires": { - "path-root-regex": "^0.1.0" + "engines": { + "node": ">=8" } }, - "path-root-regex": { - "version": "0.1.2", - "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, - "path-to-regexp": { + "node_modules/path-to-regexp": { "version": "1.8.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz", "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", "dev": true, - "requires": { - "isarray": "0.0.1" - }, "dependencies": { - "isarray": { - "version": "0.0.1", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - } + "isarray": "0.0.1" } }, - "path-type": { - "version": "1.1.0", - "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0" + "engines": { + "node": ">=8" } }, - "pathval": { + "node_modules/pathval": { "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", - "dev": true + "dev": true, + "engines": { + "node": "*" + } }, - "performance-now": { + "node_modules/performance-now": { "version": "2.1.0", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", - "dev": true - }, - "pify": { - "version": "2.3.0", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==", "dev": true }, - "pinkie": { - "version": "2.0.4", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", "dev": true }, - "pinkie-promise": { - "version": "2.0.1", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true, - "requires": { - "pinkie": "^2.0.0" + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" } }, - "plugin-error": { - "version": "0.1.2", - "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", - "dev": true, - "requires": { - "ansi-cyan": "^0.1.1", - "ansi-red": "^0.1.1", - "arr-diff": "^1.0.1", - "arr-union": "^2.0.1", - "extend-shallow": "^1.1.2" - }, - "dependencies": { - "arr-diff": { - "version": "1.1.0", - "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", - "dev": true, - "requires": { - "arr-flatten": "^1.0.1", - "array-slice": "^0.2.3" - } - }, - "arr-union": { - "version": "2.1.0", - "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", - "dev": true - }, - "array-slice": { - "version": "0.2.3", - "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", - "dev": true - }, - "extend-shallow": { - "version": "1.1.4", - "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", - "dev": true, - "requires": { - "kind-of": "^1.1.0" - } - }, - "kind-of": { - "version": "1.1.0", - "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", - "dev": true - } + "node_modules/pkg-dir": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-7.0.0.tgz", + "integrity": "sha512-Ie9z/WINcxxLp27BKOCHGde4ITq9UklYKDzVo1nhk5sqGEXU3FpkwP5GM2voTGJkGd9B3Otl+Q4uwSOeSUtOBA==", + "dev": true, + "dependencies": { + "find-up": "^6.3.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "pn": { - "version": "1.1.0", - "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", - "dev": true + "node_modules/pkg-dir/node_modules/find-up": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-6.3.0.tgz", + "integrity": "sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw==", + "dev": true, + "dependencies": { + "locate-path": "^7.1.0", + "path-exists": "^5.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "posix-character-classes": { - "version": "0.1.1", - "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", - "dev": true + "node_modules/pkg-dir/node_modules/locate-path": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", + "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", + "dev": true, + "dependencies": { + "p-locate": "^6.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "prelude-ls": { - "version": "1.1.2", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", - "dev": true + "node_modules/pkg-dir/node_modules/p-limit": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", + "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "preserve": { - "version": "0.2.0", - "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", - "dev": true + "node_modules/pkg-dir/node_modules/p-locate": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", + "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", + "dev": true, + "dependencies": { + "p-limit": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "pretty-hrtime": { - "version": "1.0.3", - "integrity": "sha1-t+PqQkNaTJsnWdmeDyAesZWALuE=", - "dev": true + "node_modules/pkg-dir/node_modules/path-exists": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", + "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } }, - "process-nextick-args": { - "version": "2.0.1", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", - "dev": true + "node_modules/pkg-dir/node_modules/yocto-queue": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", + "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", + "dev": true, + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "psl": { - "version": "1.8.0", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "node_modules/pn": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pn/-/pn-1.1.0.tgz", + "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", "dev": true }, - "pump": { - "version": "3.0.0", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true, - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" + "peer": true, + "engines": { + "node": ">= 0.8.0" } }, - "pumpify": { - "version": "1.5.1", - "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", - "dev": true, - "requires": { - "duplexify": "^3.6.0", - "inherits": "^2.0.3", - "pump": "^2.0.0" - }, - "dependencies": { - "pump": { - "version": "2.0.1", - "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", - "dev": true, - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - } + "node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" } }, - "punycode": { - "version": "2.1.1", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true + "node_modules/process-on-spawn": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/process-on-spawn/-/process-on-spawn-1.0.0.tgz", + "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", + "dev": true, + "dependencies": { + "fromentries": "^1.2.0" + }, + "engines": { + "node": ">=8" + } }, - "qs": { - "version": "6.5.2", - "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "node_modules/psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", "dev": true }, - "randomatic": { - "version": "3.1.1", - "integrity": "sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw==", + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "dev": true, - "requires": { - "is-number": "^4.0.0", - "kind-of": "^6.0.0", - "math-random": "^1.0.1" - }, "dependencies": { - "is-number": { - "version": "4.0.0", - "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", - "dev": true - } + "end-of-stream": "^1.1.0", + "once": "^1.3.1" } }, - "rcfinder": { - "version": "0.1.9", - "integrity": "sha1-8+gPOH3fmugK4wpBADKWQuroERU=", + "node_modules/punycode": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", + "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", "dev": true, - "requires": { - "lodash.clonedeep": "^4.3.2" + "engines": { + "node": ">=6" } }, - "rcloader": { - "version": "0.2.2", - "integrity": "sha1-WNIpi0YtC5v9ITPSoex0+9cFxxc=", + "node_modules/qs": { + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", "dev": true, - "requires": { - "lodash.assign": "^4.2.0", - "lodash.isobject": "^3.0.2", - "lodash.merge": "^4.6.0", - "rcfinder": "^0.1.6" + "engines": { + "node": ">=0.6" } }, - "read-pkg": { - "version": "1.1.0", - "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "dev": true, - "requires": { - "load-json-file": "^1.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^1.0.0" - } + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, - "read-pkg-up": { - "version": "1.0.1", - "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", "dev": true, - "requires": { - "find-up": "^1.0.0", - "read-pkg": "^1.0.0" + "dependencies": { + "safe-buffer": "^5.1.0" } }, - "readable-stream": { - "version": "2.3.7", - "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "node_modules/readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==", "dev": true, - "requires": { + "dependencies": { "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" } }, - "readdirp": { - "version": "2.2.1", - "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, - "requires": { - "graceful-fs": "^4.1.11", - "micromatch": "^3.1.10", - "readable-stream": "^2.0.2" + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" } }, - "rechoir": { - "version": "0.6.2", - "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "node_modules/rechoir": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz", + "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", "dev": true, - "requires": { - "resolve": "^1.1.6" + "dependencies": { + "resolve": "^1.9.0" + }, + "engines": { + "node": ">= 0.10" } }, - "regex-cache": { - "version": "0.4.4", - "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", + "node_modules/regenerate": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", + "integrity": "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==", + "dev": true + }, + "node_modules/regenerate-unicode-properties": { + "version": "10.1.1", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.1.1.tgz", + "integrity": "sha512-X007RyZLsCJVVrjgEFVpLUTZwyOZk3oiL75ZcuYjlIWd6rNJtOjkBwQc5AsRrpbKVkxN6sklw/k/9m2jJYOf8Q==", "dev": true, - "requires": { - "is-equal-shallow": "^0.1.3" + "dependencies": { + "regenerate": "^1.4.2" + }, + "engines": { + "node": ">=4" } }, - "regex-not": { - "version": "1.0.2", - "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "node_modules/regenerator-runtime": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.0.tgz", + "integrity": "sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==", + "dev": true + }, + "node_modules/regenerator-transform": { + "version": "0.15.2", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.15.2.tgz", + "integrity": "sha512-hfMp2BoF0qOk3uc5V20ALGDS2ddjQaLrdl7xrGXvAIow7qeWRM2VA2HuCHkUKk9slq3VwEwLNK3DFBqDfPGYtg==", "dev": true, - "requires": { - "extend-shallow": "^3.0.2", - "safe-regex": "^1.1.0" + "dependencies": { + "@babel/runtime": "^7.8.4" } }, - "remove-bom-buffer": { - "version": "3.0.0", - "integrity": "sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ==", + "node_modules/regexpu-core": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-5.3.2.tgz", + "integrity": "sha512-RAM5FlZz+Lhmo7db9L298p2vHP5ZywrVXmVXpmAD9GuL5MPH6t9ROw1iA/wfHkQ76Qe7AaPF0nGuim96/IrQMQ==", "dev": true, - "requires": { - "is-buffer": "^1.1.5", - "is-utf8": "^0.2.1" + "dependencies": { + "@babel/regjsgen": "^0.8.0", + "regenerate": "^1.4.2", + "regenerate-unicode-properties": "^10.1.0", + "regjsparser": "^0.9.1", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.1.0" + }, + "engines": { + "node": ">=4" } }, - "remove-bom-stream": { - "version": "1.2.0", - "integrity": "sha1-BfGlk/FuQuH7kOv1nejlaVJflSM=", + "node_modules/regjsparser": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.9.1.tgz", + "integrity": "sha512-dQUtn90WanSNl+7mQKcXAgZxvUe7Z0SqXlgzv0za4LwiUhyzBC58yQO3liFoUgu8GiJVInAhJjkj1N0EtQ5nkQ==", "dev": true, - "requires": { - "remove-bom-buffer": "^3.0.0", - "safe-buffer": "^5.1.0", - "through2": "^2.0.3" + "dependencies": { + "jsesc": "~0.5.0" + }, + "bin": { + "regjsparser": "bin/parser" } }, - "remove-trailing-separator": { - "version": "1.1.0", - "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", - "dev": true - }, - "repeat-element": { - "version": "1.1.4", - "integrity": "sha512-LFiNfRcSu7KK3evMyYOuCzv3L10TW7yC1G2/+StMjK8Y6Vqd2MG7r/Qjw4ghtuCOjFvlnms/iMmLqpvW/ES/WQ==", - "dev": true - }, - "repeat-string": { - "version": "1.6.1", - "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", - "dev": true - }, - "replace-ext": { - "version": "1.0.1", - "integrity": "sha512-yD5BHCe7quCgBph4rMQ+0KkIRKwWCrHDOX1p1Gp6HwjPM5kVoCdKGNhN7ydqqsX6lJEnQDKZ/tFMiEdQ1dvPEw==", - "dev": true - }, - "replace-homedir": { - "version": "1.0.0", - "integrity": "sha1-6H9tUTuSjd6AgmDBK+f+xv9ueYw=", + "node_modules/regjsparser/node_modules/jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==", "dev": true, - "requires": { - "homedir-polyfill": "^1.0.1", - "is-absolute": "^1.0.0", - "remove-trailing-separator": "^1.1.0" + "bin": { + "jsesc": "bin/jsesc" } }, - "replacestream": { - "version": "4.0.3", - "integrity": "sha512-AC0FiLS352pBBiZhd4VXB1Ab/lh0lEgpP+GGvZqbQh8a5cmXVoTe5EX/YeTFArnp4SRGTHh1qCHu9lGs1qG8sA==", + "node_modules/release-zalgo": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz", + "integrity": "sha512-gUAyHVHPPC5wdqX/LG4LWtRYtgjxyX78oanFNTMMyFEfOqdC54s3eE82imuWKbOeqYht2CrNf64Qb8vgmmtZGA==", "dev": true, - "requires": { - "escape-string-regexp": "^1.0.3", - "object-assign": "^4.0.1", - "readable-stream": "^2.0.2" + "dependencies": { + "es6-error": "^4.0.1" + }, + "engines": { + "node": ">=4" } }, - "request": { + "node_modules/request": { "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", "dev": true, - "requires": { + "dependencies": { "aws-sign2": "~0.7.0", "aws4": "^1.8.0", "caseless": "~0.12.0", @@ -4238,396 +6651,418 @@ "tough-cookie": "~2.5.0", "tunnel-agent": "^0.6.0", "uuid": "^3.3.2" + }, + "engines": { + "node": ">= 6" } }, - "request-promise-core": { + "node_modules/request-promise-core": { "version": "1.1.4", + "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.4.tgz", "integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==", "dev": true, - "requires": { + "dependencies": { "lodash": "^4.17.19" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "request": "^2.34" } }, - "request-promise-native": { + "node_modules/request-promise-native": { "version": "1.0.9", + "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.9.tgz", "integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==", + "deprecated": "request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142", "dev": true, - "requires": { + "dependencies": { "request-promise-core": "1.1.4", "stealthy-require": "^1.1.1", "tough-cookie": "^2.3.3" + }, + "engines": { + "node": ">=0.12.0" + }, + "peerDependencies": { + "request": "^2.34" } }, - "require-directory": { - "version": "2.1.1", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", - "dev": true - }, - "require-main-filename": { - "version": "1.0.1", - "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", - "dev": true - }, - "resolve": { - "version": "1.20.0", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "node_modules/request/node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", "dev": true, - "requires": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" + "bin": { + "uuid": "bin/uuid" } }, - "resolve-dir": { - "version": "1.0.1", - "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", "dev": true, - "requires": { - "expand-tilde": "^2.0.0", - "global-modules": "^1.0.0" + "engines": { + "node": ">=0.10.0" } }, - "resolve-options": { - "version": "1.1.0", - "integrity": "sha1-MrueOcBtZzONyTeMDW1gdFZq0TE=", + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", "dev": true, - "requires": { - "value-or-function": "^3.0.0" + "engines": { + "node": ">=0.10.0" } }, - "resolve-url": { - "version": "0.2.1", - "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", - "dev": true - }, - "ret": { - "version": "0.1.15", - "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", - "dev": true - }, - "rev-hash": { + "node_modules/require-main-filename": { "version": "2.0.0", - "integrity": "sha1-dyCiNu0MJY3z5kvsA+wEiwW5JMQ=", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, - "rev-path": { - "version": "2.0.0", - "integrity": "sha512-G5R2L9gYu9kEuqPfIFgO9gO+OhBWOAT83HyauOQmGHO6y9Fsa4acv+XsmNhNDrod0HDh1/VxJRmsffThzeHJlQ==", + "node_modules/resolve": { + "version": "1.22.6", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.6.tgz", + "integrity": "sha512-njhxM7mV12JfufShqGy3Rz8j11RPdLy4xi15UurGJeoHLfJpVXKdh3ueuOqbYUcDZnffr6X739JBo5LzyahEsw==", "dev": true, - "requires": { - "modify-filename": "^1.0.0" + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "safe-buffer": { - "version": "5.1.2", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true - }, - "safe-regex": { - "version": "1.1.0", - "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", "dev": true, - "requires": { - "ret": "~0.1.10" + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" } }, - "safer-buffer": { - "version": "2.1.2", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true - }, - "sax": { - "version": "1.2.4", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", - "dev": true + "node_modules/resolve-cwd/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } }, - "semver": { - "version": "5.7.1", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } }, - "semver-greatest-satisfied-range": { - "version": "1.1.0", - "integrity": "sha1-E+jCZYq5aRywzXEJMkAoDTb3els=", + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", "dev": true, - "requires": { - "sver-compat": "^1.5.0" + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" } }, - "set-blocking": { - "version": "2.0.0", - "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", - "dev": true + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, - "set-value": { - "version": "2.0.1", - "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", - "dev": true, - "requires": { - "extend-shallow": "^2.0.1", - "is-extendable": "^0.1.1", - "is-plain-object": "^2.0.3", - "split-string": "^3.0.1" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" } + ], + "dependencies": { + "queue-microtask": "^1.2.2" } }, - "shebang-command": { - "version": "2.0.0", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", "dev": true, - "requires": { - "shebang-regex": "^3.0.0" - } + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, - "shebang-regex": { - "version": "3.0.0", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, - "shelljs": { - "version": "0.3.0", - "integrity": "sha1-NZbmMHp4FUT1kfN9phg2DzHbV7E=", + "node_modules/sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", "dev": true }, - "side-channel": { - "version": "1.0.4", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "node_modules/schema-utils": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.2.0.tgz", + "integrity": "sha512-L0jRsrPpjdckP3oPug3/VxNKt2trR8TcabrM6FOAAlvC/9Phcmm+cuAgTlxBqdBR1WJx7Naj9WHw+aOmheSVbw==", "dev": true, - "requires": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.9.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" } }, - "signal-exit": { - "version": "3.0.5", - "integrity": "sha512-KWcOiKeQj6ZyXx7zq4YxSMgHRlod4czeBQZrPb8OKcohcqAXShm7E20kEMle9WBt26hFcAf0qLOcp5zmY7kOqQ==", - "dev": true - }, - "sinon": { - "version": "9.2.4", - "integrity": "sha512-zljcULZQsJxVra28qIAL6ow1Z9tpattkCTEJR4RBP3TGc00FcttsP5pK284Nas5WjMZU5Yzy3kAIp3B3KRf5Yg==", + "node_modules/schema-utils/node_modules/ajv": { + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "requires": { - "@sinonjs/commons": "^1.8.1", - "@sinonjs/fake-timers": "^6.0.1", - "@sinonjs/samsam": "^5.3.1", - "diff": "^4.0.2", - "nise": "^4.0.4", - "supports-color": "^7.1.0" + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/schema-utils/node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, "dependencies": { - "diff": { - "version": "4.0.2", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true - }, - "has-flag": { - "version": "4.0.0", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "supports-color": { - "version": "7.2.0", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" } }, - "slash": { + "node_modules/schema-utils/node_modules/json-schema-traverse": { "version": "1.0.0", - "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "dev": true }, - "snapdragon": { - "version": "0.8.2", - "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", - "dev": true, - "requires": { - "base": "^0.11.1", - "debug": "^2.2.0", - "define-property": "^0.2.5", - "extend-shallow": "^2.0.1", - "map-cache": "^0.2.2", - "source-map": "^0.5.6", - "source-map-resolve": "^0.5.0", - "use": "^3.1.0" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - }, - "extend-shallow": { - "version": "2.0.1", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - } + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" } }, - "snapdragon-node": { - "version": "2.1.1", - "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "node_modules/serialize-javascript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", "dev": true, - "requires": { - "define-property": "^1.0.0", - "isobject": "^3.0.0", - "snapdragon-util": "^3.0.1" - }, "dependencies": { - "define-property": { - "version": "1.0.0", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "dev": true, - "requires": { - "is-descriptor": "^1.0.0" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-descriptor": { - "version": "1.0.2", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "^1.0.0", - "is-data-descriptor": "^1.0.0", - "kind-of": "^6.0.2" - } - } + "randombytes": "^2.1.0" } }, - "snapdragon-util": { + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dev": true + }, + "node_modules/shallow-clone": { "version": "3.0.1", - "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", "dev": true, - "requires": { - "kind-of": "^3.2.0" - }, "dependencies": { - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" } }, - "sort-keys": { + "node_modules/shebang-command": { "version": "2.0.0", - "integrity": "sha1-ZYU1WEhh7JfXMNbPQYIuH1ZoQSg=", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, - "requires": { - "is-plain-obj": "^1.0.0" + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" } }, - "source-map": { - "version": "0.5.7", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true - }, - "source-map-resolve": { - "version": "0.5.3", - "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true, - "requires": { - "atob": "^2.1.2", - "decode-uri-component": "^0.2.0", - "resolve-url": "^0.2.1", - "source-map-url": "^0.4.0", - "urix": "^0.1.0" + "engines": { + "node": ">=8" } }, - "source-map-url": { - "version": "0.4.1", - "integrity": "sha512-cPiFOTLUKvJFIg4SKVScy4ilPPW6rFgMgfuZJPNoDuMs3nC1HbMUycBoJw77xFIp6z1UJQJOfx6C9GMH80DiTw==", + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, - "sparkles": { - "version": "1.0.1", - "integrity": "sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw==", - "dev": true + "node_modules/sinon": { + "version": "12.0.1", + "resolved": "https://registry.npmjs.org/sinon/-/sinon-12.0.1.tgz", + "integrity": "sha512-iGu29Xhym33ydkAT+aNQFBINakjq69kKO6ByPvTsm3yyIACfyQttRTP03aBP/I8GfhFmLzrnKwNNkr0ORb1udg==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^1.8.3", + "@sinonjs/fake-timers": "^8.1.0", + "@sinonjs/samsam": "^6.0.2", + "diff": "^5.0.0", + "nise": "^5.1.0", + "supports-color": "^7.2.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/sinon" + } }, - "spdx-correct": { - "version": "3.1.1", - "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "node_modules/sinon/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "requires": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" + "engines": { + "node": ">=8" } }, - "spdx-exceptions": { - "version": "2.3.0", - "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", - "dev": true + "node_modules/sinon/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } }, - "spdx-expression-parse": { - "version": "3.0.1", - "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, - "requires": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" + "engines": { + "node": ">=8" } }, - "spdx-license-ids": { - "version": "3.0.10", - "integrity": "sha512-oie3/+gKf7QtpitB0LYLETe+k8SifzsX4KixvpOsbI6S0kRiRQ5MKOio8eMSAKQ17N06+wdEOXRiId+zOxo0hA==", - "dev": true + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "split-string": { - "version": "3.1.0", - "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/spawn-wrap": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz", + "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", "dev": true, - "requires": { - "extend-shallow": "^3.0.0" + "dependencies": { + "foreground-child": "^2.0.0", + "is-windows": "^1.0.2", + "make-dir": "^3.0.0", + "rimraf": "^3.0.0", + "signal-exit": "^3.0.2", + "which": "^2.0.1" + }, + "engines": { + "node": ">=8" } }, - "sprintf-js": { + "node_modules/sprintf-js": { "version": "1.0.3", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "dev": true }, - "sshpk": { - "version": "1.16.1", - "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "node_modules/sshpk": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz", + "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", "dev": true, - "requires": { + "dependencies": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", "bcrypt-pbkdf": "^1.0.0", @@ -4637,803 +7072,883 @@ "jsbn": "~0.1.0", "safer-buffer": "^2.0.2", "tweetnacl": "~0.14.0" - } - }, - "stack-trace": { - "version": "0.0.10", - "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", - "dev": true - }, - "static-extend": { - "version": "0.1.2", - "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", - "dev": true, - "requires": { - "define-property": "^0.2.5", - "object-copy": "^0.1.0" }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - } + "bin": { + "sshpk-conv": "bin/sshpk-conv", + "sshpk-sign": "bin/sshpk-sign", + "sshpk-verify": "bin/sshpk-verify" + }, + "engines": { + "node": ">=0.10.0" } }, - "stealthy-require": { + "node_modules/stealthy-require": { "version": "1.1.1", - "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", - "dev": true - }, - "stream-exhaust": { - "version": "1.0.2", - "integrity": "sha512-b/qaq/GlBK5xaq1yrK9/zFcyRSTNxmcZwFLGSTG0mXgZl/4Z6GgiyYOXOvY7N3eEvFRAG1bkDRz5EPGSvPYQlw==", - "dev": true - }, - "stream-shift": { - "version": "1.0.1", - "integrity": "sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ==", - "dev": true - }, - "string-width": { - "version": "1.0.2", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", + "integrity": "sha512-ZnWpYnYugiOVEY5GkcuJK1io5V8QmNYChG62gSit9pQVGErXtrKuPC55ITaVSukmMta5qpMU7vqLt2Lnni4f/g==", "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" + "engines": { + "node": ">=0.10.0" } }, - "string.prototype.trimend": { - "version": "1.0.4", - "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - } + "node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==", + "dev": true }, - "string.prototype.trimstart": { - "version": "1.0.4", - "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" } }, - "string_decoder": { - "version": "1.1.1", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, - "requires": { - "safe-buffer": "~5.1.0" + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" } }, - "strip-ansi": { - "version": "3.0.1", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", "dev": true, - "requires": { - "ansi-regex": "^2.0.0" + "engines": { + "node": ">=8" } }, - "strip-bom": { - "version": "2.0.0", - "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, - "requires": { - "is-utf8": "^0.2.0" + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "strip-bom-buf": { - "version": "1.0.0", - "integrity": "sha1-HLRar1dTD0yvhsf3UXnSyaUd1XI=", + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, - "requires": { - "is-utf8": "^0.2.1" + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "strip-bom-stream": { - "version": "2.0.0", - "integrity": "sha1-+H217yYT9paKpUWr/h7HKLaoKco=", + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "dev": true, - "requires": { - "first-chunk-stream": "^2.0.0", - "strip-bom": "^2.0.0" + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "strip-final-newline": { - "version": "2.0.0", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true - }, - "strip-json-comments": { - "version": "2.0.1", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, - "supports-color": { - "version": "3.2.3", - "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", "dev": true, - "requires": { - "has-flag": "^1.0.0" + "engines": { + "node": ">=6" } }, - "sver-compat": { - "version": "1.5.0", - "integrity": "sha1-PPh9/rTQe0o/FIJ7wYaz/QxkXNg=", + "node_modules/terser": { + "version": "5.20.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.20.0.tgz", + "integrity": "sha512-e56ETryaQDyebBwJIWYB2TT6f2EZ0fL0sW/JRXNMN26zZdKi2u/E/5my5lG6jNxym6qsrVXfFRmOdV42zlAgLQ==", "dev": true, - "requires": { - "es6-iterator": "^2.0.1", - "es6-symbol": "^3.1.1" + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" } }, - "symbol-tree": { - "version": "3.2.4", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", - "dev": true - }, - "textextensions": { - "version": "3.3.0", - "integrity": "sha512-mk82dS8eRABNbeVJrEiN5/UMSCliINAuz8mkUwH4SwslkNP//gbEzlWNS5au0z5Dpx40SQxzqZevZkn+WYJ9Dw==", - "dev": true - }, - "through2": { - "version": "2.0.5", - "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "node_modules/terser-webpack-plugin": { + "version": "5.3.9", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.9.tgz", + "integrity": "sha512-ZuXsqE07EcggTWQjXUj+Aot/OMcD0bMKGgF63f7UxYcu5/AJF53aIpK1YoP5xR9l6s/Hy2b+t1AM0bLNPRuhwA==", "dev": true, - "requires": { - "readable-stream": "~2.3.6", - "xtend": "~4.0.1" + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.17", + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.1", + "terser": "^5.16.8" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } } }, - "through2-filter": { - "version": "3.0.0", - "integrity": "sha512-jaRjI2WxN3W1V8/FMZ9HKIBXixtiqs3SQSX4/YGIiP3gL6djW48VoZq9tDqeCWs3MT8YY5wb/zli8VW8snY1CA==", + "node_modules/terser-webpack-plugin/node_modules/schema-utils": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", + "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", "dev": true, - "requires": { - "through2": "~2.0.0", - "xtend": "~4.0.0" + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" } }, - "time-stamp": { - "version": "1.1.0", - "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", - "dev": true - }, - "to-absolute-glob": { - "version": "2.0.2", - "integrity": "sha1-GGX0PZ50sIItufFFt4z/fQ98hJs=", + "node_modules/terser-webpack-plugin/node_modules/serialize-javascript": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.1.tgz", + "integrity": "sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==", "dev": true, - "requires": { - "is-absolute": "^1.0.0", - "is-negated-glob": "^1.0.0" + "dependencies": { + "randombytes": "^2.1.0" } }, - "to-object-path": { - "version": "0.3.0", - "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, "dependencies": { - "kind-of": { - "version": "3.2.2", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" } }, - "to-regex": { - "version": "3.0.2", - "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", "dev": true, - "requires": { - "define-property": "^2.0.2", - "extend-shallow": "^3.0.2", - "regex-not": "^1.0.2", - "safe-regex": "^1.1.0" - } + "peer": true }, - "to-regex-range": { - "version": "2.1.1", - "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", "dev": true, - "requires": { - "is-number": "^3.0.0", - "repeat-string": "^1.6.1" + "engines": { + "node": ">=4" } }, - "to-through": { - "version": "2.0.0", - "integrity": "sha1-/JKtq6ByZHvAtn1rA2ZKoZUJOvY=", + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, - "requires": { - "through2": "^2.0.3" + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" } }, - "tough-cookie": { + "node_modules/tough-cookie": { "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", "dev": true, - "requires": { + "dependencies": { "psl": "^1.1.28", "punycode": "^2.1.1" + }, + "engines": { + "node": ">=0.8" } }, - "tr46": { + "node_modules/tr46": { "version": "1.0.1", - "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==", "dev": true, - "requires": { + "dependencies": { "punycode": "^2.1.0" } }, - "tunnel-agent": { + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "node_modules/tsutils": { + "version": "3.21.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", + "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", + "dev": true, + "dependencies": { + "tslib": "^1.8.1" + }, + "engines": { + "node": ">= 6" + }, + "peerDependencies": { + "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" + } + }, + "node_modules/tunnel-agent": { "version": "0.6.0", - "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", "dev": true, - "requires": { + "dependencies": { "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" } }, - "tweetnacl": { + "node_modules/tweetnacl": { "version": "0.14.5", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", - "dev": true - }, - "type": { - "version": "1.2.0", - "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", "dev": true }, - "type-check": { - "version": "0.3.2", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, - "requires": { - "prelude-ls": "~1.1.2" + "peer": true, + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" } }, - "type-detect": { + "node_modules/type-detect": { "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true - }, - "typedarray": { - "version": "0.0.6", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "typescript": { - "version": "4.4.3", - "integrity": "sha512-4xfscpisVgqqDfPaJo5vkd+Qd/ItkoagnHpufr+i2QCHBsNYp+G7UAoyFl8aPtx879u38wPV65rZ8qbGZijalA==", - "dev": true + "node_modules/type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true, + "engines": { + "node": ">=8" + } }, - "uglify-js": { - "version": "3.14.2", - "integrity": "sha512-rtPMlmcO4agTUfz10CbgJ1k6UAoXM2gWb3GoMPPZB/+/Ackf8lNWk11K4rYi2D0apgoFRLtQOZhb+/iGNJq26A==", - "dev": true + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "dependencies": { + "is-typedarray": "^1.0.0" + } }, - "unbox-primitive": { - "version": "1.0.1", - "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "node_modules/typescript": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has-bigints": "^1.0.1", - "has-symbols": "^1.0.2", - "which-boxed-primitive": "^1.0.2" + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" } }, - "unc-path-regex": { - "version": "0.1.2", - "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", - "dev": true + "node_modules/unicode-canonical-property-names-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz", + "integrity": "sha512-yY5PpDlfVIU5+y/BSCxAJRBIS1Zc2dDG3Ujq+sR0U+JjUevW2JhocOF+soROYDSaAezOzOKuyyixhD6mBknSmQ==", + "dev": true, + "engines": { + "node": ">=4" + } }, - "undertaker": { - "version": "1.3.0", - "integrity": "sha512-/RXwi5m/Mu3H6IHQGww3GNt1PNXlbeCuclF2QYR14L/2CHPz3DFZkvB5hZ0N/QUkiXWCACML2jXViIQEQc2MLg==", - "dev": true, - "requires": { - "arr-flatten": "^1.0.1", - "arr-map": "^2.0.0", - "bach": "^1.0.0", - "collection-map": "^1.0.0", - "es6-weak-map": "^2.0.1", - "fast-levenshtein": "^1.0.0", - "last-run": "^1.1.0", - "object.defaults": "^1.0.0", - "object.reduce": "^1.0.0", - "undertaker-registry": "^1.0.0" - } - }, - "undertaker-registry": { - "version": "1.0.1", - "integrity": "sha1-XkvaMI5KiirlhPm5pDWaSZglzFA=", - "dev": true + "node_modules/unicode-match-property-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz", + "integrity": "sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==", + "dev": true, + "dependencies": { + "unicode-canonical-property-names-ecmascript": "^2.0.0", + "unicode-property-aliases-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } }, - "union-value": { - "version": "1.0.1", - "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", + "node_modules/unicode-match-property-value-ecmascript": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.1.0.tgz", + "integrity": "sha512-qxkjQt6qjg/mYscYMC0XKRn3Rh0wFPlfxB0xkt9CfyTvpX1Ra0+rAmdX2QyAobptSEvuy4RtpPRui6XkV+8wjA==", "dev": true, - "requires": { - "arr-union": "^3.1.0", - "get-value": "^2.0.6", - "is-extendable": "^0.1.1", - "set-value": "^2.0.1" + "engines": { + "node": ">=4" } }, - "unique-stream": { - "version": "2.3.1", - "integrity": "sha512-2nY4TnBE70yoxHkDli7DMazpWiP7xMdCYqU2nBRO0UB+ZpEkGsSija7MvmvnZFUeC+mrgiUfcHSr3LmRFIg4+A==", + "node_modules/unicode-property-aliases-ecmascript": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.1.0.tgz", + "integrity": "sha512-6t3foTQI9qne+OZoVQB/8x8rk2k1eVy1gRXhV3oFQ5T6R1dqQ1xtin3XqSlx3+ATBkliTaR/hHyJBm+LVPNM8w==", "dev": true, - "requires": { - "json-stable-stringify-without-jsonify": "^1.0.1", - "through2-filter": "^3.0.0" + "engines": { + "node": ">=4" } }, - "unset-value": { - "version": "1.0.0", - "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", - "dev": true, - "requires": { - "has-value": "^0.3.1", - "isobject": "^3.0.0" - }, - "dependencies": { - "has-value": { - "version": "0.3.1", - "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", - "dev": true, - "requires": { - "get-value": "^2.0.3", - "has-values": "^0.1.4", - "isobject": "^2.0.0" - }, - "dependencies": { - "isobject": { - "version": "2.1.0", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "dev": true, - "requires": { - "isarray": "1.0.0" - } - } - } + "node_modules/update-browserslist-db": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", + "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" }, - "has-values": { - "version": "0.1.4", - "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", - "dev": true + { + "type": "github", + "url": "https://github.com/sponsors/ai" } + ], + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" } }, - "upath": { - "version": "1.2.0", - "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==", - "dev": true - }, - "uri-js": { + "node_modules/uri-js": { "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, - "requires": { + "dependencies": { "punycode": "^2.1.0" } }, - "urix": { - "version": "0.1.0", - "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", - "dev": true + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "bin": { + "uuid": "dist/bin/uuid" + } }, - "use": { - "version": "3.1.1", - "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", - "dev": true + "node_modules/verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "dev": true, + "engines": [ + "node >=0.6.0" + ], + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } }, - "util-deprecate": { + "node_modules/verror/node_modules/core-util-is": { "version": "1.0.2", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "dev": true - }, - "uuid": { - "version": "3.4.0", - "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==", "dev": true }, - "v8flags": { - "version": "3.2.0", - "integrity": "sha512-mH8etigqMfiGWdeXpaaqGfs6BndypxusHHcv2qSHyZkGEznCd/qAXCWWRzeowtL54147cktFOC4P5y+kl8d8Jg==", + "node_modules/w3c-hr-time": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", + "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", + "deprecated": "Use your platform's native performance.now() and performance.timeOrigin.", "dev": true, - "requires": { - "homedir-polyfill": "^1.0.1" + "dependencies": { + "browser-process-hrtime": "^1.0.0" } }, - "validate-npm-package-license": { - "version": "3.0.4", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "node_modules/watchpack": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz", + "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==", "dev": true, - "requires": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" } }, - "value-or-function": { - "version": "3.0.0", - "integrity": "sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM=", + "node_modules/webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", "dev": true }, - "verror": { - "version": "1.10.0", - "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "node_modules/webpack": { + "version": "5.88.2", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.88.2.tgz", + "integrity": "sha512-JmcgNZ1iKj+aiR0OvTYtWQqJwq37Pf683dY9bVORwVbUrDhLhdn/PlO2sHsFHPkj7sHNQF3JwaAkp49V+Sq1tQ==", "dev": true, - "requires": { - "assert-plus": "^1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "^1.2.0" - }, "dependencies": { - "core-util-is": { - "version": "1.0.2", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true + "@types/eslint-scope": "^3.7.3", + "@types/estree": "^1.0.0", + "@webassemblyjs/ast": "^1.11.5", + "@webassemblyjs/wasm-edit": "^1.11.5", + "@webassemblyjs/wasm-parser": "^1.11.5", + "acorn": "^8.7.1", + "acorn-import-assertions": "^1.9.0", + "browserslist": "^4.14.5", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.15.0", + "es-module-lexer": "^1.2.1", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.9", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.2.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.3.7", + "watchpack": "^2.4.0", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true } } }, - "vinyl": { - "version": "2.2.1", - "integrity": "sha512-LII3bXRFBZLlezoG5FfZVcXflZgWP/4dCwKtxd5ky9+LOtM4CS3bIRQsmR1KMnMW07jpE8fqR2lcxPZ+8sJIcw==", + "node_modules/webpack-cli": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.10.0.tgz", + "integrity": "sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w==", "dev": true, - "requires": { - "clone": "^2.1.1", - "clone-buffer": "^1.0.0", - "clone-stats": "^1.0.0", - "cloneable-readable": "^1.0.0", - "remove-trailing-separator": "^1.0.1", - "replace-ext": "^1.0.0" + "dependencies": { + "@discoveryjs/json-ext": "^0.5.0", + "@webpack-cli/configtest": "^1.2.0", + "@webpack-cli/info": "^1.5.0", + "@webpack-cli/serve": "^1.7.0", + "colorette": "^2.0.14", + "commander": "^7.0.0", + "cross-spawn": "^7.0.3", + "fastest-levenshtein": "^1.0.12", + "import-local": "^3.0.2", + "interpret": "^2.2.0", + "rechoir": "^0.7.0", + "webpack-merge": "^5.7.3" + }, + "bin": { + "webpack-cli": "bin/cli.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "4.x.x || 5.x.x" + }, + "peerDependenciesMeta": { + "@webpack-cli/generators": { + "optional": true + }, + "@webpack-cli/migrate": { + "optional": true + }, + "webpack-bundle-analyzer": { + "optional": true + }, + "webpack-dev-server": { + "optional": true + } } }, - "vinyl-file": { - "version": "3.0.0", - "integrity": "sha1-sQTZ5ECf+jJfqt1SBkLQo7SIs2U=", + "node_modules/webpack-cli/node_modules/commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "pify": "^2.3.0", - "strip-bom-buf": "^1.0.0", - "strip-bom-stream": "^2.0.0", - "vinyl": "^2.0.1" + "engines": { + "node": ">= 10" } }, - "vinyl-fs": { - "version": "3.0.3", - "integrity": "sha512-vIu34EkyNyJxmP0jscNzWBSygh7VWhqun6RmqVfXePrOwi9lhvRs//dOaGOTRUQr4tx7/zd26Tk5WeSVZitgng==", - "dev": true, - "requires": { - "fs-mkdirp-stream": "^1.0.0", - "glob-stream": "^6.1.0", - "graceful-fs": "^4.0.0", - "is-valid-glob": "^1.0.0", - "lazystream": "^1.0.0", - "lead": "^1.0.0", - "object.assign": "^4.0.4", - "pumpify": "^1.3.5", - "readable-stream": "^2.3.3", - "remove-bom-buffer": "^3.0.0", - "remove-bom-stream": "^1.2.0", - "resolve-options": "^1.1.0", - "through2": "^2.0.0", - "to-through": "^2.0.0", - "value-or-function": "^3.0.0", - "vinyl": "^2.0.0", - "vinyl-sourcemap": "^1.1.0" - } - }, - "vinyl-sourcemap": { - "version": "1.1.0", - "integrity": "sha1-kqgAWTo4cDqM2xHYswCtS+Y7PhY=", - "dev": true, - "requires": { - "append-buffer": "^1.0.2", - "convert-source-map": "^1.5.0", - "graceful-fs": "^4.1.6", - "normalize-path": "^2.1.1", - "now-and-later": "^2.0.0", - "remove-bom-buffer": "^3.0.0", - "vinyl": "^2.0.0" - }, - "dependencies": { - "normalize-path": { - "version": "2.1.1", - "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", - "dev": true, - "requires": { - "remove-trailing-separator": "^1.0.1" - } - } + "node_modules/webpack-merge": { + "version": "5.9.0", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.9.0.tgz", + "integrity": "sha512-6NbRQw4+Sy50vYNTw7EyOn41OZItPiXB8GNv3INSoe3PSFaHJEz3SHTrYVaRm2LilNGnFUzh0FAwqPEmU/CwDg==", + "dev": true, + "dependencies": { + "clone-deep": "^4.0.1", + "wildcard": "^2.0.0" + }, + "engines": { + "node": ">=10.0.0" } }, - "vinyl-sourcemaps-apply": { - "version": "0.2.1", - "integrity": "sha1-q2VJ1h0XLCsbh75cUI0jnI74dwU=", + "node_modules/webpack-plugin-replace": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/webpack-plugin-replace/-/webpack-plugin-replace-1.2.0.tgz", + "integrity": "sha512-1HA3etHpJW55qonJqv84o5w5GY7iqF8fqSHpTWdNwarj1llkkt4jT4QSvYs1hoaU8Lu5akDnq/spHHO5mXwo1w==", "dev": true, - "requires": { - "source-map": "^0.5.1" + "engines": { + "node": ">=4" } }, - "w3c-hr-time": { - "version": "1.0.2", - "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", + "node_modules/webpack-sources": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", + "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", "dev": true, - "requires": { - "browser-process-hrtime": "^1.0.0" + "engines": { + "node": ">=10.13.0" } }, - "webidl-conversions": { - "version": "4.0.2", - "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", - "dev": true + "node_modules/webpack/node_modules/schema-utils": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", + "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } }, - "whatwg-encoding": { + "node_modules/whatwg-encoding": { "version": "1.0.5", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", "dev": true, - "requires": { + "dependencies": { "iconv-lite": "0.4.24" } }, - "whatwg-mimetype": { + "node_modules/whatwg-mimetype": { "version": "2.3.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", "dev": true }, - "whatwg-url": { + "node_modules/whatwg-url": { "version": "6.5.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz", "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", "dev": true, - "requires": { + "dependencies": { "lodash.sortby": "^4.7.0", "tr46": "^1.0.1", "webidl-conversions": "^4.0.2" } }, - "which": { - "version": "1.3.1", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, - "requires": { + "dependencies": { "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" } }, - "which-boxed-primitive": { - "version": "1.0.2", - "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", - "dev": true, - "requires": { - "is-bigint": "^1.0.1", - "is-boolean-object": "^1.1.0", - "is-number-object": "^1.0.4", - "is-string": "^1.0.5", - "is-symbol": "^1.0.3" - } + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "dev": true }, - "which-module": { - "version": "1.0.0", - "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=", + "node_modules/wildcard": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz", + "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==", "dev": true }, - "wide-align": { - "version": "1.1.3", - "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", "dev": true, - "requires": { - "string-width": "^1.0.2 || 2" + "engines": { + "node": ">=0.10.0" } }, - "word-wrap": { - "version": "1.2.3", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "node_modules/workerpool": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.1.tgz", + "integrity": "sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==", "dev": true }, - "wordwrap": { - "version": "1.0.0", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", - "dev": true + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } }, - "wrap-ansi": { - "version": "2.1.0", - "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "requires": { - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1" + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" } }, - "wrappy": { + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/wrappy": { "version": "1.0.2", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true }, - "ws": { + "node_modules/write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dev": true, + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "node_modules/ws": { "version": "5.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.3.tgz", "integrity": "sha512-jZArVERrMsKUatIdnLzqvcfydI85dvd/Fp1u/VOpfdDWQ4c9qWXe+VIeAbQ5FrDwciAkr+lzofXLz3Kuf26AOA==", "dev": true, - "requires": { + "dependencies": { "async-limiter": "~1.0.0" } }, - "xml-name-validator": { + "node_modules/xml-name-validator": { "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", "dev": true }, - "xtend": { - "version": "4.0.2", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "dev": true + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "engines": { + "node": ">=10" + } }, - "y18n": { - "version": "3.2.2", - "integrity": "sha512-uGZHXkHnhF0XeeAPgnKfPv1bgKAYyVvmNL1xlKsPYZPaIHxGti2hHqvOCQv71XMsLxu1QjergkqogUnms5D3YQ==", + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", "dev": true }, - "yargs": { - "version": "7.1.2", - "integrity": "sha512-ZEjj/dQYQy0Zx0lgLMLR8QuaqTihnxirir7EwUHp1Axq4e3+k8jXU5K0VLbNvedv1f4EWtBonDIZm0NUr+jCcA==", - "dev": true, - "requires": { - "camelcase": "^3.0.0", - "cliui": "^3.2.0", - "decamelize": "^1.1.1", - "get-caller-file": "^1.0.1", - "os-locale": "^1.4.0", - "read-pkg-up": "^1.0.1", + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", - "require-main-filename": "^1.0.1", - "set-blocking": "^2.0.0", - "string-width": "^1.0.2", - "which-module": "^1.0.0", - "y18n": "^3.2.1", - "yargs-parser": "^5.0.1" + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" } }, - "yargs-parser": { - "version": "5.0.1", - "integrity": "sha512-wpav5XYiddjXxirPoCTUPbqM0PXvJ9hiBMvuJgInvo4/lAOTZzUprArw17q2O1P2+GHhbBr18/iQwjL5Z9BqfA==", + "node_modules/yargs-parser": { + "version": "20.2.4", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", + "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", "dev": true, - "requires": { - "camelcase": "^3.0.0", - "object.assign": "^4.1.0" + "engines": { + "node": ">=10" } }, - "yargs-unparser": { - "version": "1.6.0", - "integrity": "sha512-W9tKgmSn0DpSatfri0nx52Joq5hVXgeLiqR/5G0sZNDoLZFOr/xjBUDcShCOGNsBnEMNo1KAMBkTej1Hm62HTw==", + "node_modules/yargs-unparser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", + "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", "dev": true, - "requires": { - "flat": "^4.1.0", - "lodash": "^4.17.15", - "yargs": "^13.3.0" - }, "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "dev": true - }, - "camelcase": { - "version": "5.3.1", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, - "cliui": { - "version": "5.0.0", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", - "dev": true, - "requires": { - "string-width": "^3.1.0", - "strip-ansi": "^5.2.0", - "wrap-ansi": "^5.1.0" - } - }, - "find-up": { - "version": "3.0.0", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "get-caller-file": { - "version": "2.0.5", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "require-main-filename": { - "version": "2.0.0", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "dev": true - }, - "string-width": { - "version": "3.1.0", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", - "dev": true, - "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" - } - }, - "strip-ansi": { - "version": "5.2.0", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "requires": { - "ansi-regex": "^4.1.0" - } - }, - "which-module": { - "version": "2.0.0", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "dev": true - }, - "wrap-ansi": { - "version": "5.1.0", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" - } - }, - "y18n": { - "version": "4.0.3", - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", - "dev": true - }, - "yargs": { - "version": "13.3.2", - "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", - "dev": true, - "requires": { - "cliui": "^5.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^3.0.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^13.1.2" - } - }, - "yargs-parser": { - "version": "13.1.2", - "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - } + "camelcase": "^6.0.0", + "decamelize": "^4.0.0", + "flat": "^5.0.2", + "is-plain-obj": "^2.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-unparser/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yargs-unparser/node_modules/decamelize": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", + "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } } } diff --git a/package.json b/package.json index 2b873dde..9bec3e2d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "amazon-connect-streams", - "version": "1.7.5", + "version": "1.7.6", "description": "Amazon Connect Streams Library", "engines": { "node": ">=12.0.0" @@ -25,11 +25,10 @@ "connect" ], "scripts": { - "gulp-test": "gulp test", - "release": "tsc && gulp && gulp test", - "watch": "gulp watch", - "clean": "rm -rf build/ node_modules build package-lock.json", - "release-watch": "npm run release && npm run watch" + "release": "npm run build-streams && npm run test-mocha", + "build-streams": "webpack --config ./webpack/connect-streams.config.js && webpack --config ./webpack/connect-streams-min.config.js", + "test-mocha": "nyc mocha \"test/unit/**/*.spec.js\" --exit", + "clean": "rm -rf build/ node_modules build package-lock.json" }, "author": "Amazon Web Services", "license": "Apache-2.0", @@ -38,22 +37,24 @@ }, "homepage": "https://github.com/aws/amazon-connect-streams#readme", "devDependencies": { - "chai": "^4.1.2", - "gulp": "^4.0.2", - "gulp-cli": "^2.0.1", - "gulp-concat": "^2.6.1", - "gulp-istanbul": "^1.1.3", - "gulp-jshint": "^2.1.0", - "gulp-mocha": "^7.0.2", - "gulp-rename": "^1.2.2", - "gulp-replace": "^1.0.0", - "gulp-rev": "^8.1.1", - "gulp-uglify": "^3.0.0", - "gulp-watch": "^5.0.1", - "jshint": "^2.9.7", + "@babel/preset-env": "^7.21.4", + "@babel/preset-typescript": "^7.21.4", + "@typescript-eslint/eslint-plugin": "^5.59.1", + "@typescript-eslint/parser": "^5.59.1", + "babel": "^6.23.0", + "babel-loader": "^9.1.2", + "chai": "^4.3.7", + "jshint": "^2.13.6", + "mocha": "^10.2.0", "mocha-jsdom": "^2.0.0", + "nyc": "^15.1.0", + "prettier": "^2.8.8", "pump": "^3.0.0", - "sinon": "^9.0.0", - "typescript": "^4.2.4" + "sinon": "^12.0.0", + "terser-webpack-plugin": "^5.3.7", + "typescript": "^5.0.4", + "webpack": "^5.8.0", + "webpack-cli": "^4.9.1", + "webpack-plugin-replace": "^1.2.0" } } diff --git a/release/connect-streams-min.js b/release/connect-streams-min.js index f2593af3..c1c745fc 100644 --- a/release/connect-streams-min.js +++ b/release/connect-streams-min.js @@ -1 +1 @@ -!function o(r,i,s){function c(t,e){if(!i[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(a)return a(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=i[t]={exports:{}},r[t][0].call(n.exports,function(e){return c(r[t][1][e]||e)},n,n.exports,o,r,i,s)}return i[t].exports}for(var a="function"==typeof require&&require,e=0;ee.BLOCK_SIZE&&((t=new e).update(n),n=t.digest());e=new Uint8Array(e.BLOCK_SIZE);return e.set(n),e}(e,t),o=new Uint8Array(e.BLOCK_SIZE);o.set(n);for(var r=0;r>>32-r)+n&4294967295}function a(e,t,n,o,r,i,s){return c(t&n|~t&o,e,t,r,i,s)}function u(e,t,n,o,r,i,s){return c(t&o|n&~o,e,t,r,i,s)}function l(e,t,n,o,r,i,s){return c(t^n^o,e,t,r,i,s)}function p(e,t,n,o,r,i,s){return c(n^(t|~o),e,t,r,i,s)}(t.exports=o).BLOCK_SIZE=64,o.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;0>>0,!0),t.setUint32(60,Math.floor(o/4294967296),!0),this.hashBuffer(),this.finished=!0}for(var i=new DataView(new ArrayBuffer(16)),r=0;r<4;r++)i.setUint32(4*r,this.state[r],!0);o=new s(i.buffer,i.byteOffset,i.byteLength);return e?o.toString(e):o},o.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=a(n=t[0],i=t[1],r=t[2],o=t[3],e.getUint32(0,!0),7,3614090360),o=a(o,n,i,r,e.getUint32(4,!0),12,3905402710),r=a(r,o,n,i,e.getUint32(8,!0),17,606105819),i=a(i,r,o,n,e.getUint32(12,!0),22,3250441966);n=a(n,i,r,o,e.getUint32(16,!0),7,4118548399),o=a(o,n,i,r,e.getUint32(20,!0),12,1200080426),r=a(r,o,n,i,e.getUint32(24,!0),17,2821735955),i=a(i,r,o,n,e.getUint32(28,!0),22,4249261313),n=a(n,i,r,o,e.getUint32(32,!0),7,1770035416),o=a(o,n,i,r,e.getUint32(36,!0),12,2336552879),r=a(r,o,n,i,e.getUint32(40,!0),17,4294925233),i=a(i,r,o,n,e.getUint32(44,!0),22,2304563134),n=a(n,i,r,o,e.getUint32(48,!0),7,1804603682),o=a(o,n,i,r,e.getUint32(52,!0),12,4254626195),r=a(r,o,n,i,e.getUint32(56,!0),17,2792965006),n=u(n,i=a(i,r,o,n,e.getUint32(60,!0),22,1236535329),r,o,e.getUint32(4,!0),5,4129170786),o=u(o,n,i,r,e.getUint32(24,!0),9,3225465664),r=u(r,o,n,i,e.getUint32(44,!0),14,643717713),i=u(i,r,o,n,e.getUint32(0,!0),20,3921069994),n=u(n,i,r,o,e.getUint32(20,!0),5,3593408605),o=u(o,n,i,r,e.getUint32(40,!0),9,38016083),r=u(r,o,n,i,e.getUint32(60,!0),14,3634488961),i=u(i,r,o,n,e.getUint32(16,!0),20,3889429448),n=u(n,i,r,o,e.getUint32(36,!0),5,568446438),o=u(o,n,i,r,e.getUint32(56,!0),9,3275163606),r=u(r,o,n,i,e.getUint32(12,!0),14,4107603335),i=u(i,r,o,n,e.getUint32(32,!0),20,1163531501),n=u(n,i,r,o,e.getUint32(52,!0),5,2850285829),o=u(o,n,i,r,e.getUint32(8,!0),9,4243563512),r=u(r,o,n,i,e.getUint32(28,!0),14,1735328473),n=l(n,i=u(i,r,o,n,e.getUint32(48,!0),20,2368359562),r,o,e.getUint32(20,!0),4,4294588738),o=l(o,n,i,r,e.getUint32(32,!0),11,2272392833),r=l(r,o,n,i,e.getUint32(44,!0),16,1839030562),i=l(i,r,o,n,e.getUint32(56,!0),23,4259657740),n=l(n,i,r,o,e.getUint32(4,!0),4,2763975236),o=l(o,n,i,r,e.getUint32(16,!0),11,1272893353),r=l(r,o,n,i,e.getUint32(28,!0),16,4139469664),i=l(i,r,o,n,e.getUint32(40,!0),23,3200236656),n=l(n,i,r,o,e.getUint32(52,!0),4,681279174),o=l(o,n,i,r,e.getUint32(0,!0),11,3936430074),r=l(r,o,n,i,e.getUint32(12,!0),16,3572445317),i=l(i,r,o,n,e.getUint32(24,!0),23,76029189),n=l(n,i,r,o,e.getUint32(36,!0),4,3654602809),o=l(o,n,i,r,e.getUint32(48,!0),11,3873151461),r=l(r,o,n,i,e.getUint32(60,!0),16,530742520),n=p(n,i=l(i,r,o,n,e.getUint32(8,!0),23,3299628645),r,o,e.getUint32(0,!0),6,4096336452),o=p(o,n,i,r,e.getUint32(28,!0),10,1126891415),r=p(r,o,n,i,e.getUint32(56,!0),15,2878612391),i=p(i,r,o,n,e.getUint32(20,!0),21,4237533241),n=p(n,i,r,o,e.getUint32(48,!0),6,1700485571),o=p(o,n,i,r,e.getUint32(12,!0),10,2399980690),r=p(r,o,n,i,e.getUint32(40,!0),15,4293915773),i=p(i,r,o,n,e.getUint32(4,!0),21,2240044497),n=p(n,i,r,o,e.getUint32(32,!0),6,1873313359),o=p(o,n,i,r,e.getUint32(60,!0),10,4264355552),r=p(r,o,n,i,e.getUint32(24,!0),15,2734768916),i=p(i,r,o,n,e.getUint32(52,!0),21,1309151649),n=p(n,i,r,o,e.getUint32(16,!0),6,4149444226),o=p(o,n,i,r,e.getUint32(44,!0),10,3174756917),r=p(r,o,n,i,e.getUint32(8,!0),15,718787259),i=p(i,r,o,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=i+t[1]&4294967295,t[2]=r+t[2]&4294967295,t[3]=o+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":81}],14:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils");new Uint32Array([1518500249,1859775393,-1894007588,-899497514]),Math.pow(2,53);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}(t.exports=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;n>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}for(var n,o=this.h0,r=this.h1,i=this.h2,s=this.h3,c=this.h4,e=0;e<80;e++)var a=e<20?(n=s^r&(i^s),1518500249):e<40?(n=r^i^s,1859775393):e<60?(n=r&i|s&(r|i),2400959708):(n=r^i^s,3395469782),a=(o<<5|o>>>27)+n+c+a+(0|this.block[e]),c=s,s=i,i=r<<30|r>>>2,r=o,o=a;for(this.h0=this.h0+o|0,this.h1=this.h1+r|0,this.h2=this.h2+i|0,this.h3=this.h3+s|0,this.h4=this.h4+c|0,e=this.offset=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":81}],15:[function(e,t,n){var s=e("buffer/").Buffer,o=e("./browserHashUtils"),d=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]),r=Math.pow(2,53)-1;function i(){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=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=0,n=(e=o.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>r)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;0>>24&255,i[4*r+1]=this.state[r]>>>16&255,i[4*r+2]=this.state[r]>>>8&255,i[4*r+3]=this.state[r]>>>0&255;return e?i.toString(e):i},i.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],o=t[1],r=t[2],i=t[3],s=t[4],c=t[5],a=t[6],u=t[7],l=0;l<64;l++){l<16?this.temp[l]=(255&e[4*l])<<24|(255&e[4*l+1])<<16|(255&e[4*l+2])<<8|255&e[4*l+3]:(p=((h=this.temp[l-2])>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,h=this.temp[l-15],this.temp[l]=(p+this.temp[l-7]|0)+(((h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3)+this.temp[l-16]|0));var p=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&c^~s&a)|0)+(u+(d[l]+this.temp[l]|0)|0)|0,h=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&r^o&r)|0,u=a,a=c,c=s,s=i+p|0,i=r,r=o,o=n,n=p+h|0}t[0]+=n,t[1]+=o,t[2]+=r,t[3]+=i,t[4]+=s,t[5]+=c,t[6]+=a,t[7]+=u}},{"./browserHashUtils":11,"buffer/":81}],16:[function(n,o,e){!function(e){!function(){var e=n("./util");e.crypto.lib=n("./browserCryptoLib"),e.Buffer=n("buffer/").Buffer,e.url=n("url/"),e.querystring=n("querystring/"),e.realClock=n("./realclock/browserClock"),e.environment="js",e.createEventStream=n("./event-stream/buffered-create-event-stream").createEventStream,e.isBrowser=function(){return!0},e.isNode=function(){return!1};var t,e=n("./core");o.exports=e,n("./credentials"),n("./credentials/credential_provider_chain"),n("./credentials/temporary_credentials"),n("./credentials/chainable_temporary_credentials"),n("./credentials/web_identity_credentials"),n("./credentials/cognito_identity_credentials"),n("./credentials/saml_credentials"),e.XML.Parser=n("./xml/browser_parser"),n("./http/xhr"),void 0===t&&(t={browser:!0})}.call(this)}.call(this,n("_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 o,i=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),i.Config=i.util.inherit({constructor:function(n){void 0===n&&(n={}),n=this.extractCredentials(n),i.util.each.call(this,this.keys,function(e,t){this.set(e,n[e],t)})},getCredentials:function(t){var e,n=this;function o(e){t(e,e?null:n.credentials)}function r(e,t){return new i.util.error(t||new Error,{code:"CredentialsError",message:e,name:"CredentialsError"})}n.credentials?"function"==typeof n.credentials.get?n.credentials.get(function(e){o(e=e&&r("Could not load credentials from "+n.credentials.constructor.name,e))}):(e=null,o(e=!n.credentials.accessKeyId||!n.credentials.secretAccessKey?r("Missing credentials"):e)):n.credentialProvider?n.credentialProvider.resolve(function(e,t){e=e&&r("Could not load credentials from any providers",e),n.credentials=t,o(e)}):o(r("No credentials to load"))},update:function(e,n){n=n||!1,e=this.extractCredentials(e),i.util.each.call(this,e,function(e,t){(n||Object.prototype.hasOwnProperty.call(this.keys,e)||i.Service.hasService(e))&&this.set(e,t)})},loadFromPath:function(e){this.clear();var n=JSON.parse(i.util.readFileSync(e)),t=new i.FileSystemCredentials(e),e=new i.CredentialProviderChain;return e.providers.unshift(t),e.resolve(function(e,t){if(e)throw e;n.credentials=t}),this.constructor(n),this},clear:function(){i.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]=i.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=i.util.copy(e)).credentials=new i.Credentials(e)),e},setPromisesDependency:function(e){null===(o=e)&&"function"==typeof Promise&&(o=Promise);e=[i.Request,i.Credentials,i.CredentialProviderChain];i.S3&&(e.push(i.S3),i.S3.ManagedUpload&&e.push(i.S3.ManagedUpload)),i.util.addPromises(e,o)},getPromisesDependency:function(){return o}}),i.config=new i.Config},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(e,t,n){var o={util:e("./util")};({}).toString(),(t.exports=o).util.update(o,{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"),o.events=new o.SequentialExecutor,o.util.memoizedProperty(o,"endpointCache",function(){return new o.EndpointCache(o.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(){var e;r.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"==typeof arguments[0]?(e=arguments[0].credentials||arguments[0],this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken):(this.accessKeyId=arguments[0],this.secretAccessKey=arguments[1],this.sessionToken=arguments[2])},expiryWindow:15,needsRefresh:function(){var e=r.util.date.getDate().getTime(),e=new Date(e+1e3*this.expiryWindow);return!!(this.expireTime&&e>this.expireTime)||(this.expired||!this.accessKeyId||!this.secretAccessKey)},get:function(t){var n=this;this.needsRefresh()?this.refresh(function(e){e||(n.expired=!1),t&&t(e)}):t&&t()},refresh:function(e){this.expired=!1,e()},coalesceRefresh:function(e,n){var o=this;1===o.refreshCallbacks.push(e)&&o.load(function(t){r.util.arrayEach(o.refreshCallbacks,function(e){n?e(t):r.util.defer(function(){e(t)})}),o.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 i=e("../core"),o=e("../../clients/sts");i.ChainableTemporaryCredentials=i.util.inherit(i.Credentials,{constructor:function(e){i.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=i.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new i.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}e=i.util.merge({params:t,credentials:e.masterCredentials||i.config.credentials},e.stsConfig||{});this.service=new o(e)},refresh:function(e){this.coalesceRefresh(e||i.util.fn.callback)},load:function(o){var r=this,i=r.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode(function(e,t){var n={};e?o(e):(t&&(n.TokenCode=t),r.service[i](n,function(e,t){e||r.service.credentialsFrom(t,r),o(e)}))})},getTokenCode:function(o){var r=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,function(e,t){if(e){var n=e;return e instanceof Error&&(n=e.message),void o(i.util.error(new Error("Error fetching MFA token: "+n),{code:r.errorCode}))}o(null,t)}):o(null)}})},{"../../clients/sts":8,"../core":18}],21:[function(e,t,n){var o=e("../core"),r=e("../../clients/cognitoidentity"),i=e("../../clients/sts");o.CognitoIdentityCredentials=o.util.inherit(o.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){o.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=o.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||o.util.fn.callback)},load:function(t){var n=this;n.createClients(),n.data=null,n._identityId=null,n.getId(function(e){e?(n.clearIdOnNotAuthorized(e),t(e)):n.params.RoleArn?n.getCredentialsFromSTS(t):n.getCredentialsForIdentity(t)})},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(n){var o=this;if("string"==typeof o.params.IdentityId)return n(null,o.params.IdentityId);o.cognito.getId(function(e,t){!e&&t.IdentityId?(o.params.IdentityId=t.IdentityId,n(null,t.IdentityId)):n(e)})},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(n){var o=this;o.cognito.getCredentialsForIdentity(function(e,t){e?o.clearIdOnNotAuthorized(e):(o.cacheId(t),o.data=t,o.loadCredentials(o.data,o)),n(e)})},getCredentialsFromSTS:function(n){var o=this;o.cognito.getOpenIdToken(function(e,t){e?(o.clearIdOnNotAuthorized(e),n(e)):(o.cacheId(t),o.params.WebIdentityToken=t.Token,o.webIdentityCredentials.refresh(function(e){e||(o.data=o.webIdentityCredentials.data,o.sts.credentialsFrom(o.data,o)),n(e)}))})},loadCachedId:function(){var e,t,n=this;o.util.isBrowser()&&!n.params.IdentityId&&((e=n.getStorage("id"))&&n.params.Logins?(t=Object.keys(n.params.Logins),0!==(n.getStorage("providers")||"").split(",").filter(function(e){return-1!==t.indexOf(e)}).length&&(n.params.IdentityId=e)):e&&(n.params.IdentityId=e))},createClients:function(){var e,t=this._clientConfig;this.webIdentityCredentials=this.webIdentityCredentials||new o.WebIdentityCredentials(this.params,t),this.cognito||((e=o.util.merge({},t)).params=this.params,this.cognito=new r(e)),this.sts=this.sts||new i(t)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,o.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=o.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 c=e("../core");c.CredentialProviderChain=c.util.inherit(c.Credentials,{constructor:function(e){this.providers=e||c.CredentialProviderChain.defaultProviders.slice(0),this.resolveCallbacks=[]},resolve:function(e){var r,i,s=this;return 0===s.providers.length?e(new Error("No providers")):1===s.resolveCallbacks.push(e)&&(r=0,i=s.providers.slice(0),function t(n,o){if(!n&&o||r===i.length)return c.util.arrayEach(s.resolveCallbacks,function(e){e(n,o)}),void(s.resolveCallbacks.length=0);var e=i[r++];(o="function"==typeof e?e.call():e).get?o.get(function(e){t(e,e?null:o)}):t(null,o)}()),s}}),c.CredentialProviderChain.defaultProviders=[],c.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=c.util.promisifyMethod("resolve",e)},c.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},c.util.addPromises(c.CredentialProviderChain)},{"../core":18}],23:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.SAMLCredentials=o.util.inherit(o.Credentials,{constructor:function(e){o.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(n){var o=this;o.createClients(),o.service.assumeRoleWithSAML(function(e,t){e||o.service.credentialsFrom(t,o),n(e)})},createClients:function(){this.service=this.service||new r({params:this.params})}})},{"../../clients/sts":8,"../core":18}],24:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.TemporaryCredentials=o.util.inherit(o.Credentials,{constructor:function(e,t){o.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||o.util.fn.callback)},load:function(n){var o=this;o.createClients(),o.masterCredentials.get(function(){o.service.config.credentials=o.masterCredentials,(o.params.RoleArn?o.service.assumeRole:o.service.getSessionToken).call(o.service,function(e,t){e||o.service.credentialsFrom(t,o),n(e)})})},loadMasterCredentials:function(e){for(this.masterCredentials=e||o.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new o.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new r({params:this.params})}})},{"../../clients/sts":8,"../core":18}],25:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.WebIdentityCredentials=o.util.inherit(o.Credentials,{constructor:function(e,t){o.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=o.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(n){var o=this;o.createClients(),o.service.assumeRoleWithWebIdentity(function(e,t){o.data=null,e||(o.data=t,o.service.credentialsFrom(t,o)),n(e)})},createClients:function(){var e;this.service||((e=o.util.merge({},this._clientConfig)).params=this.params,this.service=new r(e))}})},{"../../clients/sts":8,"../core":18}],26:[function(e,t,n){!function(a){!function(){var u=e("./core"),l=e("./util"),o=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function p(e){var t=e.service,n=t.api||{},e=(n.operations,{});return t.config.region&&(e.region=t.config.region),n.serviceId&&(e.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(e.accessKeyId=t.config.credentials.accessKeyId),e}function h(e,t){var n={};return function o(r,i,s){s&&null!=i&&"structure"===s.type&&s.required&&0=this.HEADERS_RECEIVED&&!u&&(s.statusCode=a.status,s.headers=r.parseHeaders(a.getAllResponseHeaders()),s.emit("headers",s.statusCode,s.headers,a.statusText),u=!0),this.readyState===this.DONE&&r.finishRequest(a,s)},!1),a.upload.addEventListener("progress",function(e){s.emit("sendProgress",e)}),a.addEventListener("progress",function(e){s.emit("receiveProgress",e)},!1),a.addEventListener("timeout",function(){o(l.util.error(new Error("Timeout"),{code:"TimeoutError"}))},!1),a.addEventListener("error",function(){o(l.util.error(new Error("Network Failure"),{code:"NetworkingError"}))},!1),a.addEventListener("abort",function(){o(l.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))},!1),n(s),a.open(t.method,c,!1!==e.xhrAsync),l.util.each(t.headers,function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&a.setRequestHeader(e,t)}),e.timeout&&!1!==e.xhrAsync&&(a.timeout=e.timeout),e.xhrWithCredentials&&(a.withCredentials=!0);try{a.responseType="arraybuffer"}catch(e){}try{t.body?a.send(t.body):a.send()}catch(e){if(!t.body||"object"!=typeof t.body.buffer)throw e;a.send(t.body.buffer)}return s},parseHeaders:function(e){var n={};return l.util.arrayEach(e.split(/\r?\n/),function(e){var t=e.split(":",1)[0],e=e.substring(t.length+2);0= 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,o){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 "+o+" <= "+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 r=!1,i=0;i=e.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t]))})},setupRequestListeners:function(e){},getSignerClass:function(e){var t=null,n="";return e&&(n=(t=(e.service.api.operations||{})[e.operation]||null)?t.authtype:""),n=this.config.signatureVersion||("v4"===n||"v4-unsigned-body"===n?"v4":this.api.signatureVersion),l.Signers.RequestSigner.getVersion(n)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return l.EventListeners.Query;case"json":return l.EventListeners.Json;case"rest-json":return l.EventListeners.RestJson;case"rest-xml":return l.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 l.util.calculateRetryDelay(e,this.config.retryDelayOptions)},retryableError:function(e){return!!this.timeoutError(e)||(!!this.networkingError(e)||(!!this.expiredCredentialsError(e)||(!!this.throttledError(e)||500<=e.statusCode)))},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 3e4<=Math.abs(this.getSkewCorrectedDate().getTime()-e)},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;return e=(e=(e=e.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 l.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(n)return n;if(t){t=new Error;throw l.util.error(t,"No pagination configuration for "+e)}return null}}),l.util.update(l.Service,{defineMethods:function(e){l.util.each(e.prototype.api.operations,function(n){e.prototype[n]||("none"===e.prototype.api.operations[n].authtype?e.prototype[n]=function(e,t){return this.makeUnauthenticatedRequest(n,e,t)}:e.prototype[n]=function(e,t){return this.makeRequest(n,e,t)})})},defineService:function(e,t,n){l.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var o,n=s(l.Service,n||{});return"string"==typeof e?(l.Service.addVersions(n,t),o=n.serviceIdentifier||e,n.serviceIdentifier=o):(n.prototype.api=e,l.Service.defineMethods(n)),l.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&l.util.clientSideMonitoring&&(o=l.util.clientSideMonitoring.Publisher,e=(0,l.util.clientSideMonitoring.configProvider)(),this.prototype.publisher=new o(e),e.enabled&&(l.Service._clientSideMonitoring=!0)),l.SequentialExecutor.call(n.prototype),l.Service.addDefaultMonitoringListeners(n.prototype),n},addVersions:function(e,t){Array.isArray(t)||(t=[t]),e.services=e.services||{};for(var n=0;n=t.length)return n.push(null);e=o+e;e>t.length&&(e=t.length),n.push(t.slice(o,e)),o=e},n},concat:function(e){for(var t,n=0,o=0,r=0;r>>8^t[255&(n^e.readUInt8(o))];return(-1^n)>>>0},hmac:function(e,t,n,o){return"buffer"===(n=n||"binary")&&(n=void 0),o=o||"sha256","string"==typeof t&&(t=u.buffer.toBuffer(t)),u.crypto.lib.createHmac(o,e).update(t).digest(n)},md5:function(e,t,n){return u.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return u.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,o){var r=u.crypto.createHash(e);"buffer"===(n=n||"binary")&&(n=void 0),"string"==typeof t&&(t=u.buffer.toBuffer(t));var i=u.arraySliceFn(t),e=u.Buffer.isBuffer(t);if(u.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(e=!0),o&&"object"==typeof t&&"function"==typeof t.on&&!e)t.on("data",function(e){r.update(e)}),t.on("error",function(e){o(e)}),t.on("end",function(){o(null,r.digest(n))});else{if(!o||!i||e||"undefined"==typeof FileReader){u.isBrowser()&&"object"==typeof t&&!e&&(t=new u.Buffer(new Uint8Array(t)));e=r.update(t).digest(n);return o&&o(null,e),e}var s=0,c=new FileReader;c.onerror=function(){o(new Error("Failed to read data."))},c.onload=function(){var e=new u.Buffer(new Uint8Array(c.result));r.update(e),s+=e.length,c._continueReading()},c._continueReading=function(){var e;s>=t.size?o(null,r.digest(n)):((e=s+524288)>t.size&&(e=t.size),c.readAsArrayBuffer(i.call(t,s,e)))},c._continueReading()}},toHex:function(e){for(var t=[],n=0;n/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 c=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,r=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 o=e("./escape-element").escapeElement;function r(e){this.value=e}r.prototype.toString=function(){return o(""+this.value)},t.exports={XmlText:r}},{"./escape-element":75}],78:[function(e,t,n){"use strict";n.byteLength=function(e){var t=l(e),e=t[0],t=t[1];return 3*(e+t)/4-t},n.toByteArray=function(e){var t,n,o=l(e),r=o[0],o=o[1],i=new u(function(e,t){return 3*(e+t)/4-t}(r,o)),s=0,c=0>16&255,i[s++]=t>>8&255,i[s++]=255&t;2===o&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,i[s++]=255&t);1===o&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,i[s++]=t>>8&255,i[s++]=255&t);return i},n.fromByteArray=function(e){for(var t,n=e.length,o=n%3,r=[],i=0,s=n-o;i>18&63]+c[e>>12&63]+c[e>>6&63]+c[63&e]}(o));return r.join("")}(e,i,s>2]+c[t<<4&63]+"==")):2==o&&(t=(e[n-2]<<8)+e[n-1],r.push(c[t>>10]+c[t>>4&63]+c[t<<2&63]+"="));return r.join("")};for(var c=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,i=o.length;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},h=y-1,E=Math.floor,S=String.fromCharCode;function b(e){throw RangeError(p[e])}function d(e,t){for(var n=e.length,o=[];n--;)o[n]=t(e[n]);return o}function f(e,t){var n=e.split("@"),o="";return 1>>10&1023|55296),e=56320|1023&e),t+=S(e)}).join("")}function T(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function I(e,t,n){var o=0;for(e=n?E(e/c):e>>1,e+=E(e/t);h*v>>1E((m-l)/i))&&b("overflow"),l+=c*i,!(c<(c=s<=h?1:h+v<=s?v:s-h));s+=y)i>E(m/(c=y-c))&&b("overflow"),i*=c;h=I(l-r,t=a.length+1,0==r),E(l/t)>m-p&&b("overflow"),p+=E(l/t),l%=t,a.splice(l++,0,p)}return g(a)}function A(e){for(var t,n,o,r,i,s,c,a,u,l,p=[],h=(e=C(e)).length,d=128,f=72,g=t=0;gE((m-t)/(a=n+1))&&b("overflow"),t+=(r-d)*a,d=r,g=0;gm&&b("overflow"),c==d){for(i=t,s=y;!(i<(u=s<=f?1:f+v<=s?v:s-f));s+=y)p.push(S(T(u+(l=i-u)%(u=y-u),0))),i=E(l/u);p.push(S(T(i,0))),f=I(t,a,n==o),t=0,++n}++t,++d}return p.join("")}if(r={version:"1.3.2",ucs2:{decode:C,encode:g},decode:_,encode:A,toASCII:function(e){return f(e,function(e){return u.test(e)?"xn--"+A(e):e})},toUnicode:function(e){return f(e,function(e){return a.test(e)?_(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return r});else if(t&&n)if(R.exports==t)n.exports=r;else for(i in r)r.hasOwnProperty(i)&&(t[i]=r[i]);else e.punycode=r}(this)}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(L,e,D){!function(e,t){!function(){"use strict";var c=L("base64-js"),i=L("ieee754"),s=L("isarray");function n(){return p.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function r(e,t){if(n()=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|e}function d(e,t){if(p.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;var n=(e="string"!=typeof e?""+e:e).length;if(0===n)return 0;for(var o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return N(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return k(e).length;default:if(o)return N(e).length;t=(""+t).toLowerCase(),o=!0}}function t(e,t,n){var o,r,i,s=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((n=void 0===n||n>this.length?this.length:n)<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":return function(e,t,n){var o=e.length;(!t||t<0)&&(t=0);(!n||n<0||o=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=p.from(t,o)),p.isBuffer(t))return 0===t.length?-1:m(e,t,n,o,r);if("number"==typeof t)return t&=255,p.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?(r?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,n):m(e,[t],n,o,r);throw new TypeError("val must be string, number or Buffer")}function m(e,t,n,o,r){var i=1,s=e.length,c=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;s/=i=2,c/=2,n/=2}function a(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(r)for(var u=-1,l=n;l>8,o=o%256,r.push(o),r.push(n);return r}(t,e.length-n),e,n,o)}function E(e,t,n){n=Math.min(e.length,n);for(var o=[],r=t;r>>10&1023|55296),l=56320|1023&l),o.push(l),r+=p}return function(e){var t=e.length;if(t<=S)return String.fromCharCode.apply(String,e);var n="",o=0;for(;ot&&(e+=" ... ")),""},p.prototype.compare=function(e,t,n,o,r){if(!p.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===n&&(n=e?e.length:0),void 0===o&&(o=0),void 0===r&&(r=this.length),(t=void 0===t?0:t)<0||n>e.length||o<0||r>this.length)throw new RangeError("out of range index");if(r<=o&&n<=t)return 0;if(r<=o)return-1;if(n<=t)return 1;if(this===e)return 0;for(var i=(r>>>=0)-(o>>>=0),s=(n>>>=0)-(t>>>=0),c=Math.min(i,s),a=this.slice(o,r),u=e.slice(t,n),l=0;lthis.length)throw new RangeError("Attempt to write outside buffer bounds");o=o||"utf8";for(var i,s,c,a=!1;;)switch(o){case"hex":return function(e,t,n,o){n=Number(n)||0;var r=e.length-n;if((!o||r<(o=Number(o)))&&(o=r),(r=t.length)%2!=0)throw new TypeError("Invalid hex string");r/2e.length)throw new RangeError("Index out of range")}function T(e,t,n,o){t<0&&(t=65535+t+1);for(var r=0,i=Math.min(e.length-n,2);r>>8*(o?r:1-r)}function I(e,t,n,o){t<0&&(t=4294967295+t+1);for(var r=0,i=Math.min(e.length-n,4);r>>8*(o?r:3-r)&255}function _(e,t,n,o){if(n+o>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function A(e,t,n,o,r){return r||_(e,0,n,4),i.write(e,t,n,o,23,4),n+4}function w(e,t,n,o,r){return r||_(e,0,n,8),i.write(e,t,n,o,52,8),n+8}p.prototype.slice=function(e,t){var n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):n>>8):T(this,e,t,!0),t+2},p.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,65535,0),p.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},p.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,4294967295,0),p.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):I(this,e,t,!0),t+4},p.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,4294967295,0),p.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},p.prototype.writeIntLE=function(e,t,n,o){e=+e,t|=0,o||C(this,e,t,n,(o=Math.pow(2,8*n-1))-1,-o);var r=0,i=1,s=0;for(this[t]=255&e;++r>0)-s&255;return t+n},p.prototype.writeIntBE=function(e,t,n,o){e=+e,t|=0,o||C(this,e,t,n,(o=Math.pow(2,8*n-1))-1,-o);var r=n-1,i=1,s=0;for(this[t+r]=255&e;0<=--r&&(i*=256);)e<0&&0===s&&0!==this[t+r+1]&&(s=1),this[t+r]=(e/i>>0)-s&255;return t+n},p.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,1,127,-128),p.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&(e=e<0?255+e+1:e),t+1},p.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,32767,-32768),p.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},p.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,32767,-32768),p.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},p.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,2147483647,-2147483648),p.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):I(this,e,t,!0),t+4},p.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),p.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},p.prototype.writeFloatLE=function(e,t,n){return A(this,e,t,!0,n)},p.prototype.writeFloatBE=function(e,t,n){return A(this,e,t,!1,n)},p.prototype.writeDoubleLE=function(e,t,n){return w(this,e,t,!0,n)},p.prototype.writeDoubleBE=function(e,t,n){return w(this,e,t,!1,n)},p.prototype.copy=function(e,t,n,o){if(n=n||0,o||0===o||(o=this.length),t>=e.length&&(t=e.length),(o=0=this.length)throw new RangeError("sourceStart out of bounds");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length);var r,i=(o=e.length-t>>=0,n=void 0===n?this.length:n>>>0,"number"==typeof(e=e||0))for(c=t;c>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 k(e){return c.toByteArray(function(e){var t;if((e=((t=e).trim?t.trim():t.replace(/^\s+|\s+$/g,"")).replace(R,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,n,o){for(var r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},L("buffer").Buffer)},{"base64-js":78,buffer:81,ieee754:83,isarray:84}],82:[function(e,t,n){function o(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function a(e){return"function"==typeof e}function u(e){return"object"==typeof e&&null!==e}function l(e){return void 0===e}((t.exports=o).EventEmitter=o).prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.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},o.prototype.emit=function(e){var t,n,o,r,i,s;if(this._events||(this._events={}),"error"===e&&(!this._events.error||u(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(l(n=this._events[e]))return!1;if(a(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:r=Array.prototype.slice.call(arguments,1),n.apply(this,r)}else if(u(n))for(r=Array.prototype.slice.call(arguments,1),o=(s=n.slice()).length,i=0;in&&(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},o.prototype.once=function(e,t){if(!a(t))throw TypeError("listener must be a function");var n=!1;function o(){this.removeListener(e,o),n||(n=!0,t.apply(this,arguments))}return o.listener=t,this.on(e,o),this},o.prototype.removeListener=function(e,t){var n,o,r,i;if(!a(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=(n=this._events[e]).length,o=-1,n===t||a(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(u(n)){for(i=r;0>1,l=-7,p=n?r-1:0,h=n?-1:1,n=e[t+p];for(p+=h,i=n&(1<<-l)-1,n>>=-l,l+=c;0>=-l,l+=o;0>1,p=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,h=o?0:i-1,d=o?1:-1,i=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(o=Math.pow(2,-s))<1&&(s--,o*=2),2<=(t+=1<=s+l?p/o:p*Math.pow(2,1-l))*o&&(s++,o/=2),u<=s+l?(c=0,s=u):1<=s+l?(c=(t*o-1)*Math.pow(2,r),s+=l):(c=t*Math.pow(2,l-1)*Math.pow(2,r),s=0));8<=r;e[n+h]=255&c,h+=d,c/=256,r-=8);for(s=s<":!0,"=":!0,"!":!0},P={" ":!0,"\t":!0,"\n":!0};function x(e){return"0"<=e&&e<="9"||"-"===e}function n(){}n.prototype={tokenize:function(e){var t,n,o,r=[];for(this._current=0;this._current"===n?"="===e[this._current]?(this._current++,{type:k,value:">=",start:t}):{type:"GT",value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:"EQ",value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t=this._current,n=e.length;"`"!==e[this._current]&&this._current",'"',"`"," ","\r","\n","\t"]),R=["'"].concat(n),N=["%","/","?",";","#"].concat(R),k=["/","?","#"],O=/^[a-z0-9A-Z_-]{0,63}$/,L=/^([a-z0-9A-Z_-]{0,63})(.*)$/,D={javascript:!0,"javascript:":!0},P={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},M=e("querystring");function r(e,t,n){if(e&&s(e)&&e instanceof h)return e;var o=new h;return o.parse(e,t,n),o}function U(e){return"string"==typeof e}function s(e){return"object"==typeof e&&null!==e}function d(e){return null===e}h.prototype.parse=function(e,t,n){if(!U(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o,r,i=(i=e).trim(),e=w.exec(i);if(e&&(o=(e=e[0]).toLowerCase(),this.protocol=o,i=i.substr(e.length)),(n||e||i.match(/^\/\/[^@\/]+@[^@\/]+/))&&(!(r="//"===i.substr(0,2))||e&&P[e]||(i=i.substr(2),this.slashes=!0)),!P[e]&&(r||e&&!x[e])){for(var s=-1,c=0;c>>((3&t)<<3)&255;return r})},{}],101:[function(e,t,n){var l,p,h=e("./lib/rng"),d=e("./lib/bytesToUuid"),f=0,g=0;t.exports=function(e,t,n){var o=t&&n||0,r=t||[],i=(e=e||{}).node||l,s=void 0!==e.clockseq?e.clockseq:p;null!=i&&null!=s||(a=h(),null==i&&(i=l=[1|a[0],a[1],a[2],a[3],a[4],a[5]]),null==s&&(s=p=16383&(a[6]<<8|a[7])));var c=void 0!==e.msecs?e.msecs:(new Date).getTime(),n=void 0!==e.nsecs?e.nsecs:g+1,a=c-f+(n-g)/1e4;if(a<0&&void 0===e.clockseq&&(s=s+1&16383),1e4<=(n=(a<0||f>>24&255,r[o++]=n>>>16&255,r[o++]=n>>>8&255,r[o++]=255&n,c=c/4294967296*1e4&268435455,r[o++]=c>>>8&255,r[o++]=255&c,r[o++]=c>>>24&15|16,r[o++]=c>>>16&255,r[o++]=s>>>8|128,r[o++]=255&s;for(var u=0;u<6;++u)r[o+u]=i[u];return t||d(r)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(e,t,n){var s=e("./lib/rng"),c=e("./lib/bytesToUuid");t.exports=function(e,t,n){var o=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var i=0;i<16;++i)t[o+i]=r[i];return t||c(r)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o=e("./utils/LRU"),e=(Object.defineProperty(i.prototype,"size",{get:function(){return this.cache.length},enumerable:!0,configurable:!0}),i.prototype.put=function(e,t){e="string"!=typeof e?i.getKeyString(e):e,t=this.populateValue(t);this.cache.put(e,t)},i.prototype.get=function(e){var t="string"!=typeof e?i.getKeyString(e):e,n=Date.now(),o=this.cache.get(t);if(o)for(var r=0;r>>=0;break;case"x":o=o.toString(16);break;case"X":o=o.toString(16).toUpperCase()}o=/[def]/.test(i[8])&&i[3]&&0<=o?"+"+o:o,s=i[4]?"0"==i[4]?"0":i[4].charAt(1):" ",c=i[6]-String(o).length,c=i[6]?function(e,t){for(var n=[];0=this._logLevel&&(s[e.level]>=this._echoLevel&&c[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.sendInternalLogEntryToServer=function(e){this._serverBoundInternalLogs.push(e),e.level in s&&s[e.level]>=this._logLevel&&(s[e.level]>=this._echoLevel&&c[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=o._logLevel}));n=new r.Blob([JSON.stringify(e,void 0,4)],["text/plain"]),e=document.createElement("a"),t=t||"agent-log";e.href=r.URL.createObjectURL(n),e.download=t+".txt",document.body.appendChild(e),e.click(),document.body.removeChild(e)},l.prototype.scheduleUpstreamLogPush=function(e){connect.upstreamLogPushScheduled||(connect.upstreamLogPushScheduled=!0,r.setInterval(connect.hitch(this,this.reportMasterLogsUpStream,e),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var t=this._logsToPush.slice();this._logsToPush=[],connect.ifMaster(connect.MasterTopics.SEND_LOGS,function(){0{try{n[t]=e[t]}catch(e){connect.getLog().info("deepcopyCrossOriginEvent failed on key: ",t).sendInternalLogToServer()}}),connect.deepcopy(n)},connect.getBaseUrl=function(){var e=a.location;return connect.sprintf("%s//%s:%s",e.protocol,e.hostname,e.port)},connect.getUrlWithProtocol=function(e){var t=a.location.protocol;return e.substr(0,t.length)!==t?connect.sprintf("%s//%s",t,e):e},connect.isFramed=function(){try{return window.self!==window.top}catch(e){return!0}},connect.hasOtherConnectedCCPs=function(){return 1o(e)).catch(()=>o({})):1!==n&&(e.status>=connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout(function(){t(--n)},s):r(e)}).catch(function(e){r(e)})}(t)})},connect.backoff=function(o,r,i,s){connect.assertTrue(connect.isFunction(o),"func must be a Function");var c=this;o({success:function(e){s&&s.success&&s.success(e)},failure:function(e,t){var n;0>",e)},d.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},d.prototype.trigger=function(t,n){connect.assertNotNull(t,"eventName");var o=this,e=this.subMap.getSubscriptions("<>"),r=this.subMap.getSubscriptions(t);this.logEvents&&t!==connect.EventType.LOG&&t!==connect.EventType.MASTER_RESPONSE&&t!==connect.EventType.API_METRIC&&t!==connect.EventType.SERVER_BOUND_INTERNAL_LOG&&connect.getLog().trace("Publishing event: %s",t).sendInternalLogToServer(),t.startsWith(connect.ContactEvents.ACCEPTED)&&n&&n.contactId&&!(n instanceof connect.Contact)&&(n=new connect.Contact(n.contactId)),e.concat(r).forEach(function(e){try{e.f(n||null,t,o)}catch(e){connect.getLog().error("'%s' event handler failed.",t).withException(e).sendInternalLogToServer()}})},d.prototype.bridge=function(){var n=this;return function(e,t){n.trigger(t,e)}},d.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach(function(e){e.unsubscribe()})},connect.EventBus=d,connect.EventFactory=e,connect.EventType=t,connect.AgentEvents=o,connect.ConfigurationEvents=u,connect.ConnectionEvents=a,connect.ConnnectionEvents=a,connect.ContactEvents=i,connect.ChannelViewEvents=s,connect.TaskEvents=c,connect.VoiceIdEvents=l,connect.WebSocketEvents=r,connect.MasterTopics=n}(),function(){connect=this.connect||{},this.connect=connect,this.lily=connect;var o=function(){};o.prototype.send=function(e){throw new connect.NotImplementedError},o.prototype.onMessage=function(e){throw new connect.NotImplementedError};var r=function(){o.call(this)};r.prototype=Object.create(o.prototype),(r.prototype.constructor=r).prototype.onMessage=function(e){},r.prototype.send=function(e){};function e(e,t){o.call(this),this.window=e,this.domain=t||"*"}((e.prototype=Object.create(o.prototype)).constructor=e).prototype.send=function(e){this.window.postMessage(e,this.domain)},e.prototype.onMessage=function(e){this.window.addEventListener("message",e)};var i=function(e,t,n){o.call(this),this.input=e,this.output=t,this.domain=n||"*"};i.prototype=Object.create(o.prototype),(i.prototype.constructor=i).prototype.send=function(e){this.output.postMessage(e,this.domain)},i.prototype.onMessage=function(t){this.input.addEventListener("message",e=>{e.source===this.output&&t(e)})};function t(e){o.call(this),this.port=e,this.id=connect.randomId()}((t.prototype=Object.create(o.prototype)).constructor=t).prototype.send=function(e){this.port.postMessage(e)},t.prototype.onMessage=function(e){this.port.addEventListener("message",e)},t.prototype.getId=function(){return this.id};function n(e){o.call(this),this.streamMap=e?connect.index(e,function(e){return e.getId()}):{},this.messageListeners=[]}((n.prototype=Object.create(o.prototype)).constructor=n).prototype.send=function(t){this.getStreams().forEach(function(e){try{e.send(t)}catch(e){}})},n.prototype.onMessage=function(t){this.messageListeners.push(t),this.getStreams().forEach(function(e){e.onMessage(t)})},n.prototype.addStream=function(t){this.streamMap[t.getId()]=t,this.messageListeners.forEach(function(e){t.onMessage(e)})},n.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},n.prototype.getStreams=function(e){return connect.values(this.streamMap)},n.prototype.getStreamForPort=function(t){return connect.find(this.getStreams(),function(e){return e.port===t})};var s=function(e,t,n){this.name=e,this.upstream=t||new r,this.downstream=n||new r,this.downstreamBus=new connect.EventBus,this.upstreamBus=new connect.EventBus,this.upstream.onMessage(connect.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(connect.hitch(this,this._dispatchEvent,this.downstreamBus))};s.prototype.onUpstream=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.upstreamBus.subscribe(e,t)},s.prototype.onAllUpstream=function(e){return connect.assertNotNull(e,"f"),connect.assertTrue(connect.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},s.prototype.onDownstream=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.downstreamBus.subscribe(e,t)},s.prototype.onAllDownstream=function(e){return connect.assertNotNull(e,"f"),connect.assertTrue(connect.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},s.prototype.sendUpstream=function(e,t){connect.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:t})},s.prototype.sendDownstream=function(e,t){connect.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:t})},s.prototype._dispatchEvent=function(e,t){t=t.data;t.event&&e.trigger(t.event,t.data)},s.prototype.passUpstream=function(){var n=this;return function(e,t){n.upstream.send({event:t,data:e})}},s.prototype.passDownstream=function(){var n=this;return function(e,t){n.downstream.send({event:t,data:e})}},s.prototype.shutdown=function(){this.upstreamBus.unsubscribeAll(),this.downstreamBus.unsubscribeAll()};function c(e,t,n,o){s.call(this,e,new i(t,n.contentWindow,o||"*"),null)}(c.prototype=Object.create(s.prototype)).constructor=c,connect.Stream=o,connect.NullStream=r,connect.WindowStream=e,connect.WindowIOStream=i,connect.PortStream=t,connect.StreamMultiplexer=n,connect.Conduit=s,connect.IFrameConduit=c}(),function(){connect=this.connect||{},this.connect=connect,this.lily=connect,connect.ClientMethods=connect.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"]),connect.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"},connect.MasterMethods=connect.makeEnum(["becomeMaster","checkMaster"]);var o=function(){};o.EMPTY_CALLBACKS={success:function(){},failure:function(){}},o.prototype.call=function(e,t,n){connect.assertNotNull(e,"method");n=n||o.EMPTY_CALLBACKS;this._callImpl(e,t||{},n)},o.prototype._callImpl=function(e,t,n){throw new connect.NotImplementedError};function e(){o.call(this)}((e.prototype=Object.create(o.prototype)).constructor=e).prototype._callImpl=function(e,t,n){n&&n.failure&&(e=connect.sprintf("No such method exists on NULL client: %s",e),n.failure(new connect.ValueError(e),{message:e}))};var t=function(e,t,n){o.call(this),this.conduit=e,this.requestEvent=t,this.responseEvent=n,this._requestIdCallbacksMap={},this.conduit.onUpstream(n,connect.hitch(this,this._handleResponse))};t.prototype=Object.create(o.prototype),(t.prototype.constructor=t).prototype._callImpl=function(e,t,n){t=connect.EventFactory.createRequest(this.requestEvent,e,t);this._requestIdCallbacksMap[t.requestId]=n,this.conduit.sendUpstream(t.event,t)},t.prototype._getCallbacksForRequest=function(e){var t=this._requestIdCallbacksMap[e]||null;return null!=t&&delete this._requestIdCallbacksMap[e],t},t.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))};function n(e){t.call(this,e,connect.EventType.API_REQUEST,connect.EventType.API_RESPONSE)}(n.prototype=Object.create(t.prototype)).constructor=n;function r(e){t.call(this,e,connect.EventType.MASTER_REQUEST,connect.EventType.MASTER_RESPONSE)}(r.prototype=Object.create(t.prototype)).constructor=r;function i(e,t,n){connect.assertNotNull(e,"authCookieName"),connect.assertNotNull(t,"authToken"),connect.assertNotNull(n,"endpoint"),o.call(this),this.endpointUrl=connect.getUrlWithProtocol(n),this.authToken=t,this.authCookieName=e}((i.prototype=Object.create(o.prototype)).constructor=i).prototype._callImpl=function(e,t,c){var n={};n[this.authCookieName]=this.authToken;n={method:"post",body:JSON.stringify(t||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(n)}};connect.fetch(this.endpointUrl,n).then(function(e){c.success(e)}).catch(function(o){const r=o.body.getReader();let i="";const s=new TextDecoder;r.read().then(function e({done:t,value:n}){if(t){t=JSON.parse(i);return t.status=o.status,void c.failure(t)}return i+=s.decode(n),r.read().then(e)})})};function s(e,t,n){connect.assertNotNull(e,"authToken"),connect.assertNotNull(t,"region"),o.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=t,this.authToken=e,e=connect.getBaseUrl(),e=n||(e.includes(".awsapps.com")?e+"/connect/api":e+"/api"),e=new AWS.Endpoint(e),this.client=new AWS.Connect({endpoint:e})}((s.prototype=Object.create(o.prototype)).constructor=s).prototype._callImpl=function(o,e,r){var t=this,i=connect.getLog();connect.contains(this.client,o)?(e=this._translateParams(o,e),i.trace("AWSClient: --\x3e Calling operation '%s'",o).sendInternalLogToServer(),this.client[o](e).on("build",function(e){e.httpRequest.headers["X-Amz-Bearer"]=t.authToken}).send(function(e,t){try{var n;e?(e.code===connect.CTIExceptions.UNAUTHORIZED_EXCEPTION?r.authFailure():!r.accessDenied||e.code!==connect.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==e.statusCode?((n={}).type=e.code,n.message=e.message,n.stack=e.stack?e.stack.split("\n"):[],r.failure(n,t)):r.accessDenied(),i.trace("AWSClient: <-- Operation '%s' failed: %s",o,JSON.stringify(e)).sendInternalLogToServer()):(i.trace("AWSClient: <-- Operation '%s' succeeded.",o).withObject(t).sendInternalLogToServer(),r.success(t))}catch(e){connect.getLog().error("Failed to handle AWS API request for method %s",o).withException(e).sendInternalLogToServer()}})):(e=connect.sprintf("No such method exists on AWS client: %s",o),r.failure(new connect.ValueError(e),{message:e}))},s.prototype._requiresAuthenticationParam=function(e){return e!==connect.ClientMethods.COMPLETE_CONTACT&&e!==connect.ClientMethods.CLEAR_CONTACT&&e!==connect.ClientMethods.REJECT_CONTACT&&e!==connect.ClientMethods.CREATE_TASK_CONTACT},s.prototype._translateParams=function(e,t){switch(e){case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION:t.configuration=this._translateAgentConfiguration(t.configuration);break;case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:t.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(t.softphoneStreamStatistics);break;case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:t.report=this._translateSoftphoneCallReport(t.report)}return this._requiresAuthenticationParam(e)&&(t.authentication={authToken:this.authToken}),t},s.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}},s.prototype._translateRoutingProfile=function(e){return{name:e.name,routingProfileARN:e.routingProfileARN,defaultOutboundQueue:this._translateQueue(e.defaultOutboundQueue)}},s.prototype._translateQueue=function(e){return{queueARN:e.queueARN,name:e.name}},s.prototype._translateSoftphoneStreamStatistics=function(e){return e.forEach(function(e){"packetsCount"in e&&(e.packetCount=e.packetsCount,delete e.packetsCount)}),e},s.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},connect.ClientBase=o,connect.NullClient=e,connect.UpstreamConduitClient=n,connect.UpstreamConduitMasterClient=r,connect.AWSClient=s,connect.AgentAppClient=i}(),function(){connect=this.connect||{},this.connect=connect,this.lily=connect;var o=function(e,t){connect.assertNotNull(e,"fromState"),connect.assertNotNull(t,"toState"),this.fromState=e,this.toState=t};o.prototype.getAssociations=function(e){throw connect.NotImplementedError()},o.prototype.getFromState=function(){return this.fromState},o.prototype.getToState=function(){return this.toState};function e(e,t,n){connect.assertNotNull(e,"fromState"),connect.assertNotNull(t,"toState"),connect.assertNotNull(n,"associations"),o.call(this,e,t),this.associations=n}((e.prototype=Object.create(o.prototype)).constructor=e).prototype.getAssociations=function(e){return this.associations};function i(e,t,n){connect.assertNotNull(e,"fromState"),connect.assertNotNull(t,"toState"),connect.assertNotNull(n,"closure"),connect.assertTrue(connect.isFunction(n),"closure must be a function"),o.call(this,e,t),this.closure=n}((i.prototype=Object.create(o.prototype)).constructor=i).prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};function s(){this.fromMap={}}s.ANY="<>",s.prototype.assoc=function(t,n,o){var r=this;if(!t)throw new Error("fromStateObj is not defined.");if(!n)throw new Error("toStateObj is not defined.");if(!o)throw new Error("assocObj is not defined.");return t instanceof Array?t.forEach(function(e){r.assoc(e,n,o)}):n instanceof Array?n.forEach(function(e){r.assoc(t,e,o)}):"function"==typeof o?this._addAssociation(new i(t,n,o)):o instanceof Array?this._addAssociation(new e(t,n,o)):this._addAssociation(new e(t,n,[o])),this},s.prototype.getAssociations=function(e,t,n){connect.assertNotNull(t,"fromState"),connect.assertNotNull(n,"toState");var o=[],r=this.fromMap[s.ANY]||{},i=this.fromMap[t]||{};return o=(o=o.concat(this._getAssociationsFromMap(r,e,t,n))).concat(this._getAssociationsFromMap(i,e,t,n))},s.prototype._addAssociation=function(e){var t=this.fromMap[e.getFromState()];((t=t||(this.fromMap[e.getFromState()]={}))[e.getToState()]||(t[e.getToState()]=[])).push(e)},s.prototype._getAssociationsFromMap=function(e,n,t,o){return(e[s.ANY]||[]).concat(e[o]||[]).reduce(function(e,t){return e.concat(t.getAssociations(n))},[])},connect.EventGraph=s}(),function(){var n=this;connect=n.connect||{},n.connect=connect,n.lily=connect,connect.AgentStateType=connect.makeEnum(["init","routable","not_routable","offline"]),connect.AgentStatusType=connect.AgentStateType,connect.AgentAvailStates=connect.makeEnum(["Init","Busy","AfterCallWork","CallingCustomer","Dialing","Joining","PendingAvailable","PendingBusy"]),connect.AgentErrorStates=connect.makeEnum(["Error","AgentHungUp","BadAddressAgent","BadAddressCustomer","Default","FailedConnectAgent","FailedConnectCustomer","InvalidLocale","LineEngagedAgent","LineEngagedCustomer","MissedCallAgent","MissedCallCustomer","MultipleCcpWindows","RealtimeCommunicationError"]),connect.EndpointType=connect.makeEnum(["phone_number","agent","queue"]),connect.AddressType=connect.EndpointType,connect.ConnectionType=connect.makeEnum(["agent","inbound","outbound","monitoring"]),connect.ConnectionStateType=connect.makeEnum(["init","connecting","connected","hold","disconnected"]),connect.ConnectionStatusType=connect.ConnectionStateType,connect.CONNECTION_ACTIVE_STATES=connect.set([connect.ConnectionStateType.CONNECTING,connect.ConnectionStateType.CONNECTED,connect.ConnectionStateType.HOLD]),connect.ContactStateType=connect.makeEnum(["init","incoming","pending","connecting","connected","missed","error","ended"]),connect.ContactStatusType=connect.ContactStateType,connect.CONTACT_ACTIVE_STATES=connect.makeEnum(["incoming","pending","connecting","connected"]),connect.ContactType=connect.makeEnum(["voice","queue_callback","chat","task"]),connect.ContactInitiationMethod=connect.makeEnum(["inbound","outbound","transfer","queue_transfer","callback","api","disconnect"]),connect.ChannelType=connect.makeEnum(["VOICE","CHAT","TASK"]),connect.MediaType=connect.makeEnum(["softphone","chat","task"]),connect.SoftphoneCallType=connect.makeEnum(["audio_video","video_only","audio_only","none"]),connect.SoftphoneErrorTypes=connect.makeEnum(["unsupported_browser","microphone_not_shared","signalling_handshake_failure","signalling_connection_failure","ice_collection_timeout","user_busy_error","webrtc_error","realtime_communication_error","other"]),connect.VoiceIdErrorTypes=connect.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"]),connect.CTIExceptions=connect.makeEnum(["AccessDeniedException","InvalidStateException","BadEndpointException","InvalidAgentARNException","InvalidConfigurationException","InvalidContactTypeException","PaginationException","RefreshTokenExpiredException","SendDataFailedException","UnauthorizedException","QuotaExceededException"]),connect.VoiceIdStreamingStatus=connect.makeEnum(["ONGOING","ENDED","PENDING_CONFIGURATION"]),connect.VoiceIdAuthenticationDecision=connect.makeEnum(["ACCEPT","REJECT","NOT_ENOUGH_SPEECH","SPEAKER_NOT_ENROLLED","SPEAKER_OPTED_OUT","SPEAKER_ID_NOT_PROVIDED","SPEAKER_EXPIRED"]),connect.VoiceIdFraudDetectionDecision=connect.makeEnum(["NOT_ENOUGH_SPEECH","HIGH_RISK","LOW_RISK"]),connect.ContactFlowAuthenticationDecision=connect.makeEnum(["Authenticated","NotAuthenticated","Inconclusive","NotEnrolled","OptedOut","NotEnabled","Error"]),connect.ContactFlowFraudDetectionDecision=connect.makeEnum(["HighRisk","LowRisk","Inconclusive","NotEnabled","Error"]),connect.VoiceIdEnrollmentRequestStatus=connect.makeEnum(["NOT_ENOUGH_SPEECH","IN_PROGRESS","COMPLETED","FAILED"]),connect.VoiceIdSpeakerStatus=connect.makeEnum(["OPTED_OUT","ENROLLED","PENDING"]),connect.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},connect.AgentPermissions={OUTBOUND_CALL:"outboundCall",VOICE_ID:"voiceId"};function e(){if(!connect.agent.initialized)throw new connect.StateError("The agent is not yet initialized!")}e.prototype._getData=function(){return connect.core.getAgentDataProvider().getAgentData()},e.prototype._createContactAPI=function(e){return new connect.Contact(e.contactId)},e.prototype.onContactPending=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.CONTACT_PENDING,e)},e.prototype.onRefresh=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.REFRESH,e)},e.prototype.onRoutable=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.ROUTABLE,e)},e.prototype.onNotRoutable=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.NOT_ROUTABLE,e)},e.prototype.onOffline=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.OFFLINE,e)},e.prototype.onError=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.ERROR,e)},e.prototype.onSoftphoneError=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.SOFTPHONE_ERROR,e)},e.prototype.onWebSocketConnectionLost=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST,e)},e.prototype.onWebSocketConnectionGained=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED,e)},e.prototype.onAfterCallWork=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.ACW,e)},e.prototype.onStateChange=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.STATE_CHANGE,e)},e.prototype.onMuteToggle=function(e){connect.core.getUpstream().onUpstream(connect.AgentEvents.MUTE_TOGGLE,e)},e.prototype.onLocalMediaStreamCreated=function(e){connect.core.getUpstream().onUpstream(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,e)},e.prototype.onSpeakerDeviceChanged=function(e){connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,e)},e.prototype.onMicrophoneDeviceChanged=function(e){connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,e)},e.prototype.onRingerDeviceChanged=function(e){connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED,e)},e.prototype.mute=function(){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.MUTE,data:{mute:!0}})},e.prototype.unmute=function(){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.MUTE,data:{mute:!1}})},e.prototype.setSpeakerDevice=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.SET_SPEAKER_DEVICE,data:{deviceId:e}})},e.prototype.setMicrophoneDevice=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.SET_MICROPHONE_DEVICE,data:{deviceId:e}})},e.prototype.setRingerDevice=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.SET_RINGER_DEVICE,data:{deviceId:e}})},e.prototype.getState=function(){return this._getData().snapshot.state},e.prototype.getNextState=function(){return this._getData().snapshot.nextState},e.prototype.getAvailabilityState=function(){return this._getData().snapshot.agentAvailabilityState},e.prototype.getStatus=e.prototype.getState,e.prototype.getStatusDuration=e.prototype.getStateDuration=function(){return connect.now()-this._getData().snapshot.state.startTimestamp.getTime()+connect.core.getSkew()},e.prototype.getPermissions=function(){return this.getConfiguration().permissions},e.prototype.getContacts=function(t){var n=this;return this._getData().snapshot.contacts.map(function(e){return n._createContactAPI(e)}).filter(function(e){return!t||e.getType()===t})},e.prototype.getConfiguration=function(){return this._getData().configuration},e.prototype.getAgentStates=function(){return this.getConfiguration().agentStates},e.prototype.getRoutingProfile=function(){return this.getConfiguration().routingProfile},e.prototype.getChannelConcurrency=function(e){var t=(t=this.getRoutingProfile().channelConcurrencyMap)||Object.keys(connect.ChannelType).reduce(function(e,t){return"TASK"!==t&&(e[connect.ChannelType[t]]=1),e},{});return e?t[e]||0:t},e.prototype.getName=function(){return this.getConfiguration().name},e.prototype.getExtension=function(){return this.getConfiguration().extension},e.prototype.getDialableCountries=function(){return this.getConfiguration().dialableCountries},e.prototype.isSoftphoneEnabled=function(){return this.getConfiguration().softphoneEnabled},e.prototype.setConfiguration=function(e,t){var n=connect.core.getClient();e&&e.agentPreferences&&!connect.isValidLocale(e.agentPreferences.locale)?t&&t.failure&&t.failure(connect.AgentErrorStates.INVALID_LOCALE):n.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION,{configuration:connect.assertNotNull(e,"configuration")},{success:function(e){connect.core.getUpstream().sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION),t.success&&t.success(e)},failure:t&&t.failure})},e.prototype.setState=function(e,t,n){connect.core.getClient().call(connect.ClientMethods.PUT_AGENT_STATE,{state:connect.assertNotNull(e,"state"),enqueueNextState:n&&!!n.enqueueNextState},t)},e.prototype.onEnqueuedNextState=function(e){connect.core.getEventBus().subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE,e)},e.prototype.setStatus=e.prototype.setState,e.prototype.connect=function(e,t){var n=connect.core.getClient(),e=new connect.Endpoint(e);delete e.endpointId,n.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT,{endpoint:connect.assertNotNull(e,"endpoint"),queueARN:t&&(t.queueARN||t.queueId)||this.getRoutingProfile().defaultOutboundQueue.queueARN},t&&{success:t.success,failure:t.failure})},e.prototype.getAllQueueARNs=function(){return this.getConfiguration().routingProfile.queues.map(function(e){return e.queueARN})},e.prototype.getEndpoints=function(t,n,e){var o=this,r=connect.core.getClient();connect.assertNotNull(n,"callbacks"),connect.assertNotNull(n.success,"callbacks.success");var i=e||{};i.endpoints=i.endpoints||[],i.maxResults=i.maxResults||connect.DEFAULT_BATCH_SIZE,connect.isArray(t)||(t=[t]),r.call(connect.ClientMethods.GET_ENDPOINTS,{queueARNs:t,nextToken:i.nextToken||null,maxResults:i.maxResults},{success:function(e){e.nextToken?o.getEndpoints(t,n,{nextToken:e.nextToken,maxResults:i.maxResults,endpoints:i.endpoints.concat(e.endpoints)}):(i.endpoints=i.endpoints.concat(e.endpoints),e=i.endpoints.map(function(e){return new connect.Endpoint(e)}),n.success({endpoints:e,addresses:e}))},failure:n.failure})},e.prototype.getAddresses=e.prototype.getEndpoints,e.prototype._getResourceId=function(){queueArns=this.getAllQueueARNs();for(var e of queueArns){e=e.match(/\/agent\/([^/]+)/);if(e)return e[1]}return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ",queueArns)},e.prototype.toSnapshot=function(){return new connect.AgentSnapshot(this._getData())};function t(e){connect.Agent.call(this),this.agentData=e}((t.prototype=Object.create(e.prototype)).constructor=t).prototype._getData=function(){return this.agentData},t.prototype._createContactAPI=function(e){return new connect.ContactSnapshot(e)};function o(e){this.contactId=e}o.prototype._getData=function(){return connect.core.getAgentDataProvider().getContactData(this.getContactId())},o.prototype._createConnectionAPI=function(e){return new(this.getType()===connect.ContactType.CHAT?connect.ChatConnection:this.getType()===connect.ContactType.TASK?connect.TaskConnection:connect.VoiceConnection)(this.contactId,e.connectionId)},o.prototype.getEventName=function(e){return connect.core.getContactEventName(e,this.getContactId())},o.prototype.onRefresh=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.REFRESH),e)},o.prototype.onIncoming=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.INCOMING),e)},o.prototype.onConnecting=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.CONNECTING),e)},o.prototype.onPending=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.PENDING),e)},o.prototype.onAccepted=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ACCEPTED),e)},o.prototype.onMissed=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.MISSED),e)},o.prototype.onEnded=function(e){var t=connect.core.getEventBus();t.subscribe(this.getEventName(connect.ContactEvents.ENDED),e),t.subscribe(this.getEventName(connect.ContactEvents.DESTROYED),e)},o.prototype.onDestroy=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.DESTROYED),e)},o.prototype.onACW=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ACW),e)},o.prototype.onConnected=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.CONNECTED),e)},o.prototype.onError=function(e){connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ERROR),e)},o.prototype.getContactId=function(){return this.contactId},o.prototype.getInitialContactId=o.prototype.getOriginalContactId=function(){return this._getData().initialContactId},o.prototype.getType=function(){return this._getData().type},o.prototype.getContactDuration=function(){return this._getData().contactDuration},o.prototype.getStatus=o.prototype.getState=function(){return this._getData().state},o.prototype.getStatusDuration=o.prototype.getStateDuration=function(){return connect.now()-this._getData().state.timestamp.getTime()+connect.core.getSkew()},o.prototype.getQueue=function(){return this._getData().queue},o.prototype.getQueueTimestamp=function(){return this._getData().queueTimestamp},o.prototype.getConnections=function(){var t=this;return this._getData().connections.map(function(e){return new(t.getType()===connect.ContactType.CHAT?connect.ChatConnection:t.getType()===connect.ContactType.TASK?connect.TaskConnection:connect.VoiceConnection)(t.contactId,e.connectionId)})},o.prototype.getInitialConnection=function(){return connect.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()!==connect.ConnectionType.AGENT})},o.prototype.getSingleActiveThirdPartyConnection=function(){return this.getThirdPartyConnections().filter(function(e){return e.isActive()})[0]||null},o.prototype.getAgentConnection=function(){return connect.find(this.getConnections(),function(e){e=e.getType();return e===connect.ConnectionType.AGENT||e===connect.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!=connect.find(this.getConnections(),function(e){return null!=e.getSoftphoneMediaInfo()})},o.prototype._isInbound=function(){return this._getData().initiationMethod!==connect.ContactInitiationMethod.OUTBOUND},o.prototype.isInbound=function(){var e=this.getInitialConnection();return e.getMediaType()===connect.MediaType.TASK?this._isInbound():!!e&&e.getType()===connect.ConnectionType.INBOUND},o.prototype.isConnected=function(){return this.getStatus().type===connect.ContactStateType.CONNECTED},o.prototype.accept=function(n){var e=connect.core.getClient(),o=this,r=this.getContactId();e.call(connect.ClientMethods.ACCEPT_CONTACT,{contactId:r},{success:function(e){var t=connect.core.getUpstream();t.sendUpstream(connect.EventType.BROADCAST,{event:connect.ContactEvents.ACCEPTED,data:new connect.Contact(r)}),t.sendUpstream(connect.EventType.BROADCAST,{event:connect.core.getContactEventName(connect.ContactEvents.ACCEPTED,o.getContactId()),data:new connect.Contact(r)});t=new connect.Contact(r);connect.isFirefoxBrowser()&&t.isSoftphoneCall()&&connect.core.triggerReadyToStartSessionEvent(),n&&n.success&&n.success(e)},failure:n?n.failure:null})},o.prototype.destroy=function(){connect.getLog().warn("contact.destroy() has been deprecated.")},o.prototype.reject=function(e){connect.core.getClient().call(connect.ClientMethods.REJECT_CONTACT,{contactId:this.getContactId()},e)},o.prototype.complete=function(e){connect.core.getClient().call(connect.ClientMethods.COMPLETE_CONTACT,{contactId:this.getContactId()},e)},o.prototype.clear=function(e){connect.core.getClient().call(connect.ClientMethods.CLEAR_CONTACT,{contactId:this.getContactId()},e)},o.prototype.notifyIssue=function(e,t,n){connect.core.getClient().call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE,{contactId:this.getContactId(),issueCode:e,description:t},n)},o.prototype.addConnection=function(e,t){var n=connect.core.getClient(),e=new connect.Endpoint(e);delete e.endpointId,n.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION,{contactId:this.getContactId(),endpoint:e},t)},o.prototype.toggleActiveConnections=function(e){var t=connect.core.getClient(),n=null,o=connect.find(this.getConnections(),function(e){return e.getStatus().type===connect.ConnectionStateType.HOLD});null!=o?n=o.getConnectionId():0<(o=this.getConnections().filter(function(e){return e.isActive()})).length&&(n=o[0].getConnectionId()),t.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:n},e)},o.prototype.sendSoftphoneMetrics=function(e,t){connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:n.ccpVersion,softphoneStreamStatistics:e},t),connect.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:n.ccpVersion,stats:e})},o.prototype.sendSoftphoneReport=function(e,t){connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:n.ccpVersion,report:e},t),connect.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:n.ccpVersion,report:e})},o.prototype.conferenceConnections=function(e){connect.core.getClient().call(connect.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},o.prototype.toSnapshot=function(){return new connect.ContactSnapshot(this._getData())};function r(e){connect.Contact.call(this,e.contactId),this.contactData=e}((r.prototype=Object.create(o.prototype)).constructor=r).prototype._getData=function(){return this.contactData},r.prototype._createConnectionAPI=function(e){return new connect.ConnectionSnapshot(e)};var i=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};i.prototype._getData=function(){return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(),this.getConnectionId())},i.prototype.getContactId=function(){return this.contactId},i.prototype.getConnectionId=function(){return this.connectionId},i.prototype.getEndpoint=function(){return new connect.Endpoint(this._getData().endpoint)},i.prototype.getAddress=i.prototype.getEndpoint,i.prototype.getState=function(){return this._getData().state},i.prototype.getStatus=i.prototype.getState,i.prototype.getStateDuration=function(){return connect.now()-this._getData().state.timestamp.getTime()+connect.core.getSkew()},i.prototype.getStatusDuration=i.prototype.getStateDuration,i.prototype.getType=function(){return this._getData().type},i.prototype.isInitialConnection=function(){return this._getData().initial},i.prototype.isActive=function(){return connect.contains(connect.CONNECTION_ACTIVE_STATES,this.getStatus().type)},i.prototype.isConnected=function(){return this.getStatus().type===connect.ConnectionStateType.CONNECTED},i.prototype.isConnecting=function(){return this.getStatus().type===connect.ConnectionStateType.CONNECTING},i.prototype.isOnHold=function(){return this.getStatus().type===connect.ConnectionStateType.HOLD},i.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},i.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},i.prototype.destroy=function(e){connect.core.getClient().call(connect.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},i.prototype.sendDigits=function(e,t){connect.core.getClient().call(connect.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},t)},i.prototype.hold=function(e){connect.core.getClient().call(connect.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},i.prototype.resume=function(e){connect.core.getClient().call(connect.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},i.prototype.toSnapshot=function(){return new connect.ConnectionSnapshot(this._getData())},i.prototype._initMediaController=function(){this.getMediaInfo()&&connect.core.mediaFactory.get(this).catch(function(){})},i.prototype._isAgentConnectionType=function(){var e=this.getType();return e===connect.ConnectionType.AGENT||e===connect.ConnectionType.MONITORING},i.prototype._isAgentConnectionType=function(){var e=this.getType();return e===connect.ConnectionType.AGENT||e===connect.ConnectionType.MONITORING};var s=function(e){this.contactId=e};s.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise(function(n,o){t.call(connect.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:connect.core.getAgentDataProvider().getInstanceId(),awsAccountId:connect.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){var t;e.contactData.customerId?(t={speakerId:e.contactData.customerId},connect.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),n(t)):(t=connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call"),o(t))},failure:function(e){connect.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();e=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(e)}})})},s.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var n=connect.core.getClient();return new Promise(function(o,r){e.getSpeakerId().then(function(t){e.getDomainId().then(function(e){n.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:connect.assertNotNull(t.speakerId,"speakerId"),DomainId:e},{success:function(e){connect.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){var t=JSON.parse(e);switch(t.status){case 400:case 404:var n=t;n.type=n.type||connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),o(n);break;default:connect.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();n=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);r(n)}}})}).catch(function(e){r(e)})}).catch(function(e){r(e)})})},s.prototype._optOutSpeakerInLcms=function(e){var o=this,r=connect.core.getClient();return new Promise(function(t,n){r.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:o.contactId,InstanceId:connect.core.getAgentDataProvider().getInstanceId(),AWSAccountId:connect.core.getAgentDataProvider().getAWSAccountId(),CustomerId:connect.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0}},{success:function(e){connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),t(e)},failure:function(e){connect.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();e=connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);n(e)}})})},s.prototype.optOutSpeaker=function(){var i=this;i.checkConferenceCall();var s=connect.core.getClient();return new Promise(function(o,r){i.getSpeakerId().then(function(n){i.getDomainId().then(function(e){var t=n.speakerId;s.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:connect.assertNotNull(t,"speakerId"),DomainId:e},{success:function(e){i._optOutSpeakerInLcms(t).catch(function(){}),connect.getLog().info("optOutSpeaker succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){connect.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();e=connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);r(e)}})}).catch(function(e){r(e)})}).catch(function(e){r(e)})})},s.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var r=connect.core.getClient();return new Promise(function(n,o){e.getSpeakerId().then(function(t){e.getDomainId().then(function(e){r.call(connect.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:connect.assertNotNull(t.speakerId,"speakerId"),DomainId:e},{success:function(e){connect.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),n(e)},failure:function(e){connect.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();e=connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(e)}})}).catch(function(e){o(e)})}).catch(function(e){o(e)})})},s.prototype.startSession=function(){var o=this;o.checkConferenceCall();var r=connect.core.getClient();return new Promise(function(t,n){o.getDomainId().then(function(e){r.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:o.contactId,instanceId:connect.core.getAgentDataProvider().getInstanceId(),customerAccountId:connect.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:e},{success:function(e){e.sessionId?t(e):(connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer(),e=connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api"),n(e))},failure:function(e){connect.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();e=connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);n(e)}})}).catch(function(e){n(e)})})},s.prototype.evaluateSpeaker=function(e){var i=this;i.checkConferenceCall();var t=connect.core.getClient(),s=connect.core.getAgentDataProvider().getContactData(this.contactId),c=0;return new Promise(function(n,o){function r(){i.getDomainId().then(function(e){t.call(connect.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:s.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++c=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){e=e.prefix||"";return"DEBUG"===this._logsDestination?this.consoleLoggerWrapper:new y(e)}},{key:"updateLoggerConfig",value:function(e){e=e||{};this._level=e.level||f.DEBUG,this._clientLogger=e.logger||null,this._logsDestination="NULL",e.debug&&(this._logsDestination="DEBUG"),e.logger&&(this._logsDestination="CLIENT_LOGGER")}}]),b),m=(h(S,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),S),y=(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&&u(e,t)}(E,m),h(E,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n>>0).toString(8);break;case"s":n=String(n),n=r.precision?n.substring(0,r.precision):n;break;case"t":n=String(!!n),n=r.precision?n.substring(0,r.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=r.precision?n.substring(0,r.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=r.precision?n.substring(0,r.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}d.json.test(r.type)?p+=n:(!d.number.test(r.type)||c&&!r.sign?a="":(a=c?"+":"-",n=n.toString().replace(d.sign,"")),i=r.pad_char?"0"===r.pad_char?"0":r.pad_char.charAt(1):" ",s=r.width-(a+n).length,s=r.width&&0t.packetsLost?e.packetsLost-t.packetsLost:0,t=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new F(e.timestamp,o,t,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new F(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},U=function(e){return null!==e&&window.clearInterval(e),null},q=function(e,t){c=U(c),a=U(a),d(e,t,B(o,i),B(r,s)),h(e)},F=function(e,t,n,o,r,i,s){this.softphoneStreamType=o,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=r,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},B=function(e,t){return new F((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},j=function(e){this._originalLogger=e;var o=this;this._tee=function(e,n){return function(){var e=Array.prototype.slice.call(arguments[0]),t="";return e.forEach(function(){t+=" %s"}),n.apply(o._originalLogger,[connect.LogComponent.SOFTPHONE,t].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)},connect.SoftphoneManager=function(e){var i,n=this;(g=new j(connect.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),connect.RtcPeerConnectionFactory&&(i=new connect.RtcPeerConnectionFactory(g,connect.core.getWebSocketManager(),E,connect.hitch(n,S,{transportType:"softphone",softphoneClientId:E}),connect.hitch(n,N))),D()||N(m.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ","");R({success:function(e){connect.core.setSoftphoneUserMediaStream(e)},failure:function(e){N(e,"Your microphone is not enabled in your browser. ","")}});C(),T(),I(),this.ringtoneEngine=null;var s={},c={};this.onInitContactSub={};var a=!(this.onInitContactSub.unsubscribe=function(){}),u=null,l=null,o=function(e,t){a=!0,u=e,l=t},p=function(){a=!1,l=u=null};this.getSession=function(e){return s[e]},this.replaceLocalMediaTrack=function(e,t){var n=v[e].stream;n&&(e=n.getAudioTracks()[0],t.enabled=e.enabled,e.enabled=!1,n.removeTrack(e),n.addTrack(t))};var r=function(e){return e.getStatus().type===connect.ContactStatusType.ENDED||e.getStatus().type===connect.ContactStatusType.ERROR||e.getStatus().type===connect.ContactStatusType.MISSED},h=function(n){var o;s.hasOwnProperty(n)&&(o=s[n],new Promise(function(e,t){delete s[n],delete c[n],o.hangup()}).catch(function(e){lily.getLog().warn("Clean up the session locally "+n,e.message).sendInternalLogToServer()}))};this.startSession=function(e,t){var n,o=a?u:e,r=a?l:t;o&&r&&(p(),c[r]=!0,g.info("Softphone call detected:","contactId "+o.getContactId(),"agent connectionId "+r).sendInternalLogToServer(),function(e){if(0o&&n.handleSendLogsRequest(n.logsBuffer)}),this.conduit.onDownstream(connect.EventType.CONFIGURE,function(e){e.authToken&&e.authToken!==n.initData.authToken&&(n.initData=e,connect.core.init(e),t?connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),connect.WebSocketManager.setGlobalConfig({loggerConfig:{logger:connect.getLog()}}),(t=connect.WebSocketManager.create()).onInitFailure(function(){n.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE)}),t.onConnectionOpen(function(e){n.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN,e)}),t.onConnectionClose(function(e){n.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE,e)}),t.onConnectionGain(function(){n.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED),n.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN)}),t.onConnectionLost(function(e){n.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),n.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST,e)}),t.onSubscriptionUpdate(function(e){n.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE,e)}),t.onSubscriptionFailure(function(e){n.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE,e)}),t.onAllMessage(function(e){n.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE,e)}),n.conduit.onDownstream(connect.WebSocketEvents.SEND,function(e){t.sendMessage(e)}),n.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE,function(e){t.subscribeTopics(e)}),t.init(connect.hitch(n,n.getWebSocketUrl)).then(function(e){e&&!e.webSocketConnectionFailed?(connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(),n.pollForAgent(),connect.getLog().info("Kicking off config polling").sendInternalLogToServer(),n.pollForAgentConfiguration({repeatForever:!0}),connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),r.setInterval(connect.hitch(n,n.checkAuthToken),i)):connect.webSocketInitFailed||(n.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE),connect.webSocketInitFailed=!0)})))}),this.conduit.onDownstream(connect.EventType.TERMINATE,function(){n.handleSendLogsRequest(n.logsBuffer),connect.core.terminate(),n.conduit.sendDownstream(connect.EventType.TERMINATED)}),this.conduit.onDownstream(connect.EventType.SYNCHRONIZE,function(){n.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE)}),this.conduit.onDownstream(connect.EventType.BROADCAST,function(e){n.conduit.sendDownstream(e.event,e.data)}),r.onconnect=function(e){var e=e.ports[0],t=new connect.PortStream(e);n.multiplexer.addStream(t),e.start();e=new connect.Conduit(t.getId(),null,t);e.sendDownstream(connect.EventType.ACKNOWLEDGE,{id:t.getId()}),n.portConduitMap[t.getId()]=e,n.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(n.portConduitMap).length}),null!==n.agent&&n.updateAgent(),e.onDownstream(connect.EventType.API_REQUEST,connect.hitch(n,n.handleAPIRequest,e)),e.onDownstream(connect.EventType.MASTER_REQUEST,connect.hitch(n,n.handleMasterRequest,e,t.getId())),e.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION,connect.hitch(n,n.pollForAgentConfiguration)),e.onDownstream(connect.EventType.CLOSE,function(){n.multiplexer.removeStream(t),delete n.portConduitMap[t.getId()],n.masterCoord.removeMaster(t.getId()),n.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(n.portConduitMap).length})})}}t.prototype.pollForAgent=function(){var n=this,e=connect.hitch(n,n.handleAuthFail);this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:n.nextToken,timeout:3e4},{success:function(t){try{n.agent=n.agent||{},n.agent.snapshot=t.snapshot,n.agent.snapshot.localTimestamp=connect.now(),n.agent.snapshot.skew=n.agent.snapshot.snapshotTimestamp-n.agent.snapshot.localTimestamp,n.nextToken=t.nextToken,connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(t).sendInternalLogToServer(),n.updateAgent()}catch(e){connect.getLog().error("Long poll failed to update agent.").withObject(t).withException(e).sendInternalLogToServer()}finally{r.setTimeout(connect.hitch(n,n.pollForAgent),100)}},failure:function(e,t){try{connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:e,data:t})}finally{r.setTimeout(connect.hitch(n,n.pollForAgent),5e3)}},authFailure:function(){e()},accessDenied:connect.hitch(n,n.handleAccessDenied)})},t.prototype.pollForAgentConfiguration=function(e){var n=this,o=e||{},t=connect.hitch(n,n.handleAuthFail);this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(e){e=e.configuration;n.pollForAgentPermissions(e),n.pollForAgentStates(e),n.pollForDialableCountryCodes(e),n.pollForRoutingProfileQueues(e),o.repeatForever&&r.setTimeout(connect.hitch(n,n.pollForAgentConfiguration,o),3e4)},failure:function(e,t){try{connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:e,data:t})}finally{o.repeatForever&&r.setTimeout(connect.hitch(n,n.pollForAgentConfiguration),3e4,o)}},authFailure:function(){t()},accessDenied:connect.hitch(n,n.handleAccessDenied)})},t.prototype.pollForAgentStates=function(t,e){var n=this,o=e||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(e){e.nextToken?n.pollForAgentStates(t,{states:(o.states||[]).concat(e.states),nextToken:e.nextToken,maxResults:o.maxResults}):(t.agentStates=(o.states||[]).concat(e.states),n.updateAgentConfiguration(t))},failure:function(e,t){connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},t.prototype.pollForAgentPermissions=function(t,e){var n=this,o=e||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(e){e.nextToken?n.pollForAgentPermissions(t,{permissions:(o.permissions||[]).concat(e.permissions),nextToken:e.nextToken,maxResults:o.maxResults}):(t.permissions=(o.permissions||[]).concat(e.permissions),n.updateAgentConfiguration(t))},failure:function(e,t){connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},t.prototype.pollForDialableCountryCodes=function(t,e){var n=this,o=e||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(e){e.nextToken?n.pollForDialableCountryCodes(t,{countryCodes:(o.countryCodes||[]).concat(e.countryCodes),nextToken:e.nextToken,maxResults:o.maxResults}):(t.dialableCountries=(o.countryCodes||[]).concat(e.countryCodes),n.updateAgentConfiguration(t))},failure:function(e,t){connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},t.prototype.pollForRoutingProfileQueues=function(t,e){var n=this,o=e||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:t.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(e){e.nextToken?n.pollForRoutingProfileQueues(t,{countryCodes:(o.queues||[]).concat(e.queues),nextToken:e.nextToken,maxResults:o.maxResults}):(t.routingProfile.queues=(o.queues||[]).concat(e.queues),n.updateAgentConfiguration(t))},failure:function(e,t){connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},t.prototype.handleAPIRequest=function(n,o){var r=this;this.client.call(o.method,o.params,{success:function(e){e=connect.EventFactory.createResponse(connect.EventType.API_RESPONSE,o,e);n.sendDownstream(e.event,e)},failure:function(e,t){t=connect.EventFactory.createResponse(connect.EventType.API_RESPONSE,o,t,JSON.stringify(e));n.sendDownstream(t.event,t),connect.getLog().error("'%s' API request failed",o.method).withObject({request:r.filterAuthToken(o),response:t}).withException(e).sendInternalLogToServer()},authFailure:connect.hitch(r,r.handleAuthFail)})},t.prototype.handleMasterRequest=function(e,t,n){var o=this.conduit,r=null;switch(n.method){case connect.MasterMethods.BECOME_MASTER:var i=this.masterCoord.getMaster(n.params.topic),s=Boolean(i)&&i!==t;this.masterCoord.setMaster(n.params.topic,t),r=connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE,n,{masterId:t,takeOver:s,topic:n.params.topic}),s&&o.sendDownstream(r.event,r);break;case connect.MasterMethods.CHECK_MASTER:(i=this.masterCoord.getMaster(n.params.topic))||n.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(n.params.topic,t),i=t),r=connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE,n,{masterId:i,isMaster:t===i,topic:n.params.topic});break;default:throw new Error("Unknown master method: "+n.method)}e.sendDownstream(r.event,r)},t.prototype.updateAgentConfiguration=function(e){e.permissions&&e.dialableCountries&&e.agentStates&&e.routingProfile.queues?(this.agent=this.agent||{},this.agent.configuration=e,this.updateAgent()):connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer()},t.prototype.updateAgent=function(){this.agent?this.agent.snapshot?this.agent.configuration?(this.agent.snapshot.status=this.agent.state,this.agent.snapshot.contacts&&1{var e={340:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect,connect.agentApp={};var t="ccp";connect.agentApp.initCCP=connect.core.initCCP,connect.agentApp.isInitialized=function(e){},connect.agentApp.initAppCommunication=function(e,t){var n=document.getElementById(e),o=new connect.IFrameConduit(t,window,n),r=[connect.AgentEvents.UPDATE,connect.ContactEvents.VIEW,connect.EventType.ACKNOWLEDGE,connect.EventType.TERMINATED,connect.TaskEvents.CREATED];n.addEventListener("load",(function(e){r.forEach((function(e){connect.core.getUpstream().onUpstream(e,(function(t){o.sendUpstream(e,t)}))}))}))};var n=function(e){var t=e.indexOf("ccp-v2");return e.slice(0,t-1)};connect.agentApp.initApp=function(e,o,r,i){i=i||{};var s=r.endsWith("/")?r:r+"/",c=i.onLoad?i.onLoad:null,a={endpoint:s,style:i.style,onLoad:c};connect.agentApp.AppRegistry.register(e,a,document.getElementById(o)),connect.agentApp.AppRegistry.start(e,(function(o){var r=o.endpoint,s=o.containerDOM;return{init:function(){return e===t?function(e,t,o){var r={ccpUrl:e,ccpLoadTimeout:1e4,loginPopup:!0,loginUrl:n(e)+"/login",softphone:{allowFramedSoftphone:!0,disableRingtone:!1}},i=connect.merge(r,o.ccpParams);connect.core.initCCP(t,i)}(r,s,i):connect.agentApp.initAppCommunication(e,r)},destroy:function(){return e===t?(o=n(r)+"/logout",connect.fetch(o,{credentials:"include"}).then((function(){return connect.core.getEventBus().trigger(connect.EventType.TERMINATE),!0})).catch((function(e){return connect.getLog().error("An error occured on logout."+e).withException(e),window.location.href=o,!1}))):null;var o}}}))},connect.agentApp.stopApp=function(e){return connect.agentApp.AppRegistry.stop(e)}}()},228:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect;var t,n="ccp";e.connect.agentApp.AppRegistry=(t={},{register:function(e,n,o){t[e]={containerDOM:o,endpoint:n.endpoint,style:n.style,instance:void 0,onLoad:n.onLoad}},start:function(e,o){if(t[e]){var r=t[e].containerDOM,i=t[e].endpoint,s=t[e].style,c=t[e].onLoad;if(e!==n){var a=function(e,t,n,o){var r=document.createElement("iframe");return r.src=t,r.style=n||"width: 100%; height:100%;",r.id=e,r["aria-label"]=e,r.onload=o,r.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),r}(e,i,s,c);r.appendChild(a)}return t[e].instance=o(t[e]),t[e].instance.init()}},stop:function(e){if(t[e]){var n,o=t[e],r=o.containerDOM.querySelector("iframe");return o.containerDOM.removeChild(r),o.instance&&(n=o.instance.destroy(),delete o.instance),n}}})}()},35:()=>{function e(e,n){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!o){if(Array.isArray(e)||(o=function(e,n){if(e){if("string"==typeof e)return t(e,n);var o=Object.prototype.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){o&&(e=o);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,c=!0,a=!1;return{s:function(){o=o.call(e)},n:function(){var e=o.next();return c=e.done,e},e:function(e){a=!0,s=e},f:function(){try{c||null==o.return||o.return()}finally{if(a)throw s}}}}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n0&&(n=r[0].getConnectionId())}t.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:n},e)},r.prototype.sendSoftphoneMetrics=function(e,n){connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:t.ccpVersion,softphoneStreamStatistics:e},n),connect.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:t.ccpVersion,stats:e})},r.prototype.sendSoftphoneReport=function(e,n){connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:t.ccpVersion,report:e},n),connect.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:t.ccpVersion,report:e})},r.prototype.conferenceConnections=function(e){connect.core.getClient().call(connect.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},r.prototype.toSnapshot=function(){return new connect.ContactSnapshot(this._getData())};var i=function(e){connect.Contact.call(this,e.contactId),this.contactData=e};(i.prototype=Object.create(r.prototype)).constructor=i,i.prototype._getData=function(){return this.contactData},i.prototype._createConnectionAPI=function(e){return new connect.ConnectionSnapshot(e)};var s=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};s.prototype._getData=function(){return connect.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 connect.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 connect.now()-this._getData().state.timestamp.getTime()+connect.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 connect.contains(connect.CONNECTION_ACTIVE_STATES,this.getStatus().type)},s.prototype.isConnected=function(){return this.getStatus().type===connect.ConnectionStateType.CONNECTED},s.prototype.isConnecting=function(){return this.getStatus().type===connect.ConnectionStateType.CONNECTING},s.prototype.isOnHold=function(){return this.getStatus().type===connect.ConnectionStateType.HOLD},s.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},s.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},s.prototype.destroy=function(e){connect.core.getClient().call(connect.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.sendDigits=function(e,t){connect.core.getClient().call(connect.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},t)},s.prototype.hold=function(e){connect.core.getClient().call(connect.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.resume=function(e){connect.core.getClient().call(connect.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.toSnapshot=function(){return new connect.ConnectionSnapshot(this._getData())},s.prototype._initMediaController=function(){this.getMediaInfo()&&connect.core.mediaFactory.get(this).catch((function(){}))},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===connect.ConnectionType.AGENT||e===connect.ConnectionType.MONITORING},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===connect.ConnectionType.AGENT||e===connect.ConnectionType.MONITORING};var c=function(e){this.contactId=e};c.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){t.call(connect.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:connect.core.getAgentDataProvider().getInstanceId(),awsAccountId:connect.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){if(e.contactData.customerId){var t={speakerId:e.contactData.customerId};connect.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),n(t)}else{var r=connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call");o(r)}},failure:function(e){connect.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(t)}})}))},c.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getSpeakerId().then((function(r){e.getDomainId().then((function(e){t.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:connect.assertNotNull(r.speakerId,"speakerId"),DomainId:e},{success:function(e){connect.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),n(e)},failure:function(e){var t=JSON.parse(e);switch(t.status){case 400:case 404:var r=t;r.type=r.type?r.type:connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),n(r);break;default:connect.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();var i=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);o(i)}}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype._optOutSpeakerInLcms=function(e){var t=this,n=connect.core.getClient();return new Promise((function(o,r){n.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:t.contactId,InstanceId:connect.core.getAgentDataProvider().getInstanceId(),AWSAccountId:connect.core.getAgentDataProvider().getAWSAccountId(),CustomerId:connect.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0}},{success:function(e){connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){connect.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);r(t)}})}))},c.prototype.optOutSpeaker=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getSpeakerId().then((function(r){e.getDomainId().then((function(i){var s=r.speakerId;t.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:connect.assertNotNull(s,"speakerId"),DomainId:i},{success:function(t){e._optOutSpeakerInLcms(s).catch((function(){})),connect.getLog().info("optOutSpeaker succeeded").withObject(t).sendInternalLogToServer(),n(t)},failure:function(e){connect.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);o(t)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getSpeakerId().then((function(r){e.getDomainId().then((function(e){t.call(connect.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:connect.assertNotNull(r.speakerId,"speakerId"),DomainId:e},{success:function(e){connect.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),n(e)},failure:function(e){connect.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(t)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.startSession=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getDomainId().then((function(r){t.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:e.contactId,instanceId:connect.core.getAgentDataProvider().getInstanceId(),customerAccountId:connect.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:r},{success:function(e){if(e.sessionId)n(e);else{connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api");o(t)}},failure:function(e){connect.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);o(t)}})})).catch((function(e){o(e)}))}))},c.prototype.evaluateSpeaker=function(e){var t=this;t.checkConferenceCall();var n=connect.core.getClient(),o=connect.core.getAgentDataProvider().getContactData(this.contactId),r=0;return new Promise((function(i,s){function c(){t.getDomainId().then((function(e){n.call(connect.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:o.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++r=1&&(o=n.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i,"")),!o){connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer();var r=connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND);return void t(r)}connect.getLog().info("getDomainId succeeded").withObject(n).sendInternalLogToServer(),connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.VoiceIdEvents.UPDATE_DOMAIN_ID,data:{domainId:o}}),e(o)}catch(e){connect.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer(),r=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e),t(r)}},failure:function(e){connect.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer();var n=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e);t(n)}}):t(new Error("Agent doesn't have the permission for Voice ID"))}))},c.prototype.checkConferenceCall=function(){if(connect.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return connect.contains(connect.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new connect.NotImplementedError("VoiceId is not supported for conference calls")},c.prototype.isAuthEnabled=function(e){return e!==connect.ContactFlowAuthenticationDecision.NOT_ENABLED},c.prototype.isAuthResultNotEnoughSpeech=function(e){return e===connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH},c.prototype.isAuthResultInconclusive=function(e){return e===connect.ContactFlowAuthenticationDecision.INCONCLUSIVE},c.prototype.isFraudEnabled=function(e){return e!==connect.ContactFlowFraudDetectionDecision.NOT_ENABLED},c.prototype.isFraudResultNotEnoughSpeech=function(e){return e===connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH},c.prototype.isFraudResultInconclusive=function(e){return e===connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE};var a=function(e,t){this._speakerAuthenticator=new c(e),s.call(this,e,t)};(a.prototype=Object.create(s.prototype)).constructor=a,a.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},a.prototype.getMediaInfo=function(){return this._getData().softphoneMediaInfo},a.prototype.getMediaType=function(){return connect.MediaType.SOFTPHONE},a.prototype.getMediaController=function(){return connect.core.mediaFactory.get(this)},a.prototype.getVoiceIdSpeakerId=function(){return this._speakerAuthenticator.getSpeakerId()},a.prototype.getVoiceIdSpeakerStatus=function(){return this._speakerAuthenticator.getSpeakerStatus()},a.prototype.optOutVoiceIdSpeaker=function(){return this._speakerAuthenticator.optOutSpeaker()},a.prototype.deleteVoiceIdSpeaker=function(){return this._speakerAuthenticator.deleteSpeaker()},a.prototype.evaluateSpeakerWithVoiceId=function(e){return this._speakerAuthenticator.evaluateSpeaker(e)},a.prototype.enrollSpeakerInVoiceId=function(){return this._speakerAuthenticator.enrollSpeaker()},a.prototype.updateVoiceIdSpeakerId=function(e){return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e)},a.prototype.getQuickConnectName=function(){return this._getData().quickConnectName},a.prototype.isMute=function(){return this._getData().mute},a.prototype.muteParticipant=function(e){connect.core.getClient().call(connect.ClientMethods.MUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},a.prototype.unmuteParticipant=function(e){connect.core.getClient().call(connect.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 t=connect.core.getAgentDataProvider().getContactData(this.contactId),n={contactId:this.contactId,initialContactId:t.initialContactId||this.contactId,participantId:this.connectionId,getConnectionToken:connect.hitch(this,this.getConnectionToken)};if(e.connectionData)try{n.participantToken=JSON.parse(e.connectionData).ConnectionAuthenticationToken}catch(t){connect.getLog().error(connect.LogComponent.CHAT,"Connection data is invalid").withObject(e).withException(t).sendInternalLogToServer(),n.participantToken=null}return n.participantToken=n.participantToken||null,n.originalInfo=this._getData().chatMediaInfo,n}return null},u.prototype.getConnectionToken=function(){client=connect.core.getClient();var e=connect.core.getAgentDataProvider().getContactData(this.contactId),t={transportType:connect.TRANSPORT_TYPES.CHAT_TOKEN,participantId:this.connectionId,contactId:e.initialContactId||this.contactId};return new Promise((function(e,n){client.call(connect.ClientMethods.CREATE_TRANSPORT,t,{success:function(t){connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(),e(t)},failure:function(e,t){connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({err:e,data:t}),n(Error("getConnectionToken failed"))}})}))},u.prototype.getMediaType=function(){return connect.MediaType.CHAT},u.prototype.getMediaController=function(){return connect.core.mediaFactory.get(this)},u.prototype._initMediaController=function(){this._isAgentConnectionType()&&connect.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 connect.MediaType.TASK},l.prototype.getMediaInfo=function(){var e=connect.core.getAgentDataProvider().getContactData(this.contactId);return{contactId:this.contactId,initialContactId:e.initialContactId||this.contactId}},l.prototype.getMediaController=function(){return connect.core.mediaFactory.get(this)};var p=function(e){connect.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,t){return new h({type:connect.EndpointType.PHONE_NUMBER,phoneNumber:e,name:t||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},connect.agent=function(e){var t=connect.core.getEventBus().subscribe(connect.AgentEvents.INIT,e);return connect.agent.initialized&&e(new connect.Agent),t},connect.agent.initialized=!1,connect.contact=function(e){return connect.core.getEventBus().subscribe(connect.ContactEvents.INIT,e)},connect.onWebsocketInitFailure=function(e){var t=connect.core.getEventBus().subscribe(connect.WebSocketEvents.INIT_FAILURE,e);return connect.webSocketInitFailed&&e(),t},connect.ifMaster=function(e,t,n,o){if(connect.assertNotNull(e,"A topic must be provided."),connect.assertNotNull(t,"A true callback must be provided."),!connect.core.masterClient)return connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e).sendInternalLogToServer(),void(n&&n());connect.core.getMasterClient().call(connect.MasterMethods.CHECK_MASTER,{topic:e,shouldNotBecomeMasterIfNone:o},{success:function(e){e.isMaster?t():n&&n()}})},connect.becomeMaster=function(e,t,n){connect.assertNotNull(e,"A topic must be provided."),connect.core.masterClient?connect.core.getMasterClient().call(connect.MasterMethods.BECOME_MASTER,{topic:e},{success:function(){t&&t()}}):(connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e),n&&n())},connect.Agent=n,connect.AgentSnapshot=o,connect.Contact=r,connect.ContactSnapshot=i,connect.Connection=a,connect.BaseConnection=s,connect.VoiceConnection=a,connect.ChatConnection=u,connect.TaskConnection=l,connect.ConnectionSnapshot=p,connect.Endpoint=h,connect.Address=h,connect.SoftphoneError=d,connect.VoiceId=c}()},538:(e,t,n)=>{var o;function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}!function e(t,n,o){function r(s,c){if(!n[s]){if(!t[s]){if(i)return i(s,!0);var a=new Error("Cannot find module '"+s+"'");throw a.code="MODULE_NOT_FOUND",a}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return r(t[s][1][e]||e)}),u,u.exports,e,t,n,o)}return n[s].exports}for(var i=void 0,s=0;s-1});var r=["[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 o(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 o=e("./browserHashUtils");function r(e,t){this.hash=new e,this.outer=new e;var n=function(e,t){var n=o.convertToBuffer(t);if(n.byteLength>e.BLOCK_SIZE){var r=new e;r.update(n),n=r.digest()}var i=new Uint8Array(e.BLOCK_SIZE);return i.set(n),i}(e,t),r=new Uint8Array(e.BLOCK_SIZE);r.set(n);for(var i=0;i>>32-r)+n&4294967295}function a(e,t,n,o,r,i,s){return c(t&n|~t&o,e,t,r,i,s)}function u(e,t,n,o,r,i,s){return c(t&o|n&~o,e,t,r,i,s)}function l(e,t,n,o,r,i,s){return c(t^n^o,e,t,r,i,s)}function p(e,t,n,o,r,i,s){return c(n^(t|~o),e,t,r,i,s)}t.exports=s,s.BLOCK_SIZE=i,s.prototype.update=function(e){if(o.isEmptyData(e))return this;if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=o.convertToBuffer(e),n=0,r=t.byteLength;for(this.bytesHashed+=r;r>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),r--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},s.prototype.digest=function(e){if(!this.finished){var t=this,n=t.buffer,o=t.bufferLength,s=8*t.bytesHashed;if(n.setUint8(this.bufferLength++,128),o%i>=56){for(var c=this.bufferLength;c>>0,!0),n.setUint32(60,Math.floor(s/4294967296),!0),this.hashBuffer(),this.finished=!0}var a=new DataView(new ArrayBuffer(16));for(c=0;c<4;c++)a.setUint32(4*c,this.state[c],!0);var u=new r(a.buffer,a.byteOffset,a.byteLength);return e?u.toString(e):u},s.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],o=t[1],r=t[2],i=t[3];n=a(n,o,r,i,e.getUint32(0,!0),7,3614090360),i=a(i,n,o,r,e.getUint32(4,!0),12,3905402710),r=a(r,i,n,o,e.getUint32(8,!0),17,606105819),o=a(o,r,i,n,e.getUint32(12,!0),22,3250441966),n=a(n,o,r,i,e.getUint32(16,!0),7,4118548399),i=a(i,n,o,r,e.getUint32(20,!0),12,1200080426),r=a(r,i,n,o,e.getUint32(24,!0),17,2821735955),o=a(o,r,i,n,e.getUint32(28,!0),22,4249261313),n=a(n,o,r,i,e.getUint32(32,!0),7,1770035416),i=a(i,n,o,r,e.getUint32(36,!0),12,2336552879),r=a(r,i,n,o,e.getUint32(40,!0),17,4294925233),o=a(o,r,i,n,e.getUint32(44,!0),22,2304563134),n=a(n,o,r,i,e.getUint32(48,!0),7,1804603682),i=a(i,n,o,r,e.getUint32(52,!0),12,4254626195),r=a(r,i,n,o,e.getUint32(56,!0),17,2792965006),n=u(n,o=a(o,r,i,n,e.getUint32(60,!0),22,1236535329),r,i,e.getUint32(4,!0),5,4129170786),i=u(i,n,o,r,e.getUint32(24,!0),9,3225465664),r=u(r,i,n,o,e.getUint32(44,!0),14,643717713),o=u(o,r,i,n,e.getUint32(0,!0),20,3921069994),n=u(n,o,r,i,e.getUint32(20,!0),5,3593408605),i=u(i,n,o,r,e.getUint32(40,!0),9,38016083),r=u(r,i,n,o,e.getUint32(60,!0),14,3634488961),o=u(o,r,i,n,e.getUint32(16,!0),20,3889429448),n=u(n,o,r,i,e.getUint32(36,!0),5,568446438),i=u(i,n,o,r,e.getUint32(56,!0),9,3275163606),r=u(r,i,n,o,e.getUint32(12,!0),14,4107603335),o=u(o,r,i,n,e.getUint32(32,!0),20,1163531501),n=u(n,o,r,i,e.getUint32(52,!0),5,2850285829),i=u(i,n,o,r,e.getUint32(8,!0),9,4243563512),r=u(r,i,n,o,e.getUint32(28,!0),14,1735328473),n=l(n,o=u(o,r,i,n,e.getUint32(48,!0),20,2368359562),r,i,e.getUint32(20,!0),4,4294588738),i=l(i,n,o,r,e.getUint32(32,!0),11,2272392833),r=l(r,i,n,o,e.getUint32(44,!0),16,1839030562),o=l(o,r,i,n,e.getUint32(56,!0),23,4259657740),n=l(n,o,r,i,e.getUint32(4,!0),4,2763975236),i=l(i,n,o,r,e.getUint32(16,!0),11,1272893353),r=l(r,i,n,o,e.getUint32(28,!0),16,4139469664),o=l(o,r,i,n,e.getUint32(40,!0),23,3200236656),n=l(n,o,r,i,e.getUint32(52,!0),4,681279174),i=l(i,n,o,r,e.getUint32(0,!0),11,3936430074),r=l(r,i,n,o,e.getUint32(12,!0),16,3572445317),o=l(o,r,i,n,e.getUint32(24,!0),23,76029189),n=l(n,o,r,i,e.getUint32(36,!0),4,3654602809),i=l(i,n,o,r,e.getUint32(48,!0),11,3873151461),r=l(r,i,n,o,e.getUint32(60,!0),16,530742520),n=p(n,o=l(o,r,i,n,e.getUint32(8,!0),23,3299628645),r,i,e.getUint32(0,!0),6,4096336452),i=p(i,n,o,r,e.getUint32(28,!0),10,1126891415),r=p(r,i,n,o,e.getUint32(56,!0),15,2878612391),o=p(o,r,i,n,e.getUint32(20,!0),21,4237533241),n=p(n,o,r,i,e.getUint32(48,!0),6,1700485571),i=p(i,n,o,r,e.getUint32(12,!0),10,2399980690),r=p(r,i,n,o,e.getUint32(40,!0),15,4293915773),o=p(o,r,i,n,e.getUint32(4,!0),21,2240044497),n=p(n,o,r,i,e.getUint32(32,!0),6,1873313359),i=p(i,n,o,r,e.getUint32(60,!0),10,4264355552),r=p(r,i,n,o,e.getUint32(24,!0),15,2734768916),o=p(o,r,i,n,e.getUint32(52,!0),21,1309151649),n=p(n,o,r,i,e.getUint32(16,!0),6,4149444226),i=p(i,n,o,r,e.getUint32(44,!0),10,3174756917),r=p(r,i,n,o,e.getUint32(8,!0),15,718787259),o=p(o,r,i,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=o+t[1]&4294967295,t[2]=r+t[2]&4294967295,t[3]=i+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":81}],14:[function(e,t,n){var o=e("buffer/").Buffer,r=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(r.isEmptyData(e))return this;var t=(e=r.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 o(20),r=new DataView(n.buffer);return r.setUint32(0,this.h0,!1),r.setUint32(4,this.h1,!1),r.setUint32(8,this.h2,!1),r.setUint32(12,this.h3,!1),r.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,o,r=this.h0,i=this.h1,s=this.h2,c=this.h3,a=this.h4;for(e=0;e<80;e++){e<20?(n=c^i&(s^c),o=1518500249):e<40?(n=i^s^c,o=1859775393):e<60?(n=i&s|c&(i|s),o=2400959708):(n=i^s^c,o=3395469782);var u=(r<<5|r>>>27)+n+a+o+(0|this.block[e]);a=c,c=s,s=i<<30|i>>>2,i=r,r=u}for(this.h0=this.h0+r|0,this.h1=this.h1+i|0,this.h2=this.h2+s|0,this.h3=this.h3+c|0,this.h4=this.h4+a|0,this.offset=0,e=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":81}],15:[function(e,t,n){var o=e("buffer/").Buffer,r=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]),c=Math.pow(2,53)-1;function a(){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=a,a.BLOCK_SIZE=i,a.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(r.isEmptyData(e))return this;var t=0,n=(e=r.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>c)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},a.prototype.digest=function(e){if(!this.finished){var t=8*this.bytesHashed,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(n.setUint8(this.bufferLength++,128),r%i>=56){for(var s=this.bufferLength;s>>24&255,c[4*s+1]=this.state[s]>>>16&255,c[4*s+2]=this.state[s]>>>8&255,c[4*s+3]=this.state[s]>>>0&255;return e?c.toString(e):c},a.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],o=t[1],r=t[2],c=t[3],a=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=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&u^~a&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&o^n&r^o&r)|0;p=l,l=u,u=a,a=c+m|0,c=r,r=o,o=n,n=m+v|0}t[0]+=n,t[1]+=o,t[2]+=r,t[3]+=c,t[4]+=a,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 o=e("./core");if(t.exports=o,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"),o.XML.Parser=e("./xml/browser_parser"),e("./http/xhr"),void 0===r)var r={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 o,r=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),r.Config=r.util.inherit({constructor:function(e){void 0===e&&(e={}),e=this.extractCredentials(e),r.util.each.call(this,this.keys,(function(t,n){this.set(t,e[t],n)}))},getCredentials:function(e){var t,n=this;function o(t){e(t,t?null:n.credentials)}function i(e,t){return new r.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)),o(e)})):(t=null,n.credentials.accessKeyId&&n.credentials.secretAccessKey||(t=i("Missing credentials")),o(t)):n.credentialProvider?n.credentialProvider.resolve((function(e,t){e&&(e=i("Could not load credentials from any providers",e)),n.credentials=t,o(e)})):o(i("No credentials to load"))},update:function(e,t){t=t||!1,e=this.extractCredentials(e),r.util.each.call(this,e,(function(e,n){(t||Object.prototype.hasOwnProperty.call(this.keys,e)||r.Service.hasService(e))&&this.set(e,n)}))},loadFromPath:function(e){this.clear();var t=JSON.parse(r.util.readFileSync(e)),n=new r.FileSystemCredentials(e),o=new r.CredentialProviderChain;return o.providers.unshift(n),o.resolve((function(e,n){if(e)throw e;t.credentials=n})),this.constructor(t),this},clear:function(){r.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]=r.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=r.util.copy(e)).credentials=new r.Credentials(e)),e},setPromisesDependency:function(e){o=e,null===e&&"function"==typeof Promise&&(o=Promise);var t=[r.Request,r.Credentials,r.CredentialProviderChain];r.S3&&(t.push(r.S3),r.S3.ManagedUpload&&t.push(r.S3.ManagedUpload)),r.util.addPromises(t,o)},getPromisesDependency:function(){return o}}),r.config=new r.Config},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(e,t,n){var o={util:e("./util")};({}).toString(),t.exports=o,o.util.update(o,{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"),o.events=new o.SequentialExecutor,o.util.memoizedProperty(o,"endpointCache",(function(){return new o.EndpointCache(o.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 o=e("./core");o.Credentials=o.util.inherit({constructor:function(){if(o.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"===r(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=o.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){o.util.arrayEach(n.refreshCallbacks,(function(n){t?n(e):o.util.defer((function(){n(e)}))})),n.refreshCallbacks.length=0}))},load:function(e){e()}}),o.Credentials.addPromisesToClass=function(e){this.prototype.getPromise=o.util.promisifyMethod("get",e),this.prototype.refreshPromise=o.util.promisifyMethod("refresh",e)},o.Credentials.deletePromisesFromClass=function(){delete this.prototype.getPromise,delete this.prototype.refreshPromise},o.util.addPromises(o.Credentials)},{"./core":18}],20:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.ChainableTemporaryCredentials=o.util.inherit(o.Credentials,{constructor:function(e){o.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=o.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new o.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}var n=o.util.merge({params:t,credentials:e.masterCredentials||o.config.credentials},e.stsConfig||{});this.service=new r(n)},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this,n=t.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode((function(o,r){var i={};o?e(o):(r&&(i.TokenCode=r),t.service[n](i,(function(n,o){n||t.service.credentialsFrom(o,t),e(n)})))}))},getTokenCode:function(e){var t=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,(function(n,r){if(n){var i=n;return n instanceof Error&&(i=n.message),void e(o.util.error(new Error("Error fetching MFA token: "+i),{code:t.errorCode}))}e(null,r)})):e(null)}})},{"../../clients/sts":8,"../core":18}],21:[function(e,t,n){var o=e("../core"),i=e("../../clients/cognitoidentity"),s=e("../../clients/sts");o.CognitoIdentityCredentials=o.util.inherit(o.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){o.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=o.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||o.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,o){!n&&o.IdentityId?(t.params.IdentityId=o.IdentityId,e(null,o.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,o){n?t.clearIdOnNotAuthorized(n):(t.cacheId(o),t.data=o,t.loadCredentials(t.data,t)),e(n)}))},getCredentialsFromSTS:function(e){var t=this;t.cognito.getOpenIdToken((function(n,o){n?(t.clearIdOnNotAuthorized(n),e(n)):(t.cacheId(o),t.params.WebIdentityToken=o.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(o.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 o.WebIdentityCredentials(this.params,e),!this.cognito){var t=o.util.merge({},e);t.params=this.params,this.cognito=new i(t)}this.sts=this.sts||new s(e)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,o.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=o.util.isBrowser()&&null!==window.localStorage&&"object"===r(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 o=e("../core");o.CredentialProviderChain=o.util.inherit(o.Credentials,{constructor:function(e){this.providers=e||o.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,r=t.providers.slice(0);!function e(i,s){if(!i&&s||n===r.length)return o.util.arrayEach(t.resolveCallbacks,(function(e){e(i,s)})),void(t.resolveCallbacks.length=0);var c=r[n++];(s="function"==typeof c?c.call():c).get?s.get((function(t){e(t,t?null:s)})):e(null,s)}()}return t}}),o.CredentialProviderChain.defaultProviders=[],o.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=o.util.promisifyMethod("resolve",e)},o.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},o.util.addPromises(o.CredentialProviderChain)},{"../core":18}],23:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.SAMLCredentials=o.util.inherit(o.Credentials,{constructor:function(e){o.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithSAML((function(n,o){n||t.service.credentialsFrom(o,t),e(n)}))},createClients:function(){this.service=this.service||new r({params:this.params})}})},{"../../clients/sts":8,"../core":18}],24:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.TemporaryCredentials=o.util.inherit(o.Credentials,{constructor:function(e,t){o.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||o.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,o){n||t.service.credentialsFrom(o,t),e(n)}))}))},loadMasterCredentials:function(e){for(this.masterCredentials=e||o.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new o.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new r({params:this.params})}})},{"../../clients/sts":8,"../core":18}],25:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.WebIdentityCredentials=o.util.inherit(o.Credentials,{constructor:function(e,t){o.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=o.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithWebIdentity((function(n,o){t.data=null,n||(t.data=o,t.service.credentialsFrom(o,t)),e(n)}))},createClients:function(){if(!this.service){var e=o.util.merge({},this._clientConfig);e.params=this.params,this.service=new r(e)}}})},{"../../clients/sts":8,"../core":18}],26:[function(e,t,n){(function(n){(function(){var o=e("./core"),r=e("./util"),i=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function s(e){var t=e.service,n=t.api||{},o=(n.operations,{});return t.config.region&&(o.region=t.config.region),n.serviceId&&(o.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(o.accessKeyId=t.config.credentials.accessKeyId),o}function c(e,t,n){n&&null!=t&&"structure"===n.type&&n.required&&n.required.length>0&&r.arrayEach(n.required,(function(o){var r=n.members[o];if(!0===r.endpointDiscoveryId){var i=r.isLocationName?r.name:o;e[i]=String(t[o])}else c(e,t[o],r)}))}function a(e,t){var n={};return c(n,e.params,t),n}function u(e){var t=e.service,n=t.api,i=n.operations?n.operations[e.operation]:void 0,c=a(e,i?i.input:void 0),u=s(e);Object.keys(c).length>0&&(u=r.update(u,c),i&&(u.operation=i.name));var l=o.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:c});h(p),p.removeListener("validate",o.EventListeners.Core.VALIDATE_PARAMETERS),p.removeListener("retry",o.EventListeners.Core.RETRY_CHECK),o.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}]),p.send((function(e,t){t&&t.Endpoints?o.endpointCache.put(u,t.Endpoints):e&&o.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}])}))}}var l={};function p(e,t){var n=e.service,i=n.api,c=i.operations?i.operations[e.operation]:void 0,u=c?c.input:void 0,p=a(e,u),d=s(e);Object.keys(p).length>0&&(d=r.update(d,p),c&&(d.operation=c.name));var f=o.EndpointCache.getKeyString(d),g=o.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:c.name,Identifiers:p});m.removeListener("validate",o.EventListeners.Core.VALIDATE_PARAMETERS),h(m),o.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=r.error(n,s),o.endpointCache.remove(d),l[f]){var c=l[f];r.arrayEach(c,(function(e){e.request.response.error=r.error(n,s),e.callback()})),delete l[f]}}else i&&(o.endpointCache.put(f,i.Endpoints),e.httpRequest.updateEndpoint(i.Endpoints[0].Address),l[f])&&(c=l[f],r.arrayEach(c,(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,c=i.service.api.operations||{},u=a(i,c[i.operation]?c[i.operation].input:void 0),l=s(i);Object.keys(u).length>0&&(l=r.update(l,u),c[i.operation]&&(l.operation=c[i.operation].name)),o.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 r.error(new Error,{code:"ConfigurationException",message:"Custom endpoint is supplied; endpointDiscoveryEnabled must not be true."});var t=o.config[e.serviceIdentifier]||{};return Boolean(o.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(r.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,o=Math.abs(Math.round(e));n>-1&&o>0;n--,o/=256)t[n]=o;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 o=e("./parse-message").parseMessage;t.exports={parseEvent:function(e,t,n){var r=o(t),i=r.headers[":message-type"];if(i){if("error"===i.value)throw function(e){var t=e.headers[":error-code"],n=e.headers[":error-message"],o=new Error(n.value||n);return o.code=o.name=t.value||t,o}(r);if("event"!==i.value)return}var s=r.headers[":event-type"],c=n.members[s.value];if(c){var a={},u=c.eventPayloadMemberName;if(u){var l=c.members[u];"binary"===l.type?a[u]=r.body:a[u]=e.parse(r.body.toString(),l)}for(var p=c.eventHeaderMemberNames,h=0;h=0)return e.httpRequest.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",t();o.util.computeSha256(i,(function(n,o){n?t(n):(e.httpRequest.headers["X-Amz-Content-Sha256"]=o,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=o.util.getRequestPayloadShape(e);if(void 0===e.httpRequest.headers["Content-Length"])try{var r=o.util.string.byteLength(e.httpRequest.body);e.httpRequest.headers["Content-Length"]=r}catch(o){if(n&&n.isStreaming){if(n.requiresLength)throw o;if(t.indexOf("unsigned-body")>=0)return void(e.httpRequest.headers["Transfer-Encoding"]="chunked");throw o}throw o}})),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 o.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,r){n.httpResponse.statusCode=e,n.httpResponse.statusMessage=r,n.httpResponse.headers=t,n.httpResponse.body=o.util.buffer.toBuffer(""),n.httpResponse.buffers=[],n.httpResponse.numBytes=0;var i=t.date||t.Date,s=n.request.service;if(i){var c=Date.parse(i);s.config.correctClockSkew&&s.isClockSkewed(c)&&s.applyClockOffset(c)}})),e("HTTP_DATA","httpData",(function(e,t){if(e){if(o.util.isNode()){t.httpResponse.numBytes+=e.length;var n=t.httpResponse.headers["content-length"],r={loaded:t.httpResponse.numBytes,total:n};t.request.emit("httpDownloadProgress",[r,t])}t.httpResponse.buffers.push(o.util.buffer.toBuffer(e))}})),e("HTTP_DONE","httpDone",(function(e){if(e.httpResponse.buffers&&e.httpResponse.buffers.length>0){var t=o.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 o.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&&!h&&(u.statusCode=p.status,u.headers=c.parseHeaders(p.getAllResponseHeaders()),u.emit("headers",u.statusCode,u.headers,p.statusText),h=!0),this.readyState===this.DONE&&c.finishRequest(p,u)}),!1),p.upload.addEventListener("progress",(function(e){u.emit("sendProgress",e)})),p.addEventListener("progress",(function(e){u.emit("receiveProgress",e)}),!1),p.addEventListener("timeout",(function(){s(o.util.error(new Error("Timeout"),{code:"TimeoutError"}))}),!1),p.addEventListener("error",(function(){s(o.util.error(new Error("Network Failure"),{code:"NetworkingError"}))}),!1),p.addEventListener("abort",(function(){s(o.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))}),!1),n(u),p.open(e.method,l,!1!==t.xhrAsync),o.util.each(e.headers,(function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&p.setRequestHeader(e,t)})),t.timeout&&!1!==t.xhrAsync&&(p.timeout=t.timeout),t.xhrWithCredentials&&(p.withCredentials=!0);try{p.responseType="arraybuffer"}catch(e){}try{e.body?p.send(e.body):p.send()}catch(t){if(!e.body||"object"!==r(e.body.buffer))throw t;p.send(e.body.buffer)}return u},parseHeaders:function(e){var t={};return o.util.arrayEach(e.split(/\r?\n/),(function(e){var n=e.split(":",1)[0],o=e.substring(n.length+2);n.length>0&&(t[n.toLowerCase()]=o)})),t},finishRequest:function(e,t){var n;if("arraybuffer"===e.responseType&&e.response){var r=e.response;n=new o.util.Buffer(r.byteLength);for(var i=new Uint8Array(r),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 f(){a.apply(this,arguments),this.toType=function(e){var t=i.base64.decode(e);if(this.isSensitive&&i.isNode()&&"function"==typeof i.Buffer.alloc){var n=i.Buffer.alloc(t.length,t);t.fill(0),t=n}return t},this.toWireFormat=i.base64.encode}function g(){f.apply(this,arguments)}function m(){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:l,list:p,map:h,boolean:m,timestamp:function(e){var t=this;if(a.apply(this,arguments),e.timestampFormat)s(this,"timestampFormat",e.timestampFormat);else if(t.isTimestampFormatSet&&this.timestampFormat)s(this,"timestampFormat",this.timestampFormat);else if("header"===this.location)s(this,"timestampFormat","rfc822");else if("querystring"===this.location)s(this,"timestampFormat","iso8601");else if(this.api)switch(this.api.protocol){case"json":case"rest-json":s(this,"timestampFormat","unixTimestamp");break;case"rest-xml":case"query":case"ec2":s(this,"timestampFormat","iso8601")}this.toType=function(e){return null==e?null:"function"==typeof e.toUTCString?e:"string"==typeof e||"number"==typeof e?i.date.parseTimestamp(e):null},this.toWireFormat=function(e){return i.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:g,binary:f},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 o=a.resolve(e,t);if(o){var r=Object.keys(e);t.documentation||(r=r.filter((function(e){return!e.match(/documentation/)})));var i=function(){o.constructor.call(this,e,t,n)};return i.prototype=o,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:l,ListShape:p,MapShape:h,StringShape:d,BooleanShape:m,Base64Shape:g},t.exports=a},{"../util":71,"./collection":39}],44:[function(e,t,n){var o=e("./core");o.ParamValidator=o.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 r=this.errors.join("\n* ");throw r="There were "+this.errors.length+" validation errors:\n* "+r,o.util.error(new Error(r),{code:"MultipleValidationErrors",errors:this.errors})}if(1===this.errors.length)throw this.errors[0];return!0},fail:function(e,t){this.errors.push(o.util.error(new Error(t),{code:e}))},validateStructure:function(e,t,n){var o;this.validateType(t,n,["object"],"structure");for(var r=0;e.required&&r= 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,o){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 "+o+" <= "+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,i){if(null==e)return!1;for(var s=!1,c=0;c63)throw o.error(new Error,{code:"ValidationError",message:"Hostname label length should be between 1 to 63 characters, inclusive."});if(!i.test(e))throw r.util.error(new Error,{code:"ValidationError",message:e+" is not hostname compatible."})}))}return e}}},{"../core":18,"../util":71}],46:[function(e,t,n){var o=e("../util"),r=e("../json/builder"),i=e("../json/parser"),s=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.httpRequest,n=e.service.api,o=n.targetPrefix+"."+n.operations[e.operation].name,i=n.jsonVersion||"1.0",c=n.operations[e.operation].input,a=new r;1===i&&(i="1.0"),t.body=a.build(e.params||{},c),t.headers["Content-Type"]="application/x-amz-json-"+i,t.headers["X-Amz-Target"]=o,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 r=JSON.parse(n.body.toString());(r.__type||r.code)&&(t.code=(r.__type||r.code).split("#").pop()),"RequestEntityTooLarge"===t.code?t.message="Request body must be less than 1 MB":t.message=r.message||r.Message||null}catch(r){t.statusCode=n.statusCode,t.message=n.statusMessage}else t.statusCode=n.statusCode,t.message=n.statusCode.toString();e.error=o.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||{},o=new i;e.data=o.parse(t,n)}}}},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(e,t,n){var o=e("../core"),r=e("../util"),i=e("../query/query_param_serializer"),s=e("../model/shape"),c=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=r.queryParamsToString(n.params),c(e)},extractError:function(e){var t,n=e.httpResponse.body.toString();if(n.match("=0?"&":"?";var a=[];o.arrayEach(Object.keys(s).sort(),(function(e){Array.isArray(s[e])||(s[e]=[s[e]]);for(var t=0;t0){var p=(t=new o.XML.Parser).parse(s.toString(),a);r.update(e.data,p)}}}},{"../core":18,"../util":71,"./rest":48}],51:[function(e,t,n){var o=e("../util");function r(){}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,r){o.each(n.members,(function(n,o){var s=t[n];if(null!=s){var a=i(o);c(a=e?e+"."+a:a,s,o,r)}}))}function c(e,t,n,r){null!=t&&("structure"===n.type?s(e,t,n,r):"list"===n.type?function(e,t,n,r){var s=n.member||{};0!==t.length?o.arrayEach(t,(function(t,o){var a="."+(o+1);if("ec2"===n.api.protocol)a+="";else if(n.flattened){if(s.name){var u=e.split(".");u.pop(),u.push(i(s)),e=u.join(".")}}else a="."+(s.name?s.name:"member")+a;c(e+a,t,s,r)})):r.call(this,e,null)}(e,t,n,r):"map"===n.type?function(e,t,n,r){var i=1;o.each(t,(function(t,o){var s=(n.flattened?".":".entry.")+i+++".",a=s+(n.key.name||"key"),u=s+(n.value.name||"value");c(e+a,t,n.key,r),c(e+u,o,n.value,r)}))}(e,t,n,r):r(e,n.toWireFormat(t).toString()))}r.prototype.serialize=function(e,t,n){s("",e,t,n)},t.exports=r},{"../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 o=e("./util"),r=e("./region_config_data.json");function i(e,t){o.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),o=e.api.endpointPrefix;return[[t,o],[n,o],[t,"*"],[n,"*"],["*",o],["*","*"]].map((function(e){return e[0]&&e[1]?e.join("/"):null}))}(e),n=0;n=0){a=!0;var u=0}var l=function(){a&&u!==c?r.emit("error",n.util.error(new Error("Stream content length mismatch. Received "+u+" of "+c+" bytes."),{code:"StreamContentLengthMismatch"})):2===n.HttpClient.streamsApiVersion?r.end():r.emit("end")},p=s.httpResponse.createUnbufferedStream();if(2===n.HttpClient.streamsApiVersion)if(a){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),r.on("error",(function(e){a=!1,p.unpipe(h),h.emit("end"),h.end()})),p.pipe(h).pipe(r,{end:!1})}else p.pipe(r);else a&&p.on("data",(function(e){e&&e.length&&(u+=e.length)})),p.on("data",(function(e){r.emit("data",e)})),p.on("end",l);p.on("error",(function(e){a=!1,r.emit("error",e)}))}})),r},emitEvent:function(e,t,o){"function"==typeof t&&(o=t,t=null),o||(o=function(){}),t||(t=this.eventParameters(e,this.response)),n.SequentialExecutor.prototype.emit.call(this,e,t,(function(e){e&&(this.response.error=e),o.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 o=e("./core"),r=o.util.inherit,i=e("jmespath");function s(e){var t=e.request._waiter,n=t.config.acceptors,o=!1,r="retry";n.forEach((function(n){if(!o){var i=t.matchers[n.matcher];i&&i(e,n.expected,n.argument)&&(o=!0,r=n.state)}})),!o&&e.error&&(r="failure"),"success"===r?t.setSuccess(e):t.setError(e,"retry"===r)}o.ResourceWaiter=r({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 o=i.search(e.data,n)}catch(e){return!1}return i.strictDeepEqual(o,t)},pathAll:function(e,t,n){try{var o=i.search(e.data,n)}catch(e){return!1}Array.isArray(o)||(o=[o]);var r=o.length;if(!r)return!1;for(var s=0;s-1&&n.splice(r,1)}return this},removeAllListeners:function(e){return e?delete this._events[e]:this._events={},this},emit:function(e,t,n){n||(n=function(){});var o=this.listeners(e),r=o.length;return this.callListeners(o,t,n),r>0},callListeners:function(e,t,n,r){var i=this,s=r||null;function c(r){if(r&&(s=o.util.error(s||new Error,r),i._haltHandlersOnError))return n.call(i,s);i.callListeners(e,t,n,s)}for(;e.length>0;){var a=e.shift();if(a._isAsync)return void a.apply(i,t.concat([c]));try{a.apply(i,t)}catch(e){s=o.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),o.util.each(e,(function(e,n){"function"==typeof n&&(n=[n]),o.util.arrayEach(n,(function(n){t.on(e,n)}))})),t},addNamedListener:function(e,t,n,o){return this[e]=n,this.addListener(t,n,o),this},addNamedAsyncListener:function(e,t,n,o){return n._isAsync=!0,this.addNamedListener(e,t,n,o)},addNamedListeners:function(e){var t=this;return e((function(){t.addNamedListener.apply(t,arguments)}),(function(){t.addNamedAsyncListener.apply(t,arguments)})),this}}),o.SequentialExecutor.prototype.addListener=o.SequentialExecutor.prototype.on,t.exports=o.SequentialExecutor},{"./core":18}],59:[function(e,t,n){(function(n){(function(){var o=e("./core"),i=e("./model/api"),s=e("./region_config"),c=o.util.inherit,a=0;o.Service=c({constructor:function(e){if(!this.loadServiceClass)throw o.util.error(new Error,"Service must be constructed with `new' operator");var t=this.loadServiceClass(e||{});if(t){var n=o.util.copy(e),r=new t(e);return Object.defineProperty(r,"_originalConfig",{get:function(){return n},enumerable:!1,configurable:!0}),r._clientId=++a,r}this.initialize(e)},initialize:function(e){var t=o.config[this.serviceIdentifier];if(this.config=new o.Config(o.config),t&&this.config.update(t,!0),e&&this.config.update(e,!0),this.validateService(),this.config.endpoint||s(this),this.config.endpoint=this.endpointFromTemplate(this.config.endpoint),this.setEndpoint(this.config.endpoint),o.SequentialExecutor.call(this),o.Service.addDefaultMonitoringListeners(this),(this.config.clientSideMonitoring||o.Service._clientSideMonitoring)&&this.publisher){var r=this.publisher;this.addNamedListener("PUBLISH_API_CALL","apiCall",(function(e){n.nextTick((function(){r.eventHandler(e)}))})),this.addNamedListener("PUBLISH_API_ATTEMPT","apiCallAttempt",(function(e){n.nextTick((function(){r.eventHandler(e)}))}))}},validateService:function(){},loadServiceClass:function(e){var t=e;if(o.util.isEmpty(this.api)){if(t.apiConfig)return o.Service.defineServiceApi(this.constructor,t.apiConfig);if(this.constructor.services){(t=new o.Config(o.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]&&o.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?o.util.isType(e,Date)&&(e=o.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,r=t.length-1;r>=0;r--)if("*"!==t[r][t[r].length-1]&&(n=t[r]),t[r].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 '"+r(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 r=this.api.operations[e];r&&(t=o.util.copy(t),o.util.each(this.config.params,(function(e,n){r.input.members[e]&&(void 0!==t[e]&&null!==t[e]||(t[e]=n))})))}var i=new o.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 o=this.makeRequest(e,t).toUnauthenticated();return n?o.send(n):o},waitFor:function(e,t,n){return new o.ResourceWaiter(this,e).wait(t,n)},addAllRequestListeners:function(e){for(var t=[o.events,o.EventListeners.Core,this.serviceInterface(),o.EventListeners.CorePost],n=0;n299?(r.code&&(n.FinalAwsException=r.code),r.message&&(n.FinalAwsExceptionMessage=r.message)):((r.code||r.name)&&(n.FinalSdkException=r.code||r.name),r.message&&(n.FinalSdkExceptionMessage=r.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()},o=e.response;return o.httpResponse.statusCode&&(n.HttpStatusCode=o.httpResponse.statusCode),!e._unAuthenticated&&e.service.config.credentials&&e.service.config.credentials.accessKeyId&&(n.AccessKey=e.service.config.credentials.accessKeyId),o.httpResponse.headers?(e.httpRequest.headers["x-amz-security-token"]&&(n.SessionToken=e.httpRequest.headers["x-amz-security-token"]),o.httpResponse.headers["x-amzn-requestid"]&&(n.XAmznRequestId=o.httpResponse.headers["x-amzn-requestid"]),o.httpResponse.headers["x-amz-request-id"]&&(n.XAmzRequestId=o.httpResponse.headers["x-amz-request-id"]),o.httpResponse.headers["x-amz-id-2"]&&(n.XAmzId2=o.httpResponse.headers["x-amz-id-2"]),n):n},attemptFailEvent:function(e){var t=this.apiAttemptEvent(e),n=e.response,o=n.error;return n.httpResponse.statusCode>299?(o.code&&(t.AwsException=o.code),o.message&&(t.AwsExceptionMessage=o.message)):((o.code||o.name)&&(t.SdkException=o.code||o.name),o.message&&(t.SdkExceptionMessage=o.message)),t},attachMonitoringEmitter:function(e){var t,n,r,i,s,c,a=0,u=this;e.on("validate",(function(){i=o.util.realClock.now(),c=Date.now()}),!0),e.on("sign",(function(){n=o.util.realClock.now(),t=Date.now(),s=e.httpRequest.region,a++}),!0),e.on("validateResponse",(function(){r=Math.round(o.util.realClock.now()-n)})),e.addNamedListener("API_CALL_ATTEMPT","success",(function(){var n=u.apiAttemptEvent(e);n.Timestamp=t,n.AttemptLatency=r>=0?r:0,n.Region=s,u.emit("apiCallAttempt",[n])})),e.addNamedListener("API_CALL_ATTEMPT_RETRY","retry",(function(){var i=u.attemptFailEvent(e);i.Timestamp=t,r=r||Math.round(o.util.realClock.now()-n),i.AttemptLatency=r>=0?r:0,i.Region=s,u.emit("apiCallAttempt",[i])})),e.addNamedListener("API_CALL","complete",(function(){var t=u.apiCallEvent(e);if(t.AttemptCount=a,!(t.AttemptCount<=0)){t.Timestamp=c;var n=Math.round(o.util.realClock.now()-i);t.Latency=n>=0?n:0;var r=e.response;"number"==typeof r.retryCount&&"number"==typeof r.maxRetries&&r.retryCount>=r.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t])}}))},setupRequestListeners:function(e){},getSignerClass:function(e){var t,n=null,r="";return e&&(r=(n=(e.service.api.operations||{})[e.operation]||null)?n.authtype:""),t=this.config.signatureVersion?this.config.signatureVersion:"v4"===r||"v4-unsigned-body"===r?"v4":this.api.signatureVersion,o.Signers.RequestSigner.getVersion(t)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return o.EventListeners.Query;case"json":return o.EventListeners.Json;case"rest-json":return o.EventListeners.RestJson;case"rest-xml":return o.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 o.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 o.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(!n){if(t){var r=new Error;throw o.util.error(r,"No pagination configuration for "+e)}return null}return n}}),o.util.update(o.Service,{defineMethods:function(e){o.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){o.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var r=c(o.Service,n||{});if("string"==typeof e){o.Service.addVersions(r,t);var i=r.serviceIdentifier||e;r.serviceIdentifier=i}else r.prototype.api=e,o.Service.defineMethods(r);if(o.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&o.util.clientSideMonitoring){var s=o.util.clientSideMonitoring.Publisher,a=(0,o.util.clientSideMonitoring.configProvider)();this.prototype.publisher=new s(a),a.enabled&&(o.Service._clientSideMonitoring=!0)}return o.SequentialExecutor.call(r.prototype),o.Service.addDefaultMonitoringListeners(r.prototype),r},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,r)){var o=t.env[r];this.validateRegionalEndpointsFlagValue(o,{code:"InvalidEnvironmentalVariable",message:"invalid "+r+' environmental variable. Expect "legacy" or "regional". Got "'+t.env[r]+'".'})}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 c=s[i];this.validateRegionalEndpointsFlagValue(c,{code:"InvalidConfiguration",message:"invalid "+i+' profile config. Expect "legacy" or "regional". Got "'+s[i]+'".'})}}},optInRegionalEndpoint:function(){this.validateRegionalEndpointsFlag();var e=this.config;if("regional"===e.stsRegionalEndpoints){if(o(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 o=e("../core"),r=o.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===o.Signers.V4){if(t>604800)throw o.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!==o.Signers.S3)throw o.util.error(new Error,{message:"Presigning only supports S3 or SigV4 signing.",code:"UnsupportedSigner",retryable:!1});var r=e.service?e.service.getSkewCorrectedDate():o.util.date.getDate();e.httpRequest.headers[i]=parseInt(o.util.date.unixTimestamp(r)+t,10).toString()}}function c(e){var t=e.httpRequest.endpoint,n=o.util.urlParse(e.httpRequest.path),r={};n.search&&(r=o.util.queryStringParse(n.search.substr(1)));var s=e.httpRequest.headers.Authorization.split(" ");if("AWS"===s[0])s=s[1].split(":"),r.AWSAccessKeyId=s[0],r.Signature=s[1],o.util.each(e.httpRequest.headers,(function(e,t){e===i&&(e="Expires"),0===e.indexOf("x-amz-meta-")&&(delete r[e],e=e.toLowerCase()),r[e]=t})),delete e.httpRequest.headers[i],delete r.Authorization,delete r.Host;else if("AWS4-HMAC-SHA256"===s[0]){s.shift();var c=s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];r["X-Amz-Signature"]=c,delete r.Expires}t.pathname=n.pathname,t.search=o.util.queryParamsToString(r)}o.Signers.Presign=r({sign:function(e,t,n){if(e.httpRequest.headers[i]=t||3600,e.on("build",s),e.on("sign",c),e.removeListener("afterBuild",o.EventListeners.Core.SET_CONTENT_LENGTH),e.removeListener("afterBuild",o.EventListeners.Core.COMPUTE_SHA256),e.emit("beforePresign",[e]),!n){if(e.build(),e.response.error)throw e.response.error;return o.util.urlFormat(e.httpRequest.endpoint)}e.build((function(){this.response.error?n(this.response.error):n(null,o.util.urlFormat(e.httpRequest.endpoint))}))}}),t.exports=o.Signers.Presign},{"../core":18}],63:[function(e,t,n){var o=e("../core"),r=o.util.inherit;o.Signers.RequestSigner=r({constructor:function(e){this.request=e},setServiceClientId:function(e){this.serviceClientId=e},getServiceClientId:function(){return this.serviceClientId}}),o.Signers.RequestSigner.getVersion=function(e){switch(e){case"v2":return o.Signers.V2;case"v3":return o.Signers.V3;case"s3v4":case"v4":return o.Signers.V4;case"s3":return o.Signers.S3;case"v3https":return o.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 o=e("../core"),r=o.util.inherit;o.Signers.S3=r(o.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"]=o.util.date.rfc822(t)),e.sessionToken&&(this.request.headers["x-amz-security-token"]=e.sessionToken);var n=this.sign(e.secretAccessKey,this.stringToSign()),r="AWS "+e.accessKeyId+":"+n;this.request.headers.Authorization=r},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=[];o.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+o.util.queryParamsToString(r)},authorization:function(e,t){var n=[],o=this.credentialString(t);return n.push(this.algorithm+" Credential="+e.accessKeyId+"/"+o),n.push("SignedHeaders="+this.signedHeaders()),n.push("Signature="+this.signature(e,t)),n.join(", ")},signature:function(e,t){var n=r.getSigningKey(e,t.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return o.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=o.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=[];o.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 r[i.shift()]),d},emptyCache:function(){r={},i=[]}}},{"../core":18}],70:[function(e,t,n){function o(e,t){this.currentState=t||null,this.states=e||{}}o.prototype.runTo=function(e,t,n,o){"function"==typeof e&&(o=n,n=t,t=e,e=null);var r=this,i=r.states[r.currentState];i.fn.call(n||r,o,(function(o){if(o){if(!i.fail)return t?t.call(n,o):null;r.currentState=i.fail}else{if(!i.accept)return t?t.call(n):null;r.currentState=i.accept}if(r.currentState===e)return t?t.call(n,o):null;r.runTo(e,t,n,o)}))},o.prototype.addState=function(e,t,n,o){return"function"==typeof t?(o=t,t=null,n=null):"function"==typeof n&&(o=n,n=null),this.currentState||(this.currentState=e),this.states[e]={accept:t,fail:n,fn:o},this},t.exports=o},{}],71:[function(e,t,n){(function(n,o){(function(){var i,s={environment:"nodejs",engine:function(){if(s.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=s.environment,n="aws-sdk-"+t+"/"+e("./core").VERSION;return"nodejs"===t&&(n+=" "+s.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 s.arrayEach(e.split("/"),(function(e){t.push(s.uriEscape(e))})),t.join("/")},urlParse:function(e){return s.url.parse(e)},urlFormat:function(e){return s.url.format(e)},queryStringParse:function(e){return s.querystring.parse(e)},queryParamsToString:function(e){var t=[],n=s.uriEscape,o=Object.keys(e).sort();return s.arrayEach(o,(function(o){var r=e[o],i=n(o),c=i+"=";if(Array.isArray(r)){var a=[];s.arrayEach(r,(function(e){a.push(n(e))})),c=i+"="+a.sort().join("&"+i+"=")}else null!=r&&(c=i+"="+n(r));t.push(c)})),t.join("&")},readFileSync:function(t){return s.isBrowser()?null:e("fs").readFileSync(t,"utf-8")},base64:{encode:function(e){if("number"==typeof e)throw s.error(new Error("Cannot base64 encode number "+e));return null==e?e:s.buffer.toBuffer(e).toString("base64")},decode:function(e){if("number"==typeof e)throw s.error(new Error("Cannot base64 decode number "+e));return null==e?e:s.buffer.toBuffer(e,"base64")}},buffer:{toBuffer:function(e,t){return"function"==typeof s.Buffer.from&&s.Buffer.from!==Uint8Array.from?s.Buffer.from(e,t):new s.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 s.Buffer.alloc)return s.Buffer.alloc(e,t,n);var o=new s.Buffer(e);return void 0!==t&&"function"==typeof o.fill&&o.fill(t,void 0,void 0,n),o},toStream:function(e){s.Buffer.isBuffer(e)||(e=s.buffer.toBuffer(e));var t=new s.stream.Readable,n=0;return t._read=function(o){if(n>=e.length)return t.push(null);var r=n+o;r>e.length&&(r=e.length),t.push(e.slice(n,r)),n=r},t},concat:function(e){var t,n,o=0,r=0;for(n=0;n>>8^t[255&(n^e.readUInt8(o))];return(-1^n)>>>0},hmac:function(e,t,n,o){return n||(n="binary"),"buffer"===n&&(n=void 0),o||(o="sha256"),"string"==typeof t&&(t=s.buffer.toBuffer(t)),s.crypto.lib.createHmac(o,e).update(t).digest(n)},md5:function(e,t,n){return s.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return s.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,o){var i=s.crypto.createHash(e);n||(n="binary"),"buffer"===n&&(n=void 0),"string"==typeof t&&(t=s.buffer.toBuffer(t));var c=s.arraySliceFn(t),a=s.Buffer.isBuffer(t);if(s.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(a=!0),o&&"object"===r(t)&&"function"==typeof t.on&&!a)t.on("data",(function(e){i.update(e)})),t.on("error",(function(e){o(e)})),t.on("end",(function(){o(null,i.digest(n))}));else{if(!o||!c||a||"undefined"==typeof FileReader){s.isBrowser()&&"object"===r(t)&&!a&&(t=new s.Buffer(new Uint8Array(t)));var u=i.update(t).digest(n);return o&&o(null,u),u}var l=0,p=new FileReader;p.onerror=function(){o(new Error("Failed to read data."))},p.onload=function(){var e=new s.Buffer(new Uint8Array(p.result));i.update(e),l+=e.length,p._continueReading()},p._continueReading=function(){if(l>=t.size)o(null,i.digest(n));else{var e=l+524288;e>t.size&&(e=t.size),p.readAsArrayBuffer(c.call(t,l,e))}},p._continueReading()}},toHex:function(e){for(var t=[],n=0;n=3e5,!1),i.config.isClockSkewed},applyClockOffset:function(e){e&&(i.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&&i&&i.config&&(t=i.config.getPromisesDependency()),void 0===t&&"undefined"!=typeof Promise&&(t=Promise),"function"!=typeof t&&(n=!0),Array.isArray(e)||(e=[e]);for(var o=0;o=500||429===o});r&&i.retryable&&(i.retryAfter=r),a(i)}}))}),a)};i.util.defer(u)},uuid:{v4:function(){return e("uuid").v4()}},convertPayloadToString:function(e){var t=e.request,n=t.operation,o=t.service.api.operations[n].output||{};o.payload&&e.data[o.payload]&&(e.data[o.payload]=e.data[o.payload].toString())},defer:function(e){"object"===r(n)&&"function"==typeof n.nextTick?n.nextTick(e):"function"==typeof o?o(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 o={},r={};n.env[s.configOptInEnv]&&(r=e.loadFrom({isConfig:!0,filename:n.env[s.sharedConfigFileEnv]}));for(var i=e.loadFrom({filename:t||n.env[s.configOptInEnv]&&n.env[s.sharedCredentialsFileEnv]}),c=0,a=Object.keys(r);c0||o?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 o=e("./escape-attribute").escapeAttribute;function r(e,t){void 0===t&&(t=[]),this.name=e,this.children=t,this.attributes={}}r.prototype.addAttribute=function(e,t){return this.attributes[e]=t,this},r.prototype.addChildNode=function(e){return this.children.push(e),this},r.prototype.removeAttribute=function(e){return delete this.attributes[e],this},r.prototype.toString=function(){for(var e=Boolean(this.children.length),t="<"+this.name,n=this.attributes,r=0,i=Object.keys(n);r"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},t.exports={XmlNode:r}},{"./escape-attribute":74}],77:[function(e,t,n){var o=e("./escape-element").escapeElement;function r(e){this.value=e}r.prototype.toString=function(){return o(""+this.value)},t.exports={XmlText:r}},{"./escape-element":75}],78:[function(e,t,n){"use strict";n.byteLength=function(e){var t=a(e),n=t[0],o=t[1];return 3*(n+o)/4-o},n.toByteArray=function(e){var t,n,o=a(e),s=o[0],c=o[1],u=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,c)),l=0,p=c>0?s-4:s;for(n=0;n>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===c&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,u[l++]=255&t),1===c&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i=[],s=16383,c=0,a=n-r;ca?a:c+s));return 1===r?(t=e[n-1],i.push(o[t>>2]+o[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(o[t>>10]+o[t>>4&63]+o[t<<2&63]+"=")),i.join("")};for(var o=[],r=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0;c<64;++c)o[c]=s[c],r[s.charCodeAt(c)]=c;function a(e){var t=e.length;if(t%4>0)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 u(e,t,n){for(var r,i,s=[],c=t;c>18&63]+o[i>>12&63]+o[i>>6&63]+o[63&i]);return s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],79:[function(e,t,n){},{}],80:[function(e,t,i){(function(e){(function(){!function(s){var c="object"==r(i)&&i&&!i.nodeType&&i,a="object"==r(t)&&t&&!t.nodeType&&t,u="object"==r(e)&&e;u.global!==u&&u.window!==u&&u.self!==u||(s=u);var l,p,h=2147483647,d=36,f=1,g=26,m=38,v=700,y=72,E=128,S="-",b=/^xn--/,C=/[^\x20-\x7E]/,T=/[\x2E\u3002\uFF0E\uFF61]/g,I={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},A=d-f,_=Math.floor,w=String.fromCharCode;function R(e){throw RangeError(I[e])}function N(e,t){for(var n=e.length,o=[];n--;)o[n]=t(e[n]);return o}function k(e,t){var n=e.split("@"),o="";return n.length>1&&(o=n[0]+"@",e=n[1]),o+N((e=e.replace(T,".")).split("."),t).join(".")}function O(e){for(var t,n,o=[],r=0,i=e.length;r=55296&&t<=56319&&r65535&&(t+=w((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=w(e)})).join("")}function D(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function P(e,t,n){var o=0;for(e=n?_(e/v):e>>1,e+=_(e/t);e>A*g>>1;o+=d)e=_(e/A);return _(o+(A+1)*e/(e+m))}function x(e){var t,n,o,r,i,s,c,a,u,l,p,m=[],v=e.length,b=0,C=E,T=y;for((n=e.lastIndexOf(S))<0&&(n=0),o=0;o=128&&R("not-basic"),m.push(e.charCodeAt(o));for(r=n>0?n+1:0;r=v&&R("invalid-input"),((a=(p=e.charCodeAt(r++))-48<10?p-22:p-65<26?p-65:p-97<26?p-97:d)>=d||a>_((h-b)/s))&&R("overflow"),b+=a*s,!(a<(u=c<=T?f:c>=T+g?g:c-T));c+=d)s>_(h/(l=d-u))&&R("overflow"),s*=l;T=P(b-i,t=m.length+1,0==i),_(b/t)>h-C&&R("overflow"),C+=_(b/t),b%=t,m.splice(b++,0,C)}return L(m)}function M(e){var t,n,o,r,i,s,c,a,u,l,p,m,v,b,C,T=[];for(m=(e=O(e)).length,t=E,n=0,i=y,s=0;s=t&&p_((h-n)/(v=o+1))&&R("overflow"),n+=(c-t)*v,t=c,s=0;sh&&R("overflow"),p==t){for(a=n,u=d;!(a<(l=u<=i?f:u>=i+g?g:u-i));u+=d)C=a-l,b=d-l,T.push(w(D(l+C%b,0))),a=_(C/b);T.push(w(D(a,0))),i=P(n,v,o==r),n=0,++o}++n,++t}return T.join("")}if(l={version:"1.3.2",ucs2:{decode:O,encode:L},decode:x,encode:M,toASCII:function(e){return k(e,(function(e){return C.test(e)?"xn--"+M(e):e}))},toUnicode:function(e){return k(e,(function(e){return b.test(e)?x(e.slice(4).toLowerCase()):e}))}},"object"==r(n.amdO)&&n.amdO)void 0===(o=function(){return l}.call(i,n,i,t))||(t.exports=o);else if(c&&a)if(t.exports==c)a.exports=l;else for(p in l)l.hasOwnProperty(p)&&(c[p]=l[p]);else s.punycode=l}(this)}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(e,t,o){(function(t,n){(function(){"use strict";var n=e("base64-js"),r=e("ieee754"),i=e("isarray");function s(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function c(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(a.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 o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return B(e).length;default:if(o)return j(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,n){var o=!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 _(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function m(e,t,n){var o=e[t];e[t]=e[n],e[n]=o}function v(e,t,n,o,r){if(0===e.length)return-1;if("string"==typeof n?(o=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=a.from(t,o)),a.isBuffer(t))return 0===t.length?-1:y(e,t,n,o,r);if("number"==typeof t)return t&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,o,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,o,r){var i,s=1,c=e.length,a=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;s=2,c/=2,a/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var l=-1;for(i=n;ic&&(n=c-a),i=n;i>=0;i--){for(var p=!0,h=0;hr&&(o=r):o=r;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");o>i/2&&(o=i/2);for(var s=0;s>8,r=n%256,i.push(r),i.push(o);return i}(t,e.length-n),e,n,o)}function A(e,t,o){return 0===t&&o===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,o))}function _(e,t,n){n=Math.min(e.length,n);for(var o=[],r=t;r239?4:u>223?3:u>191?2:1;if(r+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[r+1]))&&(a=(31&u)<<6|63&i)>127&&(l=a);break;case 3:i=e[r+1],s=e[r+2],128==(192&i)&&128==(192&s)&&(a=(15&u)<<12|(63&i)<<6|63&s)>2047&&(a<55296||a>57343)&&(l=a);break;case 4:i=e[r+1],s=e[r+2],c=e[r+3],128==(192&i)&&128==(192&s)&&128==(192&c)&&(a=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&c)>65535&&a<1114112&&(l=a)}null===l?(l=65533,p=1):l>65535&&(l-=65536,o.push(l>>>10&1023|55296),l=56320|1023&l),o.push(l),r+=p}return function(e){var t=e.length;if(t<=w)return String.fromCharCode.apply(String,e);for(var n="",o=0;o0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,o,r){if(!a.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===o&&(o=0),void 0===r&&(r=this.length),t<0||n>e.length||o<0||r>this.length)throw new RangeError("out of range index");if(o>=r&&t>=n)return 0;if(o>=r)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(r>>>=0)-(o>>>=0),s=(n>>>=0)-(t>>>=0),c=Math.min(i,s),u=this.slice(o,r),l=e.slice(t,n),p=0;pr)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");for(var i=!1;;)switch(o){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: "+o);o=(""+o).toLowerCase(),i=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var w=4096;function R(e,t,n){var o="";n=Math.min(e.length,n);for(var r=t;rr)&&(n=r);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,o,r,i){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function P(e,t,n,o){t<0&&(t=65535+t+1);for(var r=0,i=Math.min(e.length-n,2);r>>8*(o?r:1-r)}function x(e,t,n,o){t<0&&(t=4294967295+t+1);for(var r=0,i=Math.min(e.length-n,4);r>>8*(o?r:3-r)&255}function M(e,t,n,o,r,i){if(n+o>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,o,i){return i||M(e,0,n,4),r.write(e,t,n,o,23,4),n+4}function q(e,t,n,o,i){return i||M(e,0,n,8),r.write(e,t,n,o,52,8),n+8}a.prototype.slice=function(e,t){var n,o=this.length;if((e=~~e)<0?(e+=o)<0&&(e=0):e>o&&(e=o),(t=void 0===t?o:~~t)<0?(t+=o)<0&&(t=0):t>o&&(t=o),t0&&(r*=256);)o+=this[e+--t]*r;return o},a.prototype.readUInt8=function(e,t){return t||L(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||L(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||L(e,2,this.length),this[e]<<8|this[e+1]},a.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]},a.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])},a.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var o=this[e],r=1,i=0;++i=(r*=128)&&(o-=Math.pow(2,8*t)),o},a.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var o=t,r=1,i=this[e+--o];o>0&&(r*=256);)i+=this[e+--o]*r;return i>=(r*=128)&&(i-=Math.pow(2,8*t)),i},a.prototype.readInt8=function(e,t){return t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.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},a.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},a.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},a.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]},a.prototype.readFloatLE=function(e,t){return t||L(e,4,this.length),r.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||L(e,4,this.length),r.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||L(e,8,this.length),r.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||L(e,8,this.length),r.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,o){e=+e,t|=0,n|=0,o||D(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+r]=e/i&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),a.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},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),a.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},a.prototype.writeIntLE=function(e,t,n,o){if(e=+e,t|=0,!o){var r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}var i=0,s=1,c=0;for(this[t]=255&e;++i>0)-c&255;return t+n},a.prototype.writeIntBE=function(e,t,n,o){if(e=+e,t|=0,!o){var r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}var i=n-1,s=1,c=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===c&&0!==this[t+i+1]&&(c=1),this[t+i]=(e/s>>0)-c&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),a.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},a.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),a.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},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return q(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return q(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,o){if(n||(n=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o=this.length)throw new RangeError("sourceStart out of bounds");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t=0;--r)e[r+t]=this[r+n];else if(i<1e3||!a.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===o){(t-=3)>-1&&i.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&i.push(239,191,189);if(r=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 B(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,o){for(var r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}}).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 o(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function s(e){return"object"===r(e)&&null!==e}function c(e){return void 0===e}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.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},o.prototype.emit=function(e){var t,n,o,r,a,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||s(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(c(n=this._events[e]))return!1;if(i(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:r=Array.prototype.slice.call(arguments,1),n.apply(this,r)}else if(s(n))for(r=Array.prototype.slice.call(arguments,1),o=(u=n.slice()).length,a=0;a0&&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},o.prototype.on=o.prototype.addListener,o.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var n=!1;function o(){this.removeListener(e,o),n||(n=!0,t.apply(this,arguments))}return o.listener=t,this.on(e,o),this},o.prototype.removeListener=function(e,t){var n,o,r,c;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=(n=this._events[e]).length,o=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(n)){for(c=r;c-- >0;)if(n[c]===t||n[c].listener&&n[c].listener===t){o=c;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},o.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(i(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},o.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},o.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},o.listenerCount=function(e,t){return e.listenerCount(t)}},{}],83:[function(e,t,n){n.read=function(e,t,n,o,r){var i,s,c=8*r-o-1,a=(1<>1,l=-7,p=n?r-1:0,h=n?-1:1,d=e[t+p];for(p+=h,i=d&(1<<-l)-1,d>>=-l,l+=c;l>0;i=256*i+e[t+p],p+=h,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=o;l>0;s=256*s+e[t+p],p+=h,l-=8);if(0===i)i=1-u;else{if(i===a)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,o),i-=u}return(d?-1:1)*s*Math.pow(2,i-o)},n.write=function(e,t,n,o,r,i){var s,c,a,u=8*i-r-1,l=(1<>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,d=o?0:i-1,f=o?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-s))<1&&(s--,a*=2),(t+=s+p>=1?h/a:h*Math.pow(2,1-p))*a>=2&&(s++,a/=2),s+p>=l?(c=0,s=l):s+p>=1?(c=(t*a-1)*Math.pow(2,r),s+=p):(c=t*Math.pow(2,p-1)*Math.pow(2,r),s=0));r>=8;e[n+d]=255&c,d+=f,c/=256,r-=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 o={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==o.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 o(e,r){if(e===r)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(r))return!1;if(!0===t(e)){if(e.length!==r.length)return!1;for(var i=0;i":!0,"=":!0,"!":!0},G={" ":!0,"\t":!0,"\n":!0};function z(e){return e>="0"&&e<="9"||"-"===e}function K(){}K.prototype={tokenize:function(e){var t,n,o,r,i=[];for(this._current=0;this._current="a"&&r<="z"||r>="A"&&r<="Z"||"_"===r)t=this._current,n=this._consumeUnquotedIdentifier(e),i.push({type:g,value:n,start:t});else if(void 0!==H[e[this._current]])i.push({type:H[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(z(e[this._current]))o=this._consumeNumber(e),i.push(o);else if("["===e[this._current])o=this._consumeLBracket(e),i.push(o);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),i.push({type:m,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),i.push({type:V,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);i.push({type:V,value:s,start:t})}else if(void 0!==W[e[this._current]])i.push(this._consumeOperator(e));else if(void 0!==G[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,i.push({type:w,value:"&&",start:t})):i.push({type:I,value:"&",start:t});else{if("|"!==e[this._current]){var c=new Error("Unknown character:"+e[this._current]);throw c.name="LexerError",c}t=this._current,this._current++,"|"===e[this._current]?(this._current++,i.push({type:_,value:"||",start:t})):i.push({type:A,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:O,value:">=",start:t}):{type:N,value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:R,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,n=this._current,o=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 Y={};function X(){}function J(e){this.runtime=e}function Q(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[s]}]},avg:{_func:this._functionAvg,_signature:[{types:[h]}]},ceil:{_func:this._functionCeil,_signature:[{types:[s]}]},contains:{_func:this._functionContains,_signature:[{types:[a,u]},{types:[c]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[a]},{types:[a]}]},floor:{_func:this._functionFloor,_signature:[{types:[s]}]},length:{_func:this._functionLength,_signature:[{types:[a,u,l]}]},map:{_func:this._functionMap,_signature:[{types:[p]},{types:[u]}]},max:{_func:this._functionMax,_signature:[{types:[h,d]}]},merge:{_func:this._functionMerge,_signature:[{types:[l],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[u]},{types:[p]}]},sum:{_func:this._functionSum,_signature:[{types:[h]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[a]},{types:[a]}]},min:{_func:this._functionMin,_signature:[{types:[h,d]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[u]},{types:[p]}]},type:{_func:this._functionType,_signature:[{types:[c]}]},keys:{_func:this._functionKeys,_signature:[{types:[l]}]},values:{_func:this._functionValues,_signature:[{types:[l]}]},sort:{_func:this._functionSort,_signature:[{types:[d,h]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[u]},{types:[p]}]},join:{_func:this._functionJoin,_signature:[{types:[a]},{types:[d]}]},reverse:{_func:this._functionReverse,_signature:[{types:[a,u]}]},to_array:{_func:this._functionToArray,_signature:[{types:[c]}]},to_string:{_func:this._functionToString,_signature:[{types:[c]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[c]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[c],variadic:!0}]}}}Y[f]=0,Y[g]=0,Y[m]=0,Y[v]=0,Y[y]=0,Y[E]=0,Y[b]=0,Y[C]=0,Y[T]=0,Y[I]=0,Y[A]=1,Y[_]=2,Y[w]=3,Y[R]=5,Y[N]=5,Y[k]=5,Y[O]=5,Y[L]=5,Y[D]=5,Y[P]=9,Y[x]=20,Y[M]=21,Y[U]=40,Y[q]=45,Y[F]=50,Y[j]=55,Y[B]=60,X.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)!==f){var n=this._lookaheadToken(0),o=new Error("Unexpected token type: "+n.type+", value: "+n.value);throw o.name="ParserError",o}return t},_loadTokens:function(e){var t=(new K).tokenize(e);t.push({type:f,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),o=this._lookahead(0);e=0?this.expression(e):t===j?(this._match(j),this._parseMultiselectList()):t===F?(this._match(F),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(Y[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===j)t=this.expression(e);else if(this._lookahead(0)===M)t=this.expression(e);else{if(this._lookahead(0)!==U){var n=this._lookaheadToken(0),o=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw o.name="ParserError",o}this._match(U),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==v;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===E&&(this._match(E),this._lookahead(0)===v))throw new Error("Unexpected token Rbracket")}return this._match(v),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,n,o=[],r=[g,m];;){if(e=this._lookaheadToken(0),r.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(S),n={type:"KeyValuePair",name:t,value:this.expression(0)},o.push(n),this._lookahead(0)===E)this._match(E);else if(this._lookahead(0)===b){this._match(b);break}}return{type:"MultiSelectHash",children:o}}},J.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,i){var s,c,a,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(a=this.visit(e.children[0],i),f=1;f0)for(f=y;fE;f+=S)a.push(i[f]);return a;case"Projection":var b=this.visit(e.children[0],i);if(!t(b))return null;for(d=[],f=0;fl;break;case O:a=u>=l;break;case k:a=u=e&&(t=n<0?e-1:e),t}},Q.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 o,r,i,s;if(n[n.length-1].variadic){if(t.length=0;o--)n+=t[o];return n}var r=e[0].slice(0);return r.reverse(),r},_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],o=0;o=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,o=e[0],r=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],o=1;o0){if(this._getTypeName(e[0][0])===s)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],o=1;oc?1:sc&&(c=n,t=r[u]);return t},_functionMinBy:function(e){for(var t,n,o=e[1],r=e[0],i=this.createKeyFunction(o,[s,a]),c=1/0,u=0;u1)for(var n=1;n0&&u>a&&(u=a);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),o(s,d)?r(s[d])?s[d].push(f):s[d]=[s[d],f]:s[d]=f}return s};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],88:[function(e,t,n){"use strict";var o=function(e){switch(r(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"===r(e)?s(c(e),(function(r){var c=encodeURIComponent(o(r))+n;return i(e[r])?s(e[r],(function(e){return c+encodeURIComponent(o(e))})).join(t):c+encodeURIComponent(o(e[r]))})).join(t):a?encodeURIComponent(o(a))+n+encodeURIComponent(o(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],o=0;o0&&a>c&&(a=c);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),o(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 o=function(e){switch(r(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,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"===r(e)?Object.keys(e).map((function(r){var i=encodeURIComponent(o(r))+n;return Array.isArray(e[r])?e[r].map((function(e){return i+encodeURIComponent(o(e))})).join(t):i+encodeURIComponent(o(e[r]))})).join(t):i?encodeURIComponent(o(i))+n+encodeURIComponent(o(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,o){(function(){var r=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,c={},a=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=a++,o=!(arguments.length<2)&&s.call(arguments,1);return c[t]=!0,r((function(){c[t]&&(o?e.apply(null,o):e.call(null),n.clearImmediate(t))})),t},n.clearImmediate="function"==typeof o?o:function(e){delete c[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":86,timers:93}],94:[function(e,t,n){var o=e("punycode");function i(){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=y,n.resolve=function(e,t){return y(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?y(e,!1,!0).resolveObject(t):t},n.format=function(e){return E(e)&&(e=y(e)),e instanceof i?e.format():i.prototype.format.call(e)},n.Url=i;var s=/^([a-z0-9.+-]+:)/i,c=/:[0-9]*$/,a=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(a),l=["%","/","?",";","#"].concat(u),p=["/","?","#"],h=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,f={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function y(e,t,n){if(e&&S(e)&&e instanceof i)return e;var o=new i;return o.parse(e,t,n),o}function E(e){return"string"==typeof e}function S(e){return"object"===r(e)&&null!==e}function b(e){return null===e}i.prototype.parse=function(e,t,n){if(!E(e))throw new TypeError("Parameter 'url' must be a string, not "+r(e));var i=e;i=i.trim();var c=s.exec(i);if(c){var a=(c=c[0]).toLowerCase();this.protocol=a,i=i.substr(c.length)}if(n||c||i.match(/^\/\/[^@\/]+@[^@\/]+/)){var y="//"===i.substr(0,2);!y||c&&g[c]||(i=i.substr(2),this.slashes=!0)}if(!g[c]&&(y||c&&!m[c])){for(var S,b,C=-1,T=0;T127?N+="x":N+=R[k];if(!N.match(h)){var L=_.slice(0,T),D=_.slice(T+1),P=R.match(d);P&&(L.push(P[1]),D.unshift(P[2])),D.length&&(i="/"+D.join(".")+i),this.hostname=L.join(".");break}}}if(this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),!A){var x=this.hostname.split("."),M=[];for(T=0;T0)&&n.host.split("@"))&&(n.auth=S.shift(),n.host=n.hostname=S.shift())),n.search=e.search,n.query=e.query,b(n.pathname)&&b(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],f=(n.host||e.host)&&("."===d||".."===d)||""===d,v=0,y=p.length;y>=0;y--)"."==(d=p[y])?p.splice(y,1):".."===d?(p.splice(y,1),v++):v&&(p.splice(y,1),v--);if(!u&&!l)for(;v--;v)p.unshift("..");!u||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),f&&"/"!==p.join("/").substr(-1)&&p.push("");var S,C=""===p[0]||p[0]&&"/"===p[0].charAt(0);return h&&(n.hostname=n.host=C?"":p.length?p.shift():"",(S=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=S.shift(),n.host=n.hostname=S.shift())),(u=u||n.host&&p.length)&&!C&&p.unshift(""),p.length?n.pathname=p.join("/"):(n.pathname=null,n.path=null),b(n.pathname)&&b(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},i.prototype.parseHost=function(){var e=this.host,t=c.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"===r(e)&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],97:[function(e,t,o){(function(t,n){(function(){var i=/%[sdj%]/g;o.format=function(e){if(!y(e)){for(var t=[],n=0;n=r)return e;switch(e){case"%s":return String(o[n++]);case"%d":return Number(o[n++]);case"%j":try{return JSON.stringify(o[n++])}catch(e){return"[Circular]"}default:return e}})),c=o[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&o._extend(n,t),E(n.showHidden)&&(n.showHidden=!1),E(n.depth)&&(n.depth=2),E(n.colors)&&(n.colors=!1),E(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),p(n,e,n.depth)}function u(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function l(e,t){return e}function p(e,t,n){if(e.customInspect&&t&&I(t.inspect)&&t.inspect!==o.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(n,e);return y(r)||(r=p(e,r,n)),r}var i=function(e,t){if(E(t))return e.stylize("undefined","undefined");if(y(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return v(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):m(t)?e.stylize("null","null"):void 0}(e,t);if(i)return i;var s=Object.keys(t),c=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),T(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return h(t);if(0===s.length){if(I(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(S(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(C(t))return e.stylize(Date.prototype.toString.call(t),"date");if(T(t))return h(t)}var u,l="",b=!1,A=["{","}"];return f(t)&&(b=!0,A=["[","]"]),I(t)&&(l=" [Function"+(t.name?": "+t.name:"")+"]"),S(t)&&(l=" "+RegExp.prototype.toString.call(t)),C(t)&&(l=" "+Date.prototype.toUTCString.call(t)),T(t)&&(l=" "+h(t)),0!==s.length||b&&0!=t.length?n<0?S(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=b?function(e,t,n,o,r){for(var i=[],s=0,c=t.length;s60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(u,l,A)):A[0]+l+A[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,o,r,i){var s,c,a;if((a=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?c=a.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):a.set&&(c=e.stylize("[Setter]","special")),R(o,r)||(s="["+r+"]"),c||(e.seen.indexOf(a.value)<0?(c=m(n)?p(e,a.value,null):p(e,a.value,n-1)).indexOf("\n")>-1&&(c=i?c.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+c.split("\n").map((function(e){return" "+e})).join("\n")):c=e.stylize("[Circular]","special")),E(s)){if(i&&r.match(/^\d+$/))return c;(s=JSON.stringify(""+r)).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+": "+c}function f(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function m(e){return null===e}function v(e){return"number"==typeof e}function y(e){return"string"==typeof e}function E(e){return void 0===e}function S(e){return b(e)&&"[object RegExp]"===A(e)}function b(e){return"object"===r(e)&&null!==e}function C(e){return b(e)&&"[object Date]"===A(e)}function T(e){return b(e)&&("[object Error]"===A(e)||e instanceof Error)}function I(e){return"function"==typeof e}function A(e){return Object.prototype.toString.call(e)}function _(e){return e<10?"0"+e.toString(10):e.toString(10)}o.debuglog=function(e){if(E(s)&&(s=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!c[e])if(new RegExp("\\b"+e+"\\b","i").test(s)){var n=t.pid;c[e]=function(){var t=o.format.apply(o,arguments);console.error("%s %d: %s",e,n,t)}}else c[e]=function(){};return c[e]},o.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"},o.isArray=f,o.isBoolean=g,o.isNull=m,o.isNullOrUndefined=function(e){return null==e},o.isNumber=v,o.isString=y,o.isSymbol=function(e){return"symbol"===r(e)},o.isUndefined=E,o.isRegExp=S,o.isObject=b,o.isDate=C,o.isError=T,o.isFunction=I,o.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"===r(e)||void 0===e},o.isBuffer=e("./support/isBuffer");var w=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}o.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[_(e.getHours()),_(e.getMinutes()),_(e.getSeconds())].join(":"),[e.getDate(),w[e.getMonth()],t].join(" ")),o.format.apply(o,arguments))},o.inherits=e("inherits"),o._extend=function(e,t){if(!t||!b(t))return e;for(var n=Object.keys(t),o=n.length;o--;)e[n[o]]=t[n[o]];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 o=e("./v1"),r=e("./v4"),i=r;i.v1=o,i.v4=r,t.exports=i},{"./v1":101,"./v4":102}],99:[function(e,t,n){for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);t.exports=function(e,t){var n=t||0,r=o;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")}},{}],100:[function(e,t,n){var o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(o){var r=new Uint8Array(16);t.exports=function(){return o(r),r}}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 o,r,i=e("./lib/rng"),s=e("./lib/bytesToUuid"),c=0,a=0;t.exports=function(e,t,n){var u=t&&n||0,l=t||[],p=(e=e||{}).node||o,h=void 0!==e.clockseq?e.clockseq:r;if(null==p||null==h){var d=i();null==p&&(p=o=[1|d[0],d[1],d[2],d[3],d[4],d[5]]),null==h&&(h=r=16383&(d[6]<<8|d[7]))}var f=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:a+1,m=f-c+(g-a)/1e4;if(m<0&&void 0===e.clockseq&&(h=h+1&16383),(m<0||f>c)&&void 0===e.nsecs&&(g=0),g>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,a=g,r=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 o=e("./lib/rng"),r=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||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var c=0;c<16;++c)t[i+c]=s[c];return t||r(s)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o=e("./utils/LRU"),r=function(){function e(e){void 0===e&&(e=1e3),this.maxSize=e,this.cache=new o.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 o="string"!=typeof t?e.getKeyString(t):t,r=this.populateValue(n);this.cache.put(o,r)},e.prototype.get=function(t){var n="string"!=typeof t?e.getKeyString(t):t,o=Date.now(),r=this.cache.get(n);if(r)for(var i=0;i{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect,connect.ClientMethods=connect.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"]),connect.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"},connect.MasterMethods=connect.makeEnum(["becomeMaster","checkMaster"]);var t=function(){};t.EMPTY_CALLBACKS={success:function(){},failure:function(){}},t.prototype.call=function(e,n,o){connect.assertNotNull(e,"method");var r=n||{},i=o||t.EMPTY_CALLBACKS;this._callImpl(e,r,i)},t.prototype._callImpl=function(e,t,n){throw new connect.NotImplementedError};var n=function(){t.call(this)};(n.prototype=Object.create(t.prototype)).constructor=n,n.prototype._callImpl=function(e,t,n){if(n&&n.failure){var o=connect.sprintf("No such method exists on NULL client: %s",e);n.failure(new connect.ValueError(o),{message:o})}};var o=function(e,n,o){t.call(this),this.conduit=e,this.requestEvent=n,this.responseEvent=o,this._requestIdCallbacksMap={},this.conduit.onUpstream(o,connect.hitch(this,this._handleResponse))};(o.prototype=Object.create(t.prototype)).constructor=o,o.prototype._callImpl=function(e,t,n){var o=connect.EventFactory.createRequest(this.requestEvent,e,t);this._requestIdCallbacksMap[o.requestId]=n,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 r=function(e){o.call(this,e,connect.EventType.API_REQUEST,connect.EventType.API_RESPONSE)};(r.prototype=Object.create(o.prototype)).constructor=r;var i=function(e){o.call(this,e,connect.EventType.MASTER_REQUEST,connect.EventType.MASTER_RESPONSE)};(i.prototype=Object.create(o.prototype)).constructor=i;var s=function(e,n,o){connect.assertNotNull(e,"authCookieName"),connect.assertNotNull(n,"authToken"),connect.assertNotNull(o,"endpoint"),t.call(this),this.endpointUrl=connect.getUrlWithProtocol(o),this.authToken=n,this.authCookieName=e};(s.prototype=Object.create(t.prototype)).constructor=s,s.prototype._callImpl=function(e,t,n){var o=this,r={};r[o.authCookieName]=o.authToken;var i={method:"post",body:JSON.stringify(t||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(r)}};connect.fetch(o.endpointUrl,i).then((function(e){n.success(e)})).catch((function(e){var t=e.body.getReader(),o="",r=new TextDecoder;t.read().then((function i(s){var c=s.done,a=s.value;if(c){var u=JSON.parse(o);return u.status=e.status,void n.failure(u)}return o+=r.decode(a),t.read().then(i)}))}))};var c=function(e,n,o){connect.assertNotNull(e,"authToken"),connect.assertNotNull(n,"region"),t.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=n,this.authToken=e;var r=connect.getBaseUrl(),i=o||(r.includes(".awsapps.com")?r+"/connect/api":r+"/api"),s=new AWS.Endpoint(i);this.client=new AWS.Connect({endpoint:s})};(c.prototype=Object.create(t.prototype)).constructor=c,c.prototype._callImpl=function(e,t,n){var o=this,r=connect.getLog();if(connect.contains(this.client,e))t=this._translateParams(e,t),r.trace("AWSClient: --\x3e Calling operation '%s'",e).sendInternalLogToServer(),this.client[e](t).on("build",(function(e){e.httpRequest.headers["X-Amz-Bearer"]=o.authToken})).send((function(t,o){try{if(t){if(t.code===connect.CTIExceptions.UNAUTHORIZED_EXCEPTION)n.authFailure();else if(!n.accessDenied||t.code!==connect.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==t.statusCode){var i={};i.type=t.code,i.message=t.message,i.stack=t.stack?t.stack.split("\n"):[],n.failure(i,o)}else n.accessDenied();r.trace("AWSClient: <-- Operation '%s' failed: %s",e,JSON.stringify(t)).sendInternalLogToServer()}else r.trace("AWSClient: <-- Operation '%s' succeeded.",e).withObject(o).sendInternalLogToServer(),n.success(o)}catch(t){connect.getLog().error("Failed to handle AWS API request for method %s",e).withException(t).sendInternalLogToServer()}}));else{var i=connect.sprintf("No such method exists on AWS client: %s",e);n.failure(new connect.ValueError(i),{message:i})}},c.prototype._requiresAuthenticationParam=function(e){return e!==connect.ClientMethods.COMPLETE_CONTACT&&e!==connect.ClientMethods.CLEAR_CONTACT&&e!==connect.ClientMethods.REJECT_CONTACT&&e!==connect.ClientMethods.CREATE_TASK_CONTACT},c.prototype._translateParams=function(e,t){switch(e){case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION:t.configuration=this._translateAgentConfiguration(t.configuration);break;case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:t.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(t.softphoneStreamStatistics);break;case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:t.report=this._translateSoftphoneCallReport(t.report)}return this._requiresAuthenticationParam(e)&&(t.authentication={authToken:this.authToken}),t},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},connect.ClientBase=t,connect.NullClient=n,connect.UpstreamConduitClient=r,connect.UpstreamConduitMasterClient=i,connect.AWSClient=c,connect.AgentAppClient=s}()},531:()=>{function e(e,n){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!o){if(Array.isArray(e)||(o=function(e,n){if(e){if("string"==typeof e)return t(e,n);var o=Object.prototype.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){o&&(e=o);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,c=!0,a=!1;return{s:function(){o=o.call(e)},n:function(){var e=o.next();return c=e.done,e},e:function(e){a=!0,s=e},f:function(){try{c||null==o.return||o.return()}finally{if(a)throw s}}}}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n{!function(){connect=this.connect||{},this.connect=connect;var e="<>",t=connect.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","update_connected_ccps","outer_context_info","media_device_request","media_device_response"]),n=connect.makeNamespacedEnum("connect",["loginPopup","sendLogs","softphone","ringtone","metrics"]),o=connect.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"]),r=connect.makeNamespacedEnum("webSocket",["init_failure","connection_open","connection_close","connection_error","connection_gain","connection_lost","subscription_update","subscription_failure","all_message","send","subscribe"]),i=connect.makeNamespacedEnum("contact",["init","refresh","destroyed","incoming","pending","connecting","connected","missed","acw","view","ended","error","accepted"]),s=connect.makeNamespacedEnum("taskList",["activate_channel_with_view_type"]),c=connect.makeNamespacedEnum("task",["created"]),a=connect.makeNamespacedEnum("connection",["session_init","ready_to_start_session"]),u=connect.makeNamespacedEnum("configuration",["configure","set_speaker_device","set_microphone_device","set_ringer_device","speaker_device_changed","microphone_device_changed","ringer_device_changed"]),l=connect.makeNamespacedEnum("voiceId",["update_domain_id"]),p=function(){};p.createRequest=function(e,t,n){return{event:e,requestId:connect.randomId(),method:t,params:n}},p.createResponse=function(e,t,n,o){return{event:e,requestId:t.requestId,data:n,err:o||null}};var h=function(e,t,n){this.subMap=e,this.id=connect.randomId(),this.eventName=t,this.f=n};h.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var d=function(){this.subIdMap={},this.subEventNameMap={}};d.prototype.subscribe=function(e,t){var n=new h(this,e,t);this.subIdMap[n.id]=n;var o=this.subEventNameMap[e]||[];return o.push(n),this.subEventNameMap[e]=o,n},d.prototype.unsubscribe=function(e,t){connect.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==t})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),connect.contains(this.subIdMap,t)&&delete this.subIdMap[t]},d.prototype.getAllSubscriptions=function(){return connect.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},d.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var f=function(e){var t=e||{};this.subMap=new d,this.logEvents=t.logEvents||!1};f.prototype.subscribe=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.subMap.subscribe(e,t)},f.prototype.subscribeAll=function(t){return connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.subMap.subscribe(e,t)},f.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},f.prototype.trigger=function(t,n){connect.assertNotNull(t,"eventName");var o=this,r=this.subMap.getSubscriptions(e),i=this.subMap.getSubscriptions(t);this.logEvents&&t!==connect.EventType.LOG&&t!==connect.EventType.MASTER_RESPONSE&&t!==connect.EventType.API_METRIC&&t!==connect.EventType.SERVER_BOUND_INTERNAL_LOG&&connect.getLog().trace("Publishing event: %s",t).sendInternalLogToServer(),t.startsWith(connect.ContactEvents.ACCEPTED)&&n&&n.contactId&&!(n instanceof connect.Contact)&&(n=new connect.Contact(n.contactId)),r.concat(i).forEach((function(e){try{e.f(n||null,t,o)}catch(e){connect.getLog().error("'%s' event handler failed.",t).withException(e).sendInternalLogToServer()}}))},f.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},f.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))},connect.EventBus=f,connect.EventFactory=p,connect.EventType=t,connect.AgentEvents=o,connect.ConfigurationEvents=u,connect.ConnectionEvents=a,connect.ConnnectionEvents=a,connect.ContactEvents=i,connect.ChannelViewEvents=s,connect.TaskEvents=c,connect.VoiceIdEvents=l,connect.WebSocketEvents=r,connect.MasterTopics=n}()},42:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(t){var n={};function o(e){if(n[e])return n[e].exports;var r=n[e]={i:e,l:!1,exports:{}};return t[e].call(r.exports,r,r.exports,o),r.l=!0,r.exports}o.m=t,o.c=n,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(t,n){if(1&n&&(t=o(t)),8&n)return t;if(4&n&&"object"==e(t)&&t&&t.__esModule)return t;var r=Object.create(null);if(o.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&n&&"string"!=typeof t)for(var i in t)o.d(r,i,function(e){return t[e]}.bind(null,i));return r},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=2)}([function(t,n,o){"use strict";var r=o(1),i="DEBUG",s="aws/subscribe",c="aws/heartbeat",a="disconnected";function u(t){return(u="function"==typeof Symbol&&"symbol"==e(Symbol.iterator)?function(t){return e(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":e(t)})(t)}var l={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return l.assertTrue(null!==e&&void 0!==u(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"!==u(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},p=new RegExp("^(wss://)\\w*");l.validWSUrl=function(e){return p.test(e)},l.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},l.assertIsObject=function(e,t){if(!l.isObject(e))throw new Error(t+" is not an object!")},l.addJitter=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;t=Math.min(t,1);var n=Math.random()>.5?1:-1;return Math.floor(e+n*e*Math.random()*t)},l.isNetworkOnline=function(){return navigator.onLine},l.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var h=l;function d(t){return(d="function"==typeof Symbol&&"symbol"==e(Symbol.iterator)?function(t){return e(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":e(t)})(t)}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function g(e,t){return(g=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function m(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(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===i?this.consoleLoggerWrapper:new T(t)}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||S.DEBUG,this._clientLogger=t.logger||null,this._logsDestination="NULL",t.debug&&(this._logsDestination=i),t.logger&&(this._logsDestination="CLIENT_LOGGER")}}]),e}(),C=function(){function e(){m(this,e)}return y(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),T=function(e){function t(e){var n;return m(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,f(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&&g(e,t)}(t,C),y(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}();o.d(n,"a",(function(){return N}));var R=function(){var e=A.getLogger({}),t=h.isNetworkOnline(),n={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},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},p={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},d={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},f=new w((function(){B()})),g=new Set([s,"aws/unsubscribe",c]),m=setInterval((function(){if(t!==h.isNetworkOnline()){if(!(t=h.isNetworkOnline()))return void W(e.info("Network offline"));var n=T();t&&(!n||S(n,WebSocket.CLOSING)||S(n,WebSocket.CLOSED))&&(W(e.info("Network online, connecting to WebSocket server")),B())}}),250),v=function(t,n){t.forEach((function(t){try{t(n)}catch(t){W(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]:"";W(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},I=function(){return b(T())},_=function(){if(i.pendingResponse)return W(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void B();I()?(W(e.debug("Sending heartbeat")),T().send(F(c)),i.pendingResponse=!0):(W(e.warn("Failed to send heartbeat since WebSocket is not open")),E("sendHeartBeat"),B())},R=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},N=function(){d.consecutiveFailedSubscribeAttempts=0,d.consecutiveNoResponseRequest=0,clearInterval(d.responseCheckIntervalId),clearInterval(d.reSubscribeIntervalId)},k=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},O=function(){try{W(e.info("WebSocket connection established!")),E("webSocketOnOpen"),null!==o.connState&&o.connState!==a||v(u.connectionGain),o.connState="connected";var t=Date.now();v(u.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?t-r.noOpenConnectionsTimestamp:null}),k(),R(),T().openTimestamp=Date.now(),0===p.subscribed.size&&b(n.secondary)&&x(n.primary,"[Primary WebSocket] Closing WebSocket"),(p.subscribed.size>0||p.pending.size>0)&&(b(n.secondary)&&W(e.info("Subscribing secondary websocket to topics of primary websocket")),p.subscribed.forEach((function(e){p.subscriptionHistory.add(e),p.pending.add(e)})),p.subscribed.clear(),P()),_(),i.intervalHandle=setInterval(_,1e4);var s=1e3*l.connConfig.webSocketTransport.transportLifeTimeInSeconds;W(e.debug("Scheduling WebSocket manager reconnection, after delay "+s+" ms")),o.lifeTimeTimeoutHandle=setTimeout((function(){W(e.debug("Starting scheduled WebSocket manager reconnection")),B()}),s)}catch(t){W(e.error("Error after establishing WebSocket connection",t))}},L=function(t){E("webSocketOnError"),W(e.error("WebSocketManager Error, error_event: ",JSON.stringify(t))),B()},D=function(t){var o=JSON.parse(t.data);switch(o.topic){case s:if(W(e.debug("Subscription Message received from webSocket server",t.data)),d.requestCompleted=!0,d.consecutiveNoResponseRequest=0,"success"===o.content.status)d.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach((function(e){p.subscriptionHistory.delete(e),p.pending.delete(e),p.subscribed.add(e)})),0===p.subscriptionHistory.size?b(n.secondary)&&(W(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),x(n.primary,"[Primary WebSocket] Closing WebSocket")):P(),v(u.subscriptionUpdate,o);else{if(clearInterval(d.reSubscribeIntervalId),++d.consecutiveFailedSubscribeAttempts,5===d.consecutiveFailedSubscribeAttempts)return v(u.subscriptionFailure,o),void(d.consecutiveFailedSubscribeAttempts=0);d.reSubscribeIntervalId=setInterval((function(){P()}),500)}break;case c:W(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(W(e.debug("Message received for topic "+o.topic)),b(n.primary)&&b(n.secondary)&&0===p.subscriptionHistory.size&&this===n.primary)return void W(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===u.allMessage.size&&0===u.topic.size)return void W(e.warn("No registered callback listener for Topic",o.topic));v(u.allMessage,o),u.topic.has(o.topic)&&v(u.topic.get(o.topic),o)}else o.message?W(e.warn("WebSocketManager Message Error",o)):W(e.warn("Invalid incoming message",o))}},P=function t(){if(d.consecutiveNoResponseRequest>3)return W(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void v(u.subscriptionFailure,h.getSubscriptionResponse(s,!1,Array.from(p.pending)));I()?(clearInterval(d.responseCheckIntervalId),T().send(F(s,{topics:Array.from(p.pending)})),d.requestCompleted=!1,d.responseCheckIntervalId=setInterval((function(){d.requestCompleted||(++d.consecutiveNoResponseRequest,t())}),1e3)):W(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):W(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(){r.connectWebSocketRetryCount++;var t=h.addJitter(o.exponentialBackOffTime,.3);Date.now()+t<=l.connConfig.urlConnValidTime?(W(e.debug("Scheduling WebSocket reinitialization, after delay "+t+" ms")),o.exponentialTimeoutHandle=setTimeout((function(){return V()}),t),o.exponentialBackOffTime*=2):(W(e.warn("WebSocket URL cannot be used to establish connection")),B())},q=function(t){R(),N(),W(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(m),v(u.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:t}),k()},F=function(e,t){return JSON.stringify({topic:e,content:t})},j=function(t){return!!(h.isObject(t)&&h.isObject(t.webSocketTransport)&&h.isNonEmptyString(t.webSocketTransport.url)&&h.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(W(e.error("Invalid WebSocket Connection Configuration",t)),!1)},B=function(){if(h.isNetworkOnline())if(o.websocketInitFailed)W(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(l.promiseCompleted)return R(),W(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),l.promiseCompleted=!1,l.promiseHandle=u.getWebSocketTransport(),l.promiseHandle.then((function(t){return l.promiseCompleted=!0,W(e.debug("Successfully fetched webSocket connection configuration",t)),j(t)?(l.connConfig=t,l.connConfig.urlConnValidTime=Date.now()+85e3,f.connected(),V()):(q("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return l.promiseCompleted=!0,W(e.error("Failed to fetch webSocket connection configuration",t)),h.isNetworkFailure(t)?(W(e.info("Retrying fetching new WebSocket connection configuration")),f.retry()):q("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));W(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else W(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},V=function(){if(o.websocketInitFailed)return W(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!h.isNetworkOnline())return W(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};W(e.info("Initializing Websocket Manager")),E("initWebSocket");try{if(j(l.connConfig)){var t=null;return b(n.primary)?(W(e.debug("Primary Socket connection is already open")),S(n.secondary,WebSocket.CONNECTING)||(W(e.debug("Establishing a secondary web-socket connection")),n.secondary=H()),t=n.secondary):(S(n.primary,WebSocket.CONNECTING)||(W(e.debug("Establishing a primary web-socket connection")),n.primary=H()),t=n.primary),o.webSocketInitCheckerTimeoutId=setTimeout((function(){b(t)||U()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return W(e.error("Error Initializing web-socket-manager",t)),q("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},H=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){W(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),o.reconnectWebSocket&&(b(n.primary)||b(n.secondary)?C(n.primary)&&b(n.secondary)&&(W(e.info("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(W(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===a?W(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}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=a,B()),E("webSocketOnClose after-cleanup"))}(i,t)})),t},W=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(h.assertTrue(h.isFunction(t),"transportHandle must be a function"),null===u.getWebSocketTransport)return u.getWebSocketTransport=t,B();W(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.initFailure.add(e),o.websocketInitFailed&&e(),function(){return u.initFailure.delete(e)}},this.onConnectionOpen=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionOpen.add(e),function(){return u.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionClose.add(e),function(){return u.connectionClose.delete(e)}},this.onConnectionGain=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionGain.add(e),I()&&e(),function(){return u.connectionGain.delete(e)}},this.onConnectionLost=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionLost.add(e),o.connState===a&&e(),function(){return u.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.subscriptionUpdate.add(e),function(){return u.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.subscriptionFailure.add(e),function(){return u.subscriptionFailure.delete(e)}},this.onMessage=function(e,t){return h.assertNotNull(e,"topicName"),h.assertTrue(h.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 h.assertTrue(h.isFunction(e),"cb must be a function"),u.allMessage.add(e),function(){return u.allMessage.delete(e)}},this.subscribeTopics=function(e){h.assertNotNull(e,"topics"),h.assertIsList(e),e.forEach((function(e){p.subscribed.has(e)||p.pending.add(e)})),d.consecutiveNoResponseRequest=0,P()},this.sendMessage=function(t){if(h.assertIsObject(t,"payload"),void 0===t.topic||g.has(t.topic))W(e.warn("Cannot send message, Invalid topic",t));else{try{t=JSON.stringify(t)}catch(n){return void W(e.warn("Error stringify message",t))}I()?T().send(t):W(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){R(),N(),o.reconnectWebSocket=!1,clearInterval(m),M("User request to close WebSocket")},this.terminateWebSocketManager=q},N={create:function(){return new R},setGlobalConfig:function(e){var t=e.loggerConfig;A.updateLoggerConfig(t)},LogLevel:S,Logger:E}},function(t,n,o){var r;!function(){"use strict";var i={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 s(t){return function(t,n){var o,r,c,a,u,l,p,h,d,f=1,g=t.length,m="";for(r=0;r=0),a.type){case"b":o=parseInt(o,10).toString(2);break;case"c":o=String.fromCharCode(parseInt(o,10));break;case"d":case"i":o=parseInt(o,10);break;case"j":o=JSON.stringify(o,null,a.width?parseInt(a.width):0);break;case"e":o=a.precision?parseFloat(o).toExponential(a.precision):parseFloat(o).toExponential();break;case"f":o=a.precision?parseFloat(o).toFixed(a.precision):parseFloat(o);break;case"g":o=a.precision?String(Number(o.toPrecision(a.precision))):parseFloat(o);break;case"o":o=(parseInt(o,10)>>>0).toString(8);break;case"s":o=String(o),o=a.precision?o.substring(0,a.precision):o;break;case"t":o=String(!!o),o=a.precision?o.substring(0,a.precision):o;break;case"T":o=Object.prototype.toString.call(o).slice(8,-1).toLowerCase(),o=a.precision?o.substring(0,a.precision):o;break;case"u":o=parseInt(o,10)>>>0;break;case"v":o=o.valueOf(),o=a.precision?o.substring(0,a.precision):o;break;case"x":o=(parseInt(o,10)>>>0).toString(16);break;case"X":o=(parseInt(o,10)>>>0).toString(16).toUpperCase()}i.json.test(a.type)?m+=o:(!i.number.test(a.type)||h&&!a.sign?d="":(d=h?"+":"-",o=o.toString().replace(i.sign,"")),l=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",p=a.width-(d+o).length,u=a.width&&p>0?l.repeat(p):"",m+=a.align?d+o+u:"0"===l?d+u+o:u+d+o)}return m}(function(e){if(a[e])return a[e];for(var t,n=e,o=[],r=0;n;){if(null!==(t=i.text.exec(n)))o.push(t[0]);else if(null!==(t=i.modulo.exec(n)))o.push("%");else{if(null===(t=i.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){r|=1;var s=[],c=t[2],u=[];if(null===(u=i.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=i.key_access.exec(c)))s.push(u[1]);else{if(null===(u=i.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}t[2]=s}else r|=2;if(3===r)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return a[e]=o}(t),arguments)}function c(e,t){return s.apply(null,[e].concat(t||[]))}var a=Object.create(null);n.sprintf=s,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=s,window.vsprintf=c,void 0===(r=function(){return{sprintf:s,vsprintf:c}}.call(n,o,n,t))||(t.exports=r))}()},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"WebSocketManager",(function(){return r}));var o=n(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,n(3))},function(t,n){var o;o=function(){return this}();try{o=o||new Function("return this")()}catch(t){"object"==("undefined"==typeof window?"undefined":e(window))&&(o=window)}t.exports=o}])},312:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(){var t=this;connect=t.connect||{},t.connect=connect,t.lily=connect;var n={TEST:"TEST",TRACE:"TRACE",DEBUG:"DEBUG",INFO:"INFO",LOG:"LOG",WARN:"WARN",ERROR:"ERROR",CRITICAL:"CRITICAL"},o={CCP:"ccp",SOFTPHONE:"softphone",CHAT:"chat",TASK:"task"},r={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,r=Array.prototype.slice.call(e,0),i=r.shift();return function(e){return-1!==Object.values(o).indexOf(e)}(i)?(n=i,t=r.shift()):(t=i,n=o.CCP),{format:t,component:n,args:r}},c=function(e,t,n,o){this.component=e,this.level=t,this.text=n,this.time=new Date,this.exception=null,this.objects=[],this.line=0,this.agentResourceId=null;try{connect.agent.initialized&&(this.agentResourceId=(new connect.Agent)._getResourceId())}catch(e){console.log("Issue finding agentResourceId: ",e)}this.loggerId=o};c.fromObject=function(e){var t=new c(o.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 a=function t(n){var o=/AuthToken.*\=/g;n&&"object"===e(n)&&Object.keys(n).forEach((function(r){"object"===e(n[r])?t(n[r]):"string"==typeof n[r]&&("url"===r||"text"===r?n[r]=n[r].replace(o,"[redacted]"):"quickConnectName"===r&&(n[r]="[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"):[]};c.prototype.toString=function(){return connect.sprintf("[%s] [%s] [%s]: %s",this.getTime()&&this.getTime().toISOString?this.getTime().toISOString():"???",this.getLevel(),this.getAgentResourceId(),this.getText())},c.prototype.getTime=function(){return this.time},c.prototype.getAgentResourceId=function(){return this.agentResourceId},c.prototype.getLevel=function(){return this.level},c.prototype.getText=function(){return this.text},c.prototype.getComponent=function(){return this.component},c.prototype.withException=function(e){return this.exception=new u(e),this},c.prototype.withObject=function(e){var t=connect.deepcopy(e);return a(t),this.objects.push(t),this},c.prototype.withCrossOriginEventObject=function(e){var t=connect.deepcopyCrossOriginEvent(e);return a(t),this.objects.push(t),this},c.prototype.sendInternalLogToServer=function(){return connect.getLog()._serverBoundInternalLogs.push(this),this};var l=function(){this._logs=[],this._rolledLogs=[],this._logsToPush=[],this._serverBoundInternalLogs=[],this._echoLevel=r.INFO,this._logLevel=r.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(e){var n=this;this._logRollTimer&&e===this._logRollInterval?this.warn("Logger is already set to the given interval: %d",this._logRollInterval):(this._logRollTimer&&t.clearInterval(this._logRollTimer),this._logRollInterval=e,this._logRollTimer=t.setInterval((function(){this._rolledLogs=this._logs,this._logs=[],this._startLogIndexToPush=0,n.info("Log roll interval occurred.")}),this._logRollInterval))},l.prototype.setLogLevel=function(e){if(!(e in r))throw new Error("Unknown logging level: "+e);this._logLevel=r[e]},l.prototype.setEchoLevel=function(e){if(!(e in r))throw new Error("Unknown logging level: "+e);this._echoLevel=r[e]},l.prototype.write=function(e,t,n){var o=new c(e,t,n,this.getLoggerId());return a(o),this.addLogEntry(o),o},l.prototype.addLogEntry=function(e){a(e),this._logs.push(e),o.SOFTPHONE===e.component&&this._logsToPush.push(e),e.level in r&&r[e.level]>=this._logLevel&&(r[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 r&&r[e.level]>=this._logLevel&&(r[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=s._logLevel})));var a=new t.Blob([JSON.stringify(c,void 0,4)],["text/plain"]),u=document.createElement("a");o=o||"agent-log",u.href=t.URL.createObjectURL(a),u.download=o+".txt",document.body.appendChild(u),u.click(),document.body.removeChild(u)},l.prototype.scheduleUpstreamLogPush=function(e){connect.upstreamLogPushScheduled||(connect.upstreamLogPushScheduled=!0,t.setInterval(connect.hitch(this,this.reportMasterLogsUpStream,e),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var t=this._logsToPush.slice();this._logsToPush=[],connect.ifMaster(connect.MasterTopics.SEND_LOGS,(function(){t.length>0&&e.sendUpstream(connect.EventType.SEND_LOGS,t)}))},l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush=function(e){t.setInterval(connect.hitch(this,this.pushOuterContextCCPserverBoundLogsUpstream,e),1e3)},l.prototype.scheduleUpstreamOuterContextCCPLogsPush=function(e){t.setInterval(connect.hitch(this,this.pushOuterContextCCPLogsUpstream,e),1e3)},l.prototype.pushOuterContextCCPserverBoundLogsUpstream=function(e){if(this._serverBoundInternalLogs.length>0){for(var t=0;t500?e=this._serverBoundInternalLogs.splice(0,500):(e=this._serverBoundInternalLogs,this._serverBoundInternalLogs=[]),connect.publishClientSideLogs(e))};var p=function e(n){l.call(this),this.conduit=n,t.setInterval(connect.hitch(this,this._pushLogsDownstream),e.LOG_PUSH_INTERVAL),t.clearInterval(this._logRollTimer),this._logRollTimer=null};p.LOG_PUSH_INTERVAL=1e3,(p.prototype=Object.create(l.prototype)).constructor=p,p.prototype.pushLogsDownstream=function(e){var t=this;e.forEach((function(e){t.conduit.sendDownstream(connect.EventType.LOG,e)}))},p.prototype._pushLogsDownstream=function(){var e=this;this._logs.forEach((function(t){e.conduit.sendDownstream(connect.EventType.LOG,t)})),this._logs=[];for(var t=0;t{!function(){connect=this.connect||{},this.connect=connect,connect.ChatMediaController=function(e,t){var n=connect.getLog(),o=connect.LogComponent.CHAT,r=function(t,n){connect.publishMetric({name:t,contactId:e.contactId,data:n||e})},i=function(e){e.onConnectionBroken((function(e){n.error(o,"Chat Session connection broken").withException(e).sendInternalLogToServer(),r("Chat Session connection broken",e)})),e.onConnectionEstablished((function(e){n.info(o,"Chat Session connection established").withObject(e).sendInternalLogToServer(),r("Chat Session connection established",e)}))};return{get:function(){return function(){r("Chat media controller init",e.contactId),n.info(o,"Chat media controller init").withObject(e).sendInternalLogToServer(),connect.ChatSession.setGlobalConfig({loggerConfig:{logger:n},region:t.region});var s=connect.ChatSession.create({chatDetails:e,type:"AGENT",websocketManager:connect.core.getWebSocketManager()});return i(s),s.connect().then((function(t){return n.info(o,"Chat Session Successfully established for contactId %s",e.contactId).sendInternalLogToServer(),r("Chat Session Successfully established",e.contactId),s})).catch((function(t){throw n.error(o,"Chat Session establishement failed for contact %s",e.contactId).withException(t).sendInternalLogToServer(),r("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},7:()=>{!function(){connect=this.connect||{},this.connect=connect,connect.MediaFactory=function(e){var t={},n=new Set,o=connect.getLog(),r=connect.LogComponent.CHAT,i=connect.merge({},e)||{};i.region=i.region||"us-west-2";var s=function(e){t[e]&&!n.has(e)&&(o.info(r,"Destroying mediaController for %s",e),n.add(e),t[e].then((function(){"function"==typeof controller.cleanUp&&controller.cleanUp(),delete t[e],n.delete(e)})).catch((function(){delete t[e],n.delete(e)})))};return{get:function(e){return function(e){return e.isActive()}(e)?function(e){var n=e.getConnectionId();if(!e.getMediaInfo())return o.error(r,"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(t[n])return t[n];switch(o.info(r,"media controller of type %s init",e.getMediaType()).withObject(e).sendInternalLogToServer(),e.getMediaType()){case connect.MediaType.CHAT:return t[n]=new connect.ChatMediaController(e.getMediaInfo(),i).get();case connect.MediaType.SOFTPHONE:return t[n]=new connect.SoftphoneMediaController(e.getMediaInfo()).get();case connect.MediaType.TASK:return t[n]=new connect.TaskMediaController(e.getMediaInfo()).get();default:return o.error(r,"Unrecognized media type %s ",e.getMediaType()).sendInternalLogToServer(),Promise.reject()}}(e):(s(e.getConnectionId()),Promise.reject("Media Controller is no longer available for this connection"))},destroy:s}}}()},6:()=>{!function(){connect=this.connect||{},this.connect=connect,connect.SoftphoneMediaController=function(e){return{get:function(){return Promise.resolve(e)}}}}()},487:()=>{!function(){connect=this.connect||{},this.connect=connect,connect.TaskMediaController=function(e){var t=connect.getLog(),n=connect.LogComponent.TASK,o=function(t,n){connect.publishMetric({name:t,contactId:e.contactId,data:n||e})},r=function(e){e.onConnectionBroken((function(e){t.error(n,"Task Session connection broken").withException(e),o("Task Session connection broken",e)})),e.onConnectionEstablished((function(e){t.info(n,"Task Session connection established").withObject(e),o("Task Session connection established",e)}))};return{get:function(){return function(){o("Task media controller init",e.contactId),t.info(n,"Task media controller init").withObject(e);var i=connect.TaskSession.create({contactId:e.contactId,initialContactId:e.initialContactId,websocketManager:connect.core.getWebSocketManager()});return r(i),i.connect().then((function(){return t.info(n,"Task Session Successfully established for contactId %s",e.contactId),o("Task Session Successfully established",e.contactId),i})).catch((function(r){throw t.error(n,"Task Session establishement failed for contact %s",e.contactId).withException(r),o("Chat Session establishement failed",e.contactId,r),r}))}()}}}}()},743:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function n(e){for(var n=1;n2&&void 0!==arguments[2]?arguments[2]:{};t.assertNotNull(e,"ccpUrl"),t.assertNotNull(o,"container"),a=o,c=e,function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.custom=e.custom||{},(s=n(n(n({},i),e),{},{custom:n(n({},i.custom),e.custom)})).canRequest=!("false"===s.canRequest||!1===s.canRequest)}(r),t.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(e," - ").concat(s.canRequest?"Proceeding with requesting storage access":"user has opted out, skipping request storage access")).withObject(s)},setupRequestHandlers:function(e){var n=e.onGrant;o&&o.unsubscribe(),o=v({onInit:function(e){console.log("%c[INIT]","background:lime; color: black; font-size:large"),t.getLog().info("[StorageAccess][onInit] callback executed").withObject(null==e?void 0:e.data),null!=e&&e.data.hasAccess||!h()||p().show()},onDeny:function(){console.log("%c[DENIED]","background:lime; color: black; font-size:large"),t.getLog().info("[StorageAccess][onDeny] callback executed"),h()&&p().show()},onGrant:function(){console.log("%c[Granted]","background:lime; color: black; font-size:large"),t.getLog().info("[StorageAccess][onGrant] callback executed"),h()&&p().hide(),u||(n(),u=!0)}})},getRequestStorageAccessUrl:function(){if(!c)throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first");if(d(c))return f(c);if(g(c))return t.getLog().info("[StorageAccess] [CCP] Local testing"),"".concat(c).concat(r);if(s.instanceUrl&&d(s.instanceUrl))return t.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(s.instanceUrl)),f(s.instanceUrl);if(s.instanceUrl&&g(s.instanceUrl))return t.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"),"".concat(s.instanceUrl).concat(r);throw t.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"),new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL")},storageAccessEvents:l,resetStorageAccessState:function(){s={},c="",a=null},getStorageAccessParams:function(){return s},onRequest:v,request:function(){t.core._getCCPIframe().contentWindow.postMessage({event:l.REQUEST,data:n(n({},s),{},{landat:m()})},"*")}})}()},555:()=>{!function(){var e=this,t=e.connect||{};e.connect=t,e.lily=t;var n=function(n){var o=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){o._audio=new Audio(n.ringtoneUrl),o._audio.loop=!0,o._audio.addEventListener("canplay",(function(){o._audioPlayable=!0,e(o._audio)}))})):(this._audio=null,t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()),o._driveRingtone()};n.prototype._driveRingtone=function(){throw new Error("Not implemented.")},n.prototype._startRingtone=function(e){this._audio&&(this._audio.play().catch((function(n){this._publishTelemetryEvent("Ringtone Playback Failure",e),t.getLog().error("Ringtone Playback Failure").sendInternalLogToServer()})),this._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 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.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 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.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=o,t.ChatRingtoneEngine=r,t.TaskRingtoneEngine=i,t.QueueCallbackRingtoneEngine=s}()},960:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(){var t=this;connect=t.connect||{},t.connect=connect,t.lily=connect,t.ccpVersion="V2";var n={};n[connect.SoftphoneCallType.AUDIO_ONLY]="Audio",n[connect.SoftphoneCallType.VIDEO_ONLY]="Video",n[connect.SoftphoneCallType.AUDIO_VIDEO]="AudioVideo",n[connect.SoftphoneCallType.NONE]="None";var o="audio_input",r="audio_output";({})[connect.ContactType.VOICE]="Voice";var i=[],s={},c={},a=null,u=null,l=null,p=connect.SoftphoneErrorTypes,h={},d=connect.randomId(),f=function(e){return new Promise((function(t,n){connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT,e,{success:function(e){t(e.softphoneTransport.softphoneMediaConnections)},failure:function(e){e.message&&e.message.includes("SoftphoneConnectionLimitBreachedException")&&_("multiple_softphone_active_sessions","Number of active sessions are more then allowed limit.",""),n(Error("requestIceAccess failed"))},authFailure:function(){n(Error("Authentication failed while requestIceAccess"))},accessDenied:function(){n(Error("Access Denied while requestIceAccess"))}})}))},g=function(e){var t=connect.core.getUpstream(),n=e.getAgentConnection();if(n){var o=n.getSoftphoneMediaInfo();o?!0===o.autoAccept?(l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(),t.sendUpstream(connect.EventType.BROADCAST,{event:connect.ContactEvents.ACCEPTED,data:new connect.Contact(e.contactId)}),t.sendUpstream(connect.EventType.BROADCAST,{event:connect.core.getContactEventName(connect.ContactEvents.ACCEPTED,e.contactId),data:new connect.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(){connect.core.getEventBus().subscribe(connect.EventType.MUTE,S)},v=function(){connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE,b)},y=function(){connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE,C)},E=function(e){delete h[e],connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.MUTE_TOGGLE,data:{muted:!1}})},S=function(e){var t;if(0!==connect.keys(h).length){for(var n in e&&void 0!==e.mute&&(t=e.mute),h)if(h.hasOwnProperty(n)){var o=h[n].stream;if(o){var r=o.getAudioTracks()[0];void 0!==t?(r.enabled=!t,h[n].muted=t,t?l.info("Agent has muted the contact, connectionId - "+n).sendInternalLogToServer():l.info("Agent has unmuted the contact, connectionId - "+n).sendInternalLogToServer()):t=h[n].muted||!1}}connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.MUTE_TOGGLE,data:{muted:t}})}},b=function(e){if(0!==connect.keys(h).length&&e&&e.deviceId){var t=e.deviceId,n=document.getElementById("remote-audio");try{l.info("Trying to set speaker to device "+t),n&&"function"==typeof n.setSinkId&&n.setSinkId(t)}catch(e){l.error("Failed to set speaker to device "+t)}connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,data:{deviceId:t}})}},C=function(e){if(0!==connect.keys(h).length&&e&&e.deviceId){var t=e.deviceId,n=connect.core.getSoftphoneManager();try{navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:t}}}).then((function(e){var t=e.getAudioTracks()[0];for(var o in h)h.hasOwnProperty(o)&&(h[o].stream,n.getSession(o)._pc.getSenders()[0].replaceTrack(t).then((function(){n.replaceLocalMediaTrack(o,t)})))}))}catch(e){l.error("Failed to set microphone device "+t)}connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,data:{deviceId:t}})}},T=function(e,t){if(t===connect.RTCErrors.ICE_COLLECTION_TIMEOUT){for(var n="\n",o=0;o0?n.success(e):n.failure(p.MICROPHONE_NOT_SHARED)}),(function(e){n.failure(p.MICROPHONE_NOT_SHARED)})),r}n.failure(p.UNSUPPORTED_BROWSER)},_=function(e,t,n){l.error("Softphone error occurred : ",e,t||"").sendInternalLogToServer(),connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.SOFTPHONE_ERROR,data:new connect.SoftphoneError(e,t,n)})},w=function(e,t){R("Softphone Session Failed",e,{failedReason:t})},R=function(e,t,n){t&&connect.publishMetric({name:e,contactId:t,data:n})},N=function(e,t,n){R(e,t,[{name:"AgentConnectionId",value:n}]),l.info("Publish multiple session error metrics",e,"contactId "+t,"agent connectionId "+n).sendInternalLogToServer()},k=function(){return!!(connect.isOperaBrowser()&&connect.getOperaBrowserVersion()>17)||!!(connect.isChromeBrowser()&&connect.getChromeBrowserVersion()>22)||!!(connect.isFirefoxBrowser()&&connect.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()}})},L=function(e){a=window.setInterval((function(){e.getUserAudioStats().then((function(e){var t=s;s=e,i.push(x(s,t,o))}),(function(e){l.debug("Failed to get user audio stats.",e).sendInternalLogToServer()})),e.getRemoteAudioStats().then((function(e){var t=c;c=e,i.push(x(c,t,r))}),(function(e){l.debug("Failed to get remote audio stats.",e).sendInternalLogToServer()}))}),1e3)},D=function(e){u=window.setInterval((function(){O(e)}),3e4)},P=function(){s=null,c=null,i=[],a=null,u=null},x=function(e,t,n){if(t&&e){var o=e.packetsLost>t.packetsLost?e.packetsLost-t.packetsLost:0,r=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new q(e.timestamp,o,r,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new q(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},M=function(e){return null!==e&&window.clearInterval(e),null},U=function(e,t){a=M(a),u=M(u),function(e,t,n,i){t.streamStats=[F(n,o),F(i,r)];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,F(s,o),F(c,r)),O(e)},q=function(e,t,n,o,r,i,s){this.softphoneStreamType=o,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=r,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},F=function(e,t){return new q((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},j=function(e){this._originalLogger=e;var t=this;this._tee=function(e,n){return function(){var e=Array.prototype.slice.call(arguments[0]),o="";return e.forEach((function(){o+=" %s"})),n.apply(t._originalLogger,[connect.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)},connect.SoftphoneManager=function(e){var t,n=this;(l=new j(connect.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),connect.RtcPeerConnectionFactory&&(t=new connect.RtcPeerConnectionFactory(l,connect.core.getWebSocketManager(),d,connect.hitch(n,f,{transportType:"softphone",softphoneClientId:d}),connect.hitch(n,_))),k()||_(p.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ",""),A({success:function(e){connect.core.setSoftphoneUserMediaStream(e)},failure:function(e){_(e,"Your microphone is not enabled in your browser. ","")}}),m(),v(),y(),this.ringtoneEngine=null;var o={},r={};this.onInitContactSub={},this.onInitContactSub.unsubscribe=function(){};var i=!1,s=null,c=null,a=function(){i=!1,s=null,c=null};this.getSession=function(e){return o[e]},this.replaceLocalMediaTrack=function(e,t){var n=h[e].stream;if(n){var o=n.getAudioTracks()[0];t.enabled=o.enabled,o.enabled=!1,n.removeTrack(o),n.addTrack(t)}};var u=function(e){if(o.hasOwnProperty(e)){var t=o[e];new Promise((function(n,i){delete o[e],delete r[e],t.hangup()})).catch((function(t){lily.getLog().warn("Clean up the session locally "+e,t.message).sendInternalLogToServer()}))}};this.startSession=function(e,n){var p=i?s:e,d=i?c:n;if(p&&d){a(),r[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)&&(N("MultiSessionHangUp",e[t].callId,t),u(t));throw new Error("duplicate session detected, refusing to setup new connection")}}(o),p.getStatus().type===connect.ContactStatusType.CONNECTING&&R("Softphone Connecting",p.getContactId()),P();var f,m=p.getAgentConnection().getSoftphoneMediaInfo(),v=I(m.callConfigJson);v.useWebSocketProvider&&(f=connect.core.getWebSocketManager());var y=new connect.RTCSession(v.signalingEndpoint,v.iceServers,m.callContextToken,l,p.getContactId(),d,f);o[d]=y,connect.core.getSoftphoneUserMediaStream()&&(y.mediaStream=connect.core.getSoftphoneUserMediaStream()),connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConnectionEvents.SESSION_INIT,data:{connectionId:d}}),y.onSessionFailed=function(e,t){delete o[d],delete r[d],T(e,t),w(p.getContactId(),t),U(p,e.sessionReport)},y.onSessionConnected=function(e){R("Softphone Session Connected",p.getContactId()),connect.becomeMaster(connect.MasterTopics.SEND_LOGS),L(e),D(p),g(p)},y.onSessionCompleted=function(e){R("Softphone Session Completed",p.getContactId()),delete o[d],delete r[d],U(p,e.sessionReport),E(d)},y.onLocalStreamAdded=function(e,t){h[d]={stream:t},connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,data:{connectionId:d}})},y.remoteAudioElement=document.getElementById("remote-audio"),t?y.connect(t.get(v.iceServers)):y.connect()}};var S=function(e,t){o[t]&&function(e){return e.getStatus().type===connect.ContactStatusType.ENDED||e.getStatus().type===connect.ContactStatusType.ERROR||e.getStatus().type===connect.ContactStatusType.MISSED}(e)&&(u(t),a()),!e.isSoftphoneCall()||r[t]||e.getStatus().type!==connect.ContactStatusType.CONNECTING&&e.getStatus().type!==connect.ContactStatusType.INCOMING||(connect.isFirefoxBrowser()&&connect.hasOtherConnectedCCPs()?function(e,t){i=!0,s=e,c=t}(e,t):n.startSession(e,t))},b=function(e){var t=e.getAgentConnection().connectionId;l.info("Contact detected:","contactId "+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),r[t]||e.onRefresh((function(){S(e,t)}))};n.onInitContactSub=connect.contact(b),(new connect.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(),b(e),S(e,t)}))}}()},778:()=>{!function(){var e=function e(){return e.cache.hasOwnProperty(arguments[0])||(e.cache[arguments[0]]=e.parse(arguments[0])),e.format.call(null,e.cache[arguments[0]],arguments)};function t(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function n(e,t){for(var n=[];t>0;n[--t]=e);return n.join("")}e.format=function(o,r){var i,s,c,a,u,l,p,h=1,d=o.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(a[8])&&a[3]&&i>=0?"+"+i:i,l=a[4]?"0"==a[4]?"0":a[4].charAt(1):" ",p=a[6]-String(i).length,u=a[6]?n(l,p):"",g.push(a[5]?i+u:u+i)}return g.join("")},e.cache={},e.parse=function(e){for(var t=e,n=[],o=[],r=0;t;){if(null!==(n=/^[^\x25]+/.exec(t)))o.push(n[0]);else if(null!==(n=/^\x25{2}/.exec(t)))o.push("%");else{if(null===(n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t)))throw"[sprintf] huh?";if(n[2]){r|=1;var i=[],s=n[2],c=[];if(null===(c=/^([a-z_][a-z_\d]*)/i.exec(s)))throw"[sprintf] huh?";for(i.push(c[1]);""!==(s=s.substring(c[0].length));)if(null!==(c=/^\.([a-z_][a-z_\d]*)/i.exec(s)))i.push(c[1]);else{if(null===(c=/^\[(\d+)\]/.exec(s)))throw"[sprintf] huh?";i.push(c[1])}n[2]=i}else r|=2;if(3===r)throw"[sprintf] mixing positional and named placeholders is not (yet) supported";o.push(n)}t=t.substring(n[0].length)}return o},this.sprintf=e,this.vsprintf=function(t,n,o){return(o=n.slice(0)).splice(0,0,t),e.apply(null,o)}}()},768:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect;var t=function(){};t.prototype.send=function(e){throw new connect.NotImplementedError},t.prototype.onMessage=function(e){throw new connect.NotImplementedError};var n=function(){t.call(this)};(n.prototype=Object.create(t.prototype)).constructor=n,n.prototype.onMessage=function(e){},n.prototype.send=function(e){};var o=function(e,n){t.call(this),this.window=e,this.domain=n||"*"};(o.prototype=Object.create(t.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 r=function(e,n,o){t.call(this),this.input=e,this.output=n,this.domain=o||"*"};(r.prototype=Object.create(t.prototype)).constructor=r,r.prototype.send=function(e){this.output.postMessage(e,this.domain)},r.prototype.onMessage=function(e){var t=this;this.input.addEventListener("message",(function(n){n.source===t.output&&e(n)}))};var i=function(e){t.call(this),this.port=e,this.id=connect.randomId()};(i.prototype=Object.create(t.prototype)).constructor=i,i.prototype.send=function(e){this.port.postMessage(e)},i.prototype.onMessage=function(e){this.port.addEventListener("message",e)},i.prototype.getId=function(){return this.id};var s=function(e){t.call(this),this.streamMap=e?connect.index(e,(function(e){return e.getId()})):{},this.messageListeners=[]};(s.prototype=Object.create(t.prototype)).constructor=s,s.prototype.send=function(e){this.getStreams().forEach((function(t){try{t.send(e)}catch(e){}}))},s.prototype.onMessage=function(e){this.messageListeners.push(e),this.getStreams().forEach((function(t){t.onMessage(e)}))},s.prototype.addStream=function(e){this.streamMap[e.getId()]=e,this.messageListeners.forEach((function(t){e.onMessage(t)}))},s.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},s.prototype.getStreams=function(e){return connect.values(this.streamMap)},s.prototype.getStreamForPort=function(e){return connect.find(this.getStreams(),(function(t){return t.port===e}))};var c=function(e,t,o){this.name=e,this.upstream=t||new n,this.downstream=o||new n,this.downstreamBus=new connect.EventBus,this.upstreamBus=new connect.EventBus,this.upstream.onMessage(connect.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(connect.hitch(this,this._dispatchEvent,this.downstreamBus))};c.prototype.onUpstream=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.upstreamBus.subscribe(e,t)},c.prototype.onAllUpstream=function(e){return connect.assertNotNull(e,"f"),connect.assertTrue(connect.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},c.prototype.onDownstream=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.downstreamBus.subscribe(e,t)},c.prototype.onAllDownstream=function(e){return connect.assertNotNull(e,"f"),connect.assertTrue(connect.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},c.prototype.sendUpstream=function(e,t){connect.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:t})},c.prototype.sendDownstream=function(e,t){connect.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:t})},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 a=function(e,t,n,o){c.call(this,e,new r(t,n.contentWindow,o||"*"),null)};(a.prototype=Object.create(c.prototype)).constructor=a,connect.Stream=t,connect.NullStream=n,connect.WindowStream=o,connect.WindowIOStream=r,connect.PortStream=i,connect.StreamMultiplexer=s,connect.Conduit=c,connect.IFrameConduit=a}()},738:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect;var t=function(e,t){connect.assertNotNull(e,"fromState"),connect.assertNotNull(t,"toState"),this.fromState=e,this.toState=t};t.prototype.getAssociations=function(e){throw connect.NotImplementedError()},t.prototype.getFromState=function(){return this.fromState},t.prototype.getToState=function(){return this.toState};var n=function(e,n,o){connect.assertNotNull(e,"fromState"),connect.assertNotNull(n,"toState"),connect.assertNotNull(o,"associations"),t.call(this,e,n),this.associations=o};(n.prototype=Object.create(t.prototype)).constructor=n,n.prototype.getAssociations=function(e){return this.associations};var o=function(e,n,o){connect.assertNotNull(e,"fromState"),connect.assertNotNull(n,"toState"),connect.assertNotNull(o,"closure"),connect.assertTrue(connect.isFunction(o),"closure must be a function"),t.call(this,e,n),this.closure=o};(o.prototype=Object.create(t.prototype)).constructor=o,o.prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};var r=function(){this.fromMap={}};r.ANY="<>",r.prototype.assoc=function(e,t,r){var i=this;if(!e)throw new Error("fromStateObj is not defined.");if(!t)throw new Error("toStateObj is not defined.");if(!r)throw new Error("assocObj is not defined.");return e instanceof Array?e.forEach((function(e){i.assoc(e,t,r)})):t instanceof Array?t.forEach((function(t){i.assoc(e,t,r)})):"function"==typeof r?this._addAssociation(new o(e,t,r)):r instanceof Array?this._addAssociation(new n(e,t,r)):this._addAssociation(new n(e,t,[r])),this},r.prototype.getAssociations=function(e,t,n){connect.assertNotNull(t,"fromState"),connect.assertNotNull(n,"toState");var o=[],i=this.fromMap[r.ANY]||{},s=this.fromMap[t]||{};return o=(o=o.concat(this._getAssociationsFromMap(i,e,t,n))).concat(this._getAssociationsFromMap(s,e,t,n))},r.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)},r.prototype._getAssociationsFromMap=function(e,t,n,o){return(e[r.ANY]||[]).concat(e[o]||[]).reduce((function(e,n){return e.concat(n.getAssociations(t))}),[])},connect.EventGraph=r}()},420:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(){var t=this;connect=t.connect||{},t.connect=connect,t.lily=connect;var n=navigator.userAgent,o=["bubbles","cancelBubble","cancelable","composed","data","defaultPrevented","eventPhase","isTrusted","lastEventId","origin","returnValue","timeStamp","type"];connect.sprintf=t.sprintf,connect.vsprintf=t.vsprintf,delete t.sprintf,delete t.vsprintf,connect.HTTP_STATUS_CODES={SUCCESS:200,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},connect.TRANSPORT_TYPES={CHAT_TOKEN:"chat_token",WEB_SOCKET:"web_socket"},connect.hitch=function(){var e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift();return connect.assertNotNull(t,"scope"),connect.assertNotNull(n,"method"),connect.assertTrue(connect.isFunction(n),"method must be a function"),function(){var o=Array.prototype.slice.call(arguments);return n.apply(t,e.concat(o))}},connect.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},connect.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},connect.keys=function(e){var t=[];for(var n in connect.assertNotNull(e,"map"),e)t.push(n);return t},connect.values=function(e){var t=[];for(var n in connect.assertNotNull(e,"map"),e)t.push(e[n]);return t},connect.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},connect.merge=function(){var e=Array.prototype.slice.call(arguments,0),t={};return e.forEach((function(e){connect.entries(e).forEach((function(e){t[e.key]=e.value}))})),t},connect.now=function(){return(new Date).getTime()},connect.find=function(e,t){for(var n=0;n1},connect.fetch=function(e,t,n,o){return o=o||5,n=n||1e3,t=t||{},new Promise((function(r,i){!function o(s){fetch(e,t).then((function(e){e.status===connect.HTTP_STATUS_CODES.SUCCESS?e.json().then((function(e){return r(e)})).catch((function(){return r({})})):1!==s&&(e.status>=connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout((function(){o(--s)}),n):i(e)})).catch((function(e){i(e)}))}(o)}))},connect.backoff=function(e,n,o,r){connect.assertTrue(connect.isFunction(e),"func must be a Function");var i=this;e({success:function(e){r&&r.success&&r.success(e)},failure:function(s,c){if(o>0){var a=2*n*Math.random();t.setTimeout((function(){i.backoff(e,2*a,--o,r)}),a)}else r&&r.failure&&r.failure(s,c)}})},connect.publishMetric=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.CLIENT_METRIC,data:e})},connect.publishSoftphoneStats=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.SOFTPHONE_STATS,data:e})},connect.publishSoftphoneReport=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.SOFTPHONE_REPORT,data:e})},connect.publishClientSideLogs=function(e){connect.core.getEventBus().trigger(connect.EventType.CLIENT_SIDE_LOGS,e)},connect.PopupManager=function(){},connect.PopupManager.prototype.open=function(e,t,n){var o=this._getLastOpenedTimestamp(t),r=(new Date).getTime(),i=null;if(r-o>864e5){if(n){var s=n.height||578,c=n.width||433,a=n.top||0,u=n.left||0;(i=window.open("",t,"width="+c+", height="+s+", top="+a+", left="+u)).location!==e&&(i=window.open(e,t,"width="+c+", height="+s+", top="+a+", left="+u))}else(i=window.open("",t)).location!==e&&(i=window.open(e,t));this._setLastOpenedTimestamp(t,r)}return i},connect.PopupManager.prototype.clear=function(e){var n=this._getLocalStorageKey(e);t.localStorage.removeItem(n)},connect.PopupManager.prototype._getLastOpenedTimestamp=function(e){var n=this._getLocalStorageKey(e),o=t.localStorage.getItem(n);return o?parseInt(o,10):0},connect.PopupManager.prototype._setLastOpenedTimestamp=function(e,n){var o=this._getLocalStorageKey(e);t.localStorage.setItem(o,""+n)},connect.PopupManager.prototype._getLocalStorageKey=function(e){return"connectPopupManager::"+e};var r=connect.makeEnum(["granted","denied","default"]);connect.NotificationManager=function(){this.queue=[],this.permission=r.DEFAULT},connect.NotificationManager.prototype.requestPermission=function(){var e=this;"Notification"in t?t.Notification.permission===r.DENIED?(connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(),this.permission=r.DENIED):this.permission!==r.GRANTED&&t.Notification.requestPermission().then((function(t){e.permission=t,t===r.GRANTED?e._showQueued():e.queue=[]})):(connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(),this.permission=r.DENIED)},connect.NotificationManager.prototype.show=function(e,t){if(this.permission===r.GRANTED)return this._showImpl({title:e,options:t});if(this.permission===r.DENIED)connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({title:e,options:t});else{var n={title:e,options:t};connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(n).sendInternalLogToServer(),this.queue.push(n)}},connect.NotificationManager.prototype._showQueued=function(){var e=this,t=this.queue.map((function(t){return e._showImpl(t)}));return this.queue=[],t},connect.NotificationManager.prototype._showImpl=function(e){var n=new t.Notification(e.title,e.options);return e.options.clicked&&(n.onclick=function(){e.options.clicked.call(n)}),n},connect.BaseError=function(e,n){t.Error.call(this,connect.vsprintf(e,n))},connect.BaseError.prototype=Object.create(Error.prototype),connect.BaseError.prototype.constructor=connect.BaseError,connect.ValueError=function(){var e=Array.prototype.slice.call(arguments,0),t=e.shift();connect.BaseError.call(this,t,e)},connect.ValueError.prototype=Object.create(connect.BaseError.prototype),connect.ValueError.prototype.constructor=connect.ValueError,connect.NotImplementedError=function(){var e=Array.prototype.slice.call(arguments,0),t=e.shift();connect.BaseError.call(this,t,e)},connect.NotImplementedError.prototype=Object.create(connect.BaseError.prototype),connect.NotImplementedError.prototype.constructor=connect.NotImplementedError,connect.StateError=function(){var e=Array.prototype.slice.call(arguments,0),t=e.shift();connect.BaseError.call(this,t,e)},connect.StateError.prototype=Object.create(connect.BaseError.prototype),connect.StateError.prototype.constructor=connect.StateError,connect.VoiceIdError=function(e,t,n){var o={};return o.type=e,o.message=t,o.stack=Error(t).stack,o.err=n,o},connect.isCCP=function(){return"ConnectSharedWorkerConduit"===connect.core.getUpstream().name}}()},744:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect,connect.worker={};var t=function(){this.topicMasterMap={}};t.prototype.getMaster=function(e){return connect.assertNotNull(e,"topic"),this.topicMasterMap[e]||null},t.prototype.setMaster=function(e,t){connect.assertNotNull(e,"topic"),connect.assertNotNull(t,"id"),this.topicMasterMap[e]=t},t.prototype.removeMaster=function(e){connect.assertNotNull(e,"id");var t=this;connect.entries(this.topicMasterMap).filter((function(t){return t.value===e})).forEach((function(e){delete t.topicMasterMap[e.key]}))};var n=function(e){connect.ClientBase.call(this),this.conduit=e};(n.prototype=Object.create(connect.ClientBase.prototype)).constructor=n,n.prototype._callImpl=function(e,t,n){var o=this,r=(new Date).getTime();connect.containsValue(connect.AgentAppClientMethods,e)?connect.core.getAgentAppClient()._callImpl(e,t,{success:function(t){o._recordAPILatency(e,r),n.success(t)},failure:function(t){o._recordAPILatency(e,r,t),n.failure(t)}}):connect.core.getClient()._callImpl(e,t,{success:function(t){o._recordAPILatency(e,r),n.success(t)},failure:function(t,i){o._recordAPILatency(e,r,t),n.failure(t,i)},authFailure:function(){o._recordAPILatency(e,r),n.authFailure()},accessDenied:function(){n.accessDenied&&n.accessDenied()}})},n.prototype._recordAPILatency=function(e,t,n){var o=(new Date).getTime()-t;this._sendAPIMetrics(e,o,n)},n.prototype._sendAPIMetrics=function(e,t,n){this.conduit.sendDownstream(connect.EventType.API_METRIC,{name:e,time:t,dimensions:[{name:"Category",value:"API"}],error:n})};var o=function(){var o=this;this.multiplexer=new connect.StreamMultiplexer,this.conduit=new connect.Conduit("AmazonConnectSharedWorker",null,this.multiplexer),this.client=new n(this.conduit),this.timeout=null,this.agent=null,this.nextToken=null,this.initData={},this.portConduitMap={},this.masterCoord=new t,this.logsBuffer=[],this.suppress=!1,this.forceOffline=!1;var r=null;connect.rootLogger=new connect.DownstreamConduitLogger(this.conduit),this.conduit.onDownstream(connect.EventType.SEND_LOGS,(function(e){connect.getLog().pushLogsDownstream(e),o.logsBuffer=o.logsBuffer.concat(e),o.logsBuffer.length>400&&o.handleSendLogsRequest(o.logsBuffer)})),this.conduit.onDownstream(connect.EventType.CONFIGURE,(function(t){t.authToken&&t.authToken!==o.initData.authToken&&(o.initData=t,connect.core.init(t),r?connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),connect.WebSocketManager.setGlobalConfig({loggerConfig:{logger:connect.getLog()}}),(r=connect.WebSocketManager.create()).onInitFailure((function(){o.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE)})),r.onConnectionOpen((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN,e)})),r.onConnectionClose((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE,e)})),r.onConnectionGain((function(){o.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED),o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN)})),r.onConnectionLost((function(e){o.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST,e)})),r.onSubscriptionUpdate((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE,e)})),r.onSubscriptionFailure((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE,e)})),r.onAllMessage((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE,e)})),o.conduit.onDownstream(connect.WebSocketEvents.SEND,(function(e){r.sendMessage(e)})),o.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE,(function(e){r.subscribeTopics(e)})),r.init(connect.hitch(o,o.getWebSocketUrl)).then((function(t){t&&!t.webSocketConnectionFailed?(connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(),o.pollForAgent(),connect.getLog().info("Kicking off config polling").sendInternalLogToServer(),o.pollForAgentConfiguration({repeatForever:!0}),connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),e.setInterval(connect.hitch(o,o.checkAuthToken),3e5)):connect.webSocketInitFailed||(o.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE),connect.webSocketInitFailed=!0)}))))})),this.conduit.onDownstream(connect.EventType.TERMINATE,(function(){o.handleSendLogsRequest(o.logsBuffer),connect.core.terminate(),o.conduit.sendDownstream(connect.EventType.TERMINATED)})),this.conduit.onDownstream(connect.EventType.SYNCHRONIZE,(function(){o.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE)})),this.conduit.onDownstream(connect.EventType.BROADCAST,(function(e){o.conduit.sendDownstream(e.event,e.data)})),e.onconnect=function(e){var t=e.ports[0],n=new connect.PortStream(t);o.multiplexer.addStream(n),t.start();var r=new connect.Conduit(n.getId(),null,n);r.sendDownstream(connect.EventType.ACKNOWLEDGE,{id:n.getId()}),o.portConduitMap[n.getId()]=r,o.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length}),null!==o.agent&&o.updateAgent(),r.onDownstream(connect.EventType.API_REQUEST,connect.hitch(o,o.handleAPIRequest,r)),r.onDownstream(connect.EventType.MASTER_REQUEST,connect.hitch(o,o.handleMasterRequest,r,n.getId())),r.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION,connect.hitch(o,o.pollForAgentConfiguration)),r.onDownstream(connect.EventType.CLOSE,(function(){o.multiplexer.removeStream(n),delete o.portConduitMap[n.getId()],o.masterCoord.removeMaster(n.getId()),o.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length})}))}};o.prototype.pollForAgent=function(){var t=this,n=connect.hitch(t,t.handleAuthFail);this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:t.nextToken,timeout:3e4},{success:function(n){try{t.agent=t.agent||{},t.agent.snapshot=n.snapshot,t.agent.snapshot.localTimestamp=connect.now(),t.agent.snapshot.skew=t.agent.snapshot.snapshotTimestamp-t.agent.snapshot.localTimestamp,t.nextToken=n.nextToken,connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(n).sendInternalLogToServer(),t.updateAgent()}catch(e){connect.getLog().error("Long poll failed to update agent.").withObject(n).withException(e).sendInternalLogToServer()}finally{e.setTimeout(connect.hitch(t,t.pollForAgent),100)}},failure:function(n,o){try{connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:n,data:o})}finally{e.setTimeout(connect.hitch(t,t.pollForAgent),5e3)}},authFailure:function(){n()},accessDenied:connect.hitch(t,t.handleAccessDenied)})},o.prototype.pollForAgentConfiguration=function(t){var n=this,o=t||{},r=connect.hitch(n,n.handleAuthFail);this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(t){var r=t.configuration;n.pollForAgentPermissions(r),n.pollForAgentStates(r),n.pollForDialableCountryCodes(r),n.pollForRoutingProfileQueues(r),o.repeatForever&&e.setTimeout(connect.hitch(n,n.pollForAgentConfiguration,o),3e4)},failure:function(t,r){try{connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:t,data:r})}finally{o.repeatForever&&e.setTimeout(connect.hitch(n,n.pollForAgentConfiguration),3e4,o)}},authFailure:function(){r()},accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentStates=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForAgentStates(e,{states:(o.states||[]).concat(t.states),nextToken:t.nextToken,maxResults:o.maxResults}):(e.agentStates=(o.states||[]).concat(t.states),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentPermissions=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForAgentPermissions(e,{permissions:(o.permissions||[]).concat(t.permissions),nextToken:t.nextToken,maxResults:o.maxResults}):(e.permissions=(o.permissions||[]).concat(t.permissions),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForDialableCountryCodes=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForDialableCountryCodes(e,{countryCodes:(o.countryCodes||[]).concat(t.countryCodes),nextToken:t.nextToken,maxResults:o.maxResults}):(e.dialableCountries=(o.countryCodes||[]).concat(t.countryCodes),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForRoutingProfileQueues=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:e.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForRoutingProfileQueues(e,{countryCodes:(o.queues||[]).concat(t.queues),nextToken:t.nextToken,maxResults:o.maxResults}):(e.routingProfile.queues=(o.queues||[]).concat(t.queues),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.handleAPIRequest=function(e,t){var n=this;this.client.call(t.method,t.params,{success:function(n){var o=connect.EventFactory.createResponse(connect.EventType.API_RESPONSE,t,n);e.sendDownstream(o.event,o)},failure:function(o,r){var i=connect.EventFactory.createResponse(connect.EventType.API_RESPONSE,t,r,JSON.stringify(o));e.sendDownstream(i.event,i),connect.getLog().error("'%s' API request failed",t.method).withObject({request:n.filterAuthToken(t),response:i}).withException(o).sendInternalLogToServer()},authFailure:connect.hitch(n,n.handleAuthFail)})},o.prototype.handleMasterRequest=function(e,t,n){var o=this.conduit,r=null;switch(n.method){case connect.MasterMethods.BECOME_MASTER:var i=this.masterCoord.getMaster(n.params.topic),s=Boolean(i)&&i!==t;this.masterCoord.setMaster(n.params.topic,t),r=connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE,n,{masterId:t,takeOver:s,topic:n.params.topic}),s&&o.sendDownstream(r.event,r);break;case connect.MasterMethods.CHECK_MASTER:(i=this.masterCoord.getMaster(n.params.topic))||n.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(n.params.topic,t),i=t),r=connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE,n,{masterId:i,isMaster:t===i,topic:n.params.topic});break;default:throw new Error("Unknown master method: "+n.method)}e.sendDownstream(r.event,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()):connect.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(connect.AgentEvents.UPDATE,this.agent)):connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer():connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer():connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer()},o.prototype.getWebSocketUrl=function(){var e=this,t=connect.core.getClient(),n=connect.hitch(e,e.handleAuthFail),o=connect.hitch(e,e.handleAccessDenied);return new Promise((function(e,r){t.call(connect.ClientMethods.CREATE_TRANSPORT,{transportType:connect.TRANSPORT_TYPES.WEB_SOCKET},{success:function(t){connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(),e(t)},failure:function(e,t){connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({err:e,data:t}),r({reason:"getWebSocketUrl failed",_debug:e})},authFailure:function(){connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(),r(Error("Authentication failed while getting getWebSocketUrl")),n()},accessDenied:function(){connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(),r(Error("Access Denied Failure while getting getWebSocketUrl")),o()}})}))},o.prototype.handleSendLogsRequest=function(){var e=this,t=[],n=e.logsBuffer.slice();e.logsBuffer=[],n.forEach((function(e){t.push({timestamp:e.time,component:e.component,message:e.text})})),this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS,{logEvents:t},{success:function(e){connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer()},failure:function(e,t){connect.getLog().error("SendLogs request failed.").withObject(t).withException(e).sendInternalLogToServer()},authFailure:connect.hitch(e,e.handleAuthFail)})},o.prototype.handleAuthFail=function(){this.conduit.sendDownstream(connect.EventType.AUTH_FAIL)},o.prototype.handleAccessDenied=function(){this.conduit.sendDownstream(connect.EventType.ACCESS_DENIED)},o.prototype.checkAuthToken=function(){var e=this,t=new Date(e.initData.authTokenExpiration),n=(new Date).getTime();t.getTime() { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 340: +/***/ (() => { + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + connect.agentApp = {}; + var APP = { + CCP: 'ccp' + }; + connect.agentApp.initCCP = connect.core.initCCP; + connect.agentApp.isInitialized = function (instanceAlias) {}; + connect.agentApp.initAppCommunication = function (iframeId, endpoint) { + var iframe = document.getElementById(iframeId); + var iframeConduit = new connect.IFrameConduit(endpoint, window, iframe); + var BROADCAST_TYPE = [connect.AgentEvents.UPDATE, connect.ContactEvents.VIEW, connect.EventType.ACKNOWLEDGE, connect.EventType.TERMINATED, connect.TaskEvents.CREATED]; + iframe.addEventListener('load', function (e) { + BROADCAST_TYPE.forEach(function (type) { + connect.core.getUpstream().onUpstream(type, function (data) { + iframeConduit.sendUpstream(type, data); + }); + }); + }); + }; + var getConnectUrl = function getConnectUrl(ccpUrl) { + var pos = ccpUrl.indexOf('ccp-v2'); + return ccpUrl.slice(0, pos - 1); + }; + var signOutThroughCCP = function signOutThroughCCP(ccpUrl) { + var logoutUrl = getConnectUrl(ccpUrl) + '/logout'; + return connect.fetch(logoutUrl, { + credentials: 'include' + }).then(function () { + var eventBus = connect.core.getEventBus(); + eventBus.trigger(connect.EventType.TERMINATE); + return true; + })["catch"](function (e) { + connect.getLog().error('An error occured on logout.' + e).withException(e); + window.location.href = logoutUrl; + return false; + }); + }; + var signInThroughinitCCP = function signInThroughinitCCP(ccpUrl, container, config) { + var defaultParams = { + ccpUrl: ccpUrl, + ccpLoadTimeout: 10000, + loginPopup: true, + loginUrl: getConnectUrl(ccpUrl) + '/login', + softphone: { + allowFramedSoftphone: true, + disableRingtone: false } - }, - "TagResource": { - "input": { - "type": "structure", - "required": [ - "ResourceArn" - ], - "members": { - "ResourceArn": {}, - "Tags": { - "shape": "Sg" - } + }; + var ccpParams = connect.merge(defaultParams, config.ccpParams); + connect.core.initCCP(container, ccpParams); + }; + connect.agentApp.initApp = function (name, containerId, appUrl, config) { + config = config ? config : {}; + var endpoint = appUrl.endsWith('/') ? appUrl : appUrl + '/'; + var onLoad = config.onLoad ? config.onLoad : null; + var registerConfig = { + endpoint: endpoint, + style: config.style, + onLoad: onLoad + }; + connect.agentApp.AppRegistry.register(name, registerConfig, document.getElementById(containerId)); + connect.agentApp.AppRegistry.start(name, function (moduleData) { + var endpoint = moduleData.endpoint; + var containerDOM = moduleData.containerDOM; + return { + init: function init() { + if (name === APP.CCP) return signInThroughinitCCP(endpoint, containerDOM, config); + return connect.agentApp.initAppCommunication(name, endpoint); + }, + destroy: function destroy() { + if (name === APP.CCP) return signOutThroughCCP(endpoint); + return null; } + }; + }); + }; + connect.agentApp.stopApp = function (name) { + return connect.agentApp.AppRegistry.stop(name); + }; +})(); + +/***/ }), + +/***/ 228: +/***/ (() => { + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + var APP = { + CCP: 'ccp' + }; + function AppRegistry() { + var moduleData = {}; + var makeAppIframe = function makeAppIframe(appName, endpoint, style, onLoad) { + var iframe = document.createElement('iframe'); + iframe.src = endpoint; + iframe.style = style || 'width: 100%; height:100%;'; + iframe.id = appName; + iframe['aria-label'] = appName; + iframe.onload = onLoad; + iframe.setAttribute("sandbox", "allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"); + // TODO: Update sandbox option for 3P widget + + return iframe; + }; + return { + register: function register(appName, config, containerDOM) { + moduleData[appName] = { + containerDOM: containerDOM, + endpoint: config.endpoint, + style: config.style, + instance: undefined, + onLoad: config.onLoad + }; }, - "output": { - "type": "structure", - "members": {} - } - }, - "UnlinkDeveloperIdentity": { - "input": { - "type": "structure", - "required": [ - "IdentityId", - "IdentityPoolId", - "DeveloperProviderName", - "DeveloperUserIdentifier" - ], - "members": { - "IdentityId": {}, - "IdentityPoolId": {}, - "DeveloperProviderName": {}, - "DeveloperUserIdentifier": {} - } - } - }, - "UnlinkIdentity": { - "input": { - "type": "structure", - "required": [ - "IdentityId", - "Logins", - "LoginsToRemove" - ], - "members": { - "IdentityId": {}, - "Logins": { - "shape": "Sz" - }, - "LoginsToRemove": { - "shape": "Sv" - } - } - } - }, - "UntagResource": { - "input": { - "type": "structure", - "required": [ - "ResourceArn" - ], - "members": { - "ResourceArn": {}, - "TagKeys": { - "type": "list", - "member": {} - } + start: function start(appName, creator) { + if (!moduleData[appName]) return; + var containerDOM = moduleData[appName].containerDOM; + var endpoint = moduleData[appName].endpoint; + var style = moduleData[appName].style; + var onLoad = moduleData[appName].onLoad; + if (appName !== APP.CCP) { + var app = makeAppIframe(appName, endpoint, style, onLoad); + containerDOM.appendChild(app); } + moduleData[appName].instance = creator(moduleData[appName]); + return moduleData[appName].instance.init(); }, - "output": { - "type": "structure", - "members": {} - } - }, - "UpdateIdentityPool": { - "input": { - "shape": "Sj" - }, - "output": { - "shape": "Sj" - } - } - }, - "shapes": { - "S4": { - "type": "map", - "key": {}, - "value": {} - }, - "S8": { - "type": "list", - "member": {} - }, - "Sa": { - "type": "list", - "member": { - "type": "structure", - "members": { - "ProviderName": {}, - "ClientId": {}, - "ServerSideTokenCheck": { - "type": "boolean" - } - } - } - }, - "Sf": { - "type": "list", - "member": {} - }, - "Sg": { - "type": "map", - "key": {}, - "value": {} - }, - "Sj": { - "type": "structure", - "required": [ - "IdentityPoolId", - "IdentityPoolName", - "AllowUnauthenticatedIdentities" - ], - "members": { - "IdentityPoolId": {}, - "IdentityPoolName": {}, - "AllowUnauthenticatedIdentities": { - "type": "boolean" - }, - "SupportedLoginProviders": { - "shape": "S4" - }, - "DeveloperProviderName": {}, - "OpenIdConnectProviderARNs": { - "shape": "S8" - }, - "CognitoIdentityProviders": { - "shape": "Sa" - }, - "SamlProviderARNs": { - "shape": "Sf" - }, - "IdentityPoolTags": { - "shape": "Sg" + stop: function stop(appName) { + if (!moduleData[appName]) return; + var data = moduleData[appName]; + var app = data.containerDOM.querySelector('iframe'); + data.containerDOM.removeChild(app); + var result; + if (data.instance) { + result = data.instance.destroy(); + delete data.instance; } + return result; } - }, - "Su": { - "type": "structure", - "members": { - "IdentityId": {}, - "Logins": { - "shape": "Sv" - }, - "CreationDate": { - "type": "timestamp" - }, - "LastModifiedDate": { - "type": "timestamp" - } - } - }, - "Sv": { - "type": "list", - "member": {} - }, - "Sz": { - "type": "map", - "key": {}, - "value": {} - }, - "S1b": { - "type": "map", - "key": {}, - "value": {} - }, - "S1d": { - "type": "map", - "key": {}, - "value": { - "type": "structure", - "required": [ - "Type" - ], - "members": { - "Type": {}, - "AmbiguousRoleResolution": {}, - "RulesConfiguration": { - "type": "structure", - "required": [ - "Rules" - ], - "members": { - "Rules": { - "type": "list", - "member": { - "type": "structure", - "required": [ - "Claim", - "MatchType", - "Value", - "RoleARN" - ], - "members": { - "Claim": {}, - "MatchType": {}, - "Value": {}, - "RoleARN": {} - } - } - } - } - } - } - } - } - } -} -},{}],2:[function(require,module,exports){ -module.exports={ - "pagination": { + }; } -} - -},{}],3:[function(require,module,exports){ -module.exports={ - "version": "2.0", - "metadata": { - "apiVersion": "2017-02-15", - "endpointPrefix": "connect", - "jsonVersion": "1.0", - "protocol": "json", - "serviceAbbreviation": "Connect", - "serviceFullName": "AmazonConnectCTIService", - "signatureVersion": "", - "targetPrefix": "AmazonConnectCTIService", - "uid": "connect-2017-02-15" - }, - "operations": { - "AcceptContact": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {} - } - }, - "output": { - "type": "structure", - "members": {} + global.connect.agentApp.AppRegistry = AppRegistry(); +})(); + +/***/ }), + +/***/ 35: +/***/ (() => { + +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + + /*---------------------------------------------------------------- + * enum AgentStateType + */ + connect.AgentStateType = connect.makeEnum(['init', 'routable', 'not_routable', 'offline']); + connect.AgentStatusType = connect.AgentStateType; + + /** + * enum AgentAvailStates + */ + connect.AgentAvailStates = connect.makeEnum(['Init', 'Busy', 'AfterCallWork', 'CallingCustomer', 'Dialing', 'Joining', 'PendingAvailable', 'PendingBusy']); + + /** + * enum AgentErrorStates + */ + connect.AgentErrorStates = connect.makeEnum(['Error', 'AgentHungUp', 'BadAddressAgent', 'BadAddressCustomer', 'Default', 'FailedConnectAgent', 'FailedConnectCustomer', 'InvalidLocale', 'LineEngagedAgent', 'LineEngagedCustomer', 'MissedCallAgent', 'MissedCallCustomer', 'MultipleCcpWindows', 'RealtimeCommunicationError']); + + /*---------------------------------------------------------------- + * enum AddressType + */ + connect.EndpointType = connect.makeEnum(['phone_number', 'agent', 'queue']); + connect.AddressType = connect.EndpointType; + + /*---------------------------------------------------------------- + * enum ConnectionType + */ + connect.ConnectionType = connect.makeEnum(['agent', 'inbound', 'outbound', 'monitoring']); + + /*---------------------------------------------------------------- + * enum ConnectionStateType + */ + connect.ConnectionStateType = connect.makeEnum(['init', 'connecting', 'connected', 'hold', 'disconnected']); + connect.ConnectionStatusType = connect.ConnectionStateType; + connect.CONNECTION_ACTIVE_STATES = connect.set([connect.ConnectionStateType.CONNECTING, connect.ConnectionStateType.CONNECTED, connect.ConnectionStateType.HOLD]); + + /*---------------------------------------------------------------- + * enum ContactStateType + */ + connect.ContactStateType = connect.makeEnum(['init', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'error', 'ended']); + connect.ContactStatusType = connect.ContactStateType; + connect.CONTACT_ACTIVE_STATES = connect.makeEnum(['incoming', 'pending', 'connecting', 'connected']); + + /*---------------------------------------------------------------- + * enum ContactType + */ + connect.ContactType = connect.makeEnum(['voice', 'queue_callback', 'chat', 'task']); + + /*---------------------------------------------------------------- + * enum ContactInitiationMethod + */ + connect.ContactInitiationMethod = connect.makeEnum(['inbound', 'outbound', 'transfer', 'queue_transfer', 'callback', 'api', 'disconnect']); + + /*---------------------------------------------------------------- + * enum ChannelType + */ + connect.ChannelType = connect.makeEnum(['VOICE', 'CHAT', 'TASK']); + + /*---------------------------------------------------------------- + * enum MediaType + */ + connect.MediaType = connect.makeEnum(['softphone', 'chat', 'task']); + + /*---------------------------------------------------------------- + * enum SoftphoneCallType + */ + connect.SoftphoneCallType = connect.makeEnum(['audio_video', 'video_only', 'audio_only', 'none']); + + /*---------------------------------------------------------------- + * enum for SoftphoneErrorTypes + */ + connect.SoftphoneErrorTypes = connect.makeEnum(['unsupported_browser', 'microphone_not_shared', 'signalling_handshake_failure', 'signalling_connection_failure', 'ice_collection_timeout', 'user_busy_error', 'webrtc_error', 'realtime_communication_error', 'other']); + + /*---------------------------------------------------------------- + * enum for VoiceIdErrorTypes + */ + connect.VoiceIdErrorTypes = connect.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']); + + /*---------------------------------------------------------------- + * enum for CTI exceptions + */ + connect.CTIExceptions = connect.makeEnum(["AccessDeniedException", "InvalidStateException", "BadEndpointException", "InvalidAgentARNException", "InvalidConfigurationException", "InvalidContactTypeException", "PaginationException", "RefreshTokenExpiredException", "SendDataFailedException", "UnauthorizedException", "QuotaExceededException"]); + /*---------------------------------------------------------------- + * enum for VoiceId streaming status + */ + connect.VoiceIdStreamingStatus = connect.makeEnum(["ONGOING", "ENDED", "PENDING_CONFIGURATION"]); + + /*---------------------------------------------------------------- + * enum for VoiceId authentication decision + */ + connect.VoiceIdAuthenticationDecision = connect.makeEnum(["ACCEPT", "REJECT", "NOT_ENOUGH_SPEECH", "SPEAKER_NOT_ENROLLED", "SPEAKER_OPTED_OUT", "SPEAKER_ID_NOT_PROVIDED", "SPEAKER_EXPIRED"]); + + /*---------------------------------------------------------------- + * enum for VoiceId fraud detection decision + */ + connect.VoiceIdFraudDetectionDecision = connect.makeEnum(["NOT_ENOUGH_SPEECH", "HIGH_RISK", "LOW_RISK"]); + + /*---------------------------------------------------------------- + * enum for contact flow authentication decision + */ + connect.ContactFlowAuthenticationDecision = connect.makeEnum(["Authenticated", "NotAuthenticated", "Inconclusive", "NotEnrolled", "OptedOut", "NotEnabled", "Error"]); + + /*---------------------------------------------------------------- + * enum for contact flow fraud detection decision + */ + connect.ContactFlowFraudDetectionDecision = connect.makeEnum(["HighRisk", "LowRisk", "Inconclusive", "NotEnabled", "Error"]); + + /*---------------------------------------------------------------- + * enum for VoiceId EnrollmentRequest Status + */ + connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum(["NOT_ENOUGH_SPEECH", "IN_PROGRESS", "COMPLETED", "FAILED"]); + + /*---------------------------------------------------------------- + * enum for VoiceId Speaker status + */ + connect.VoiceIdSpeakerStatus = connect.makeEnum(["OPTED_OUT", "ENROLLED", "PENDING"]); + connect.VoiceIdConstants = { + EVALUATE_SESSION_DELAY: 10000, + EVALUATION_MAX_POLL_TIMES: 24, + // EvaluateSpeaker is Polling for maximum 2 mins. + EVALUATION_POLLING_INTERVAL: 5000, + ENROLLMENT_MAX_POLL_TIMES: 120, + // EnrollmentSpeaker is Polling for maximum 10 mins. + ENROLLMENT_POLLING_INTERVAL: 5000, + START_SESSION_DELAY: 8000 + }; + + /*---------------------------------------------------------------- + * constants for AgentPermissions + */ + connect.AgentPermissions = { + OUTBOUND_CALL: 'outboundCall', + VOICE_ID: 'voiceId' + }; + + /*---------------------------------------------------------------- + * class Agent + */ + var Agent = function Agent() { + if (!connect.agent.initialized) { + throw new connect.StateError("The agent is not yet initialized!"); + } + }; + Agent.prototype._getData = function () { + return connect.core.getAgentDataProvider().getAgentData(); + }; + Agent.prototype._createContactAPI = function (contactData) { + return new connect.Contact(contactData.contactId); + }; + + /** + * @deprecated + * Use `contact.onPending` for any particular contact instead. + */ + Agent.prototype.onContactPending = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.CONTACT_PENDING, f); + }; + Agent.prototype.onRefresh = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.REFRESH, f); + }; + Agent.prototype.onRoutable = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ROUTABLE, f); + }; + Agent.prototype.onNotRoutable = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.NOT_ROUTABLE, f); + }; + Agent.prototype.onOffline = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.OFFLINE, f); + }; + Agent.prototype.onError = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ERROR, f); + }; + Agent.prototype.onSoftphoneError = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.SOFTPHONE_ERROR, f); + }; + Agent.prototype.onWebSocketConnectionLost = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, f); + }; + Agent.prototype.onWebSocketConnectionGained = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED, f); + }; + Agent.prototype.onAfterCallWork = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ACW, f); + }; + Agent.prototype.onStateChange = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.STATE_CHANGE, f); + }; + Agent.prototype.onMuteToggle = function (f) { + connect.core.getUpstream().onUpstream(connect.AgentEvents.MUTE_TOGGLE, f); + }; + Agent.prototype.onLocalMediaStreamCreated = function (f) { + connect.core.getUpstream().onUpstream(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, f); + }; + Agent.prototype.onSpeakerDeviceChanged = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, f); + }; + Agent.prototype.onMicrophoneDeviceChanged = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, f); + }; + Agent.prototype.onRingerDeviceChanged = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, f); + }; + Agent.prototype.mute = function () { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.MUTE, + data: { + mute: true } - }, - "ClearContact": { - "input": { - "type": "structure", - "required": [ - "contactId" - ], - "members": { - "contactId": {} - } - }, - "output": { - "type": "structure", - "members": {} + }); + }; + Agent.prototype.unmute = function () { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.MUTE, + data: { + mute: false } - }, - "CompleteContact": { - "input": { - "type": "structure", - "required": [ - "contactId" - ], - "members": { - "contactId": {} - } - }, - "output": { - "type": "structure", - "members": {} + }); + }; + Agent.prototype.setSpeakerDevice = function (deviceId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SET_SPEAKER_DEVICE, + data: { + deviceId: deviceId } - }, - "ConferenceConnections": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {} - } - }, - "output": { - "type": "structure", - "members": {} + }); + }; + Agent.prototype.setMicrophoneDevice = function (deviceId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, + data: { + deviceId: deviceId } - }, - "CreateAdditionalConnection": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "endpoint" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "endpoint": { - "shape": "Se" - } - } - }, - "output": { - "type": "structure", - "members": {} + }); + }; + Agent.prototype.setRingerDevice = function (deviceId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SET_RINGER_DEVICE, + data: { + deviceId: deviceId } - }, - "CreateOutboundContact": { - "input": { - "type": "structure", - "required": [ - "authentication", - "endpoint" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "endpoint": { - "shape": "Se" - }, - "queueARN": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "CreateTaskContact": { - "input": { - "type": "structure", - "required": [ - "endpoint", - "name" - ], - "members": { - "endpoint": { - "shape": "Se" - }, - "previousContactId": {}, - "name": {}, - "description": {}, - "references": { - "shape": "Sr" - }, - "idempotencyToken": {}, - "scheduledTime": { - "type": "long" - } - } - }, - "output": { - "type": "structure", - "members": { - "contactId": {} - } - } - }, - "CreateTransport": { - "input": { - "type": "structure", - "required": [ - "transportType", - "authentication" - ], - "members": { - "transportType": {}, - "participantId": {}, - "contactId": {}, - "softphoneClientId": {}, - "authentication": { - "shape": "S2" - } - } - }, - "output": { - "type": "structure", - "members": { - "webSocketTransport": { - "type": "structure", - "required": [ - "url", - "transportLifeTimeInSeconds" - ], - "members": { - "url": {}, - "transportLifeTimeInSeconds": { - "type": "long" - }, - "expiry": {} - } - }, - "chatTokenTransport": { - "type": "structure", - "required": [ - "participantToken", - "expiry" - ], - "members": { - "participantToken": {}, - "expiry": {} - } - }, - "softphoneTransport": { - "type": "structure", - "required": [ - "softphoneMediaConnections" - ], - "members": { - "softphoneMediaConnections": { - "type": "list", - "member": { - "type": "structure", - "required": [ - "username", - "credential", - "urls" - ], - "members": { - "username": {}, - "credential": {}, - "urls": { - "type": "list", - "member": {} - } - } - } - } - } - } - } - } - }, - "DestroyConnection": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "GetAgentConfiguration": { - "input": { - "type": "structure", - "required": [ - "authentication" - ], - "members": { - "authentication": { - "shape": "S2" - } - } - }, - "output": { - "type": "structure", - "required": [ - "configuration" - ], - "members": { - "configuration": { - "shape": "S1h" - } - } - } - }, - "GetAgentPermissions": { - "input": { - "type": "structure", - "required": [ - "authentication" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "nextToken": {}, - "maxResults": { - "type": "integer" - } - } - }, - "output": { - "type": "structure", - "required": [ - "permissions" - ], - "members": { - "permissions": { - "type": "list", - "member": {} - }, - "nextToken": {} - } - } - }, - "GetAgentSnapshot": { - "input": { - "type": "structure", - "required": [ - "authentication" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "nextToken": {}, - "timeout": { - "type": "long" - } - } - }, - "output": { - "type": "structure", - "required": [ - "snapshot", - "nextToken" - ], - "members": { - "snapshot": { - "type": "structure", - "required": [ - "state", - "contacts", - "snapshotTimestamp" - ], - "members": { - "state": { - "shape": "S20" - }, - "nextState": { - "shape": "S20" - }, - "agentAvailabilityState": { - "type": "structure", - "members": { - "state": {}, - "timeStamp": { - "type": "timestamp" - } - } - }, - "contacts": { - "type": "list", - "member": { - "type": "structure", - "required": [ - "contactId", - "type", - "state", - "connections", - "attributes" - ], - "members": { - "contactId": {}, - "initialContactId": {}, - "type": {}, - "state": { - "type": "structure", - "required": [ - "type", - "timestamp" - ], - "members": { - "type": {}, - "timestamp": { - "type": "timestamp" - } - } - }, - "queue": { - "shape": "Sk" - }, - "queueTimestamp": { - "type": "timestamp" - }, - "connections": { - "type": "list", - "member": { - "type": "structure", - "required": [ - "connectionId", - "state", - "type", - "initial" - ], - "members": { - "connectionId": {}, - "endpoint": { - "shape": "Se" - }, - "state": { - "type": "structure", - "required": [ - "type", - "timestamp" - ], - "members": { - "type": {}, - "timestamp": { - "type": "timestamp" - } - } - }, - "type": {}, - "initial": { - "type": "boolean" - }, - "softphoneMediaInfo": { - "type": "structure", - "members": { - "callType": {}, - "autoAccept": { - "type": "boolean" - }, - "mediaLegContextToken": {}, - "callContextToken": {}, - "callConfigJson": {} - } - }, - "chatMediaInfo": { - "type": "structure", - "members": { - "chatAutoAccept": { - "type": "boolean" - }, - "connectionData": {}, - "customerName": {} - } - }, - "monitoringInfo": { - "type": "structure", - "members": { - "agent": { - "type": "structure", - "members": { - "agentName": {} - } - }, - "joinTimeStamp": { - "type": "timestamp" - } - } - }, - "mute": { - "type": "boolean" - }, - "quickConnectName": {} - } - } - }, - "attributes": { - "type": "map", - "key": {}, - "value": { - "type": "structure", - "required": [ - "name" - ], - "members": { - "name": {}, - "value": {} - } - } - }, - "contactDuration": {}, - "name": {}, - "description": {}, - "references": { - "shape": "Sr" - }, - "initiationMethod": {}, - "contactFeatures": { - "type": "structure", - "members": { - "attachmentsEnabled": { - "type": "boolean" - } - } - } - } - } - }, - "snapshotTimestamp": { - "type": "timestamp" - } - } - }, - "nextToken": {} - } - } - }, - "GetAgentStates": { - "input": { - "type": "structure", - "required": [ - "authentication" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "nextToken": {}, - "maxResults": { - "type": "integer" - } - } - }, - "output": { - "type": "structure", - "required": [ - "states" - ], - "members": { - "states": { - "type": "list", - "member": { - "shape": "S20" - } - }, - "nextToken": {} - } - } - }, - "GetDialableCountryCodes": { - "input": { - "type": "structure", - "required": [ - "authentication" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "nextToken": {}, - "maxResults": { - "type": "integer" - } - } - }, - "output": { - "type": "structure", - "required": [ - "countryCodes" - ], - "members": { - "countryCodes": { - "type": "list", - "member": {} - }, - "nextToken": {} - } - } - }, - "GetEndpoints": { - "input": { - "type": "structure", - "required": [ - "authentication", - "queueARNs" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "queueARNs": { - "type": "list", - "member": {} - }, - "nextToken": {}, - "maxResults": { - "type": "integer" - } - } - }, - "output": { - "type": "structure", - "members": { - "endpoints": { - "type": "list", - "member": { - "shape": "Se" - } - }, - "nextToken": {} - } - } - }, - "GetNewAuthToken": { - "input": { - "type": "structure", - "required": [ - "authentication", - "refreshToken" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "refreshToken": {} - } - }, - "output": { - "type": "structure", - "members": { - "newAuthToken": {}, - "expirationDateTime": { - "type": "timestamp" - } - } - } - }, - "GetRoutingProfileQueues": { - "input": { - "type": "structure", - "required": [ - "authentication", - "routingProfileARN" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "routingProfileARN": {}, - "nextToken": {}, - "maxResults": { - "type": "integer" - } - } - }, - "output": { - "type": "structure", - "required": [ - "queues" - ], - "members": { - "queues": { - "type": "list", - "member": { - "shape": "Sk" - } - }, - "nextToken": {} - } - } - }, - "HoldConnection": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "MuteParticipant": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "NotifyContactIssue": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "issueCode": {}, - "description": {}, - "clientLogs": {} + }); + }; + Agent.prototype.getState = function () { + return this._getData().snapshot.state; + }; + Agent.prototype.getNextState = function () { + return this._getData().snapshot.nextState; + }; + Agent.prototype.getAvailabilityState = function () { + return this._getData().snapshot.agentAvailabilityState; + }; + Agent.prototype.getStatus = Agent.prototype.getState; + Agent.prototype.getStateDuration = function () { + return connect.now() - this._getData().snapshot.state.startTimestamp.getTime() + connect.core.getSkew(); + }; + Agent.prototype.getStatusDuration = Agent.prototype.getStateDuration; + Agent.prototype.getPermissions = function () { + return this.getConfiguration().permissions; + }; + Agent.prototype.getContacts = function (contactTypeFilter) { + var self = this; + return this._getData().snapshot.contacts.map(function (contactData) { + return self._createContactAPI(contactData); + }).filter(function (contact) { + return !contactTypeFilter || contact.getType() === contactTypeFilter; + }); + }; + Agent.prototype.getConfiguration = function () { + return this._getData().configuration; + }; + Agent.prototype.getAgentStates = function () { + return this.getConfiguration().agentStates; + }; + Agent.prototype.getRoutingProfile = function () { + return this.getConfiguration().routingProfile; + }; + Agent.prototype.getChannelConcurrency = function (channel) { + var channelConcurrencyMap = this.getRoutingProfile().channelConcurrencyMap; + if (!channelConcurrencyMap) { + channelConcurrencyMap = Object.keys(connect.ChannelType).reduce(function (acc, key) { + // Exclude TASK from default concurrency. + if (key !== 'TASK') { + acc[connect.ChannelType[key]] = 1; } - }, - "output": { - "type": "structure", - "members": {} + return acc; + }, {}); + } + return channel ? channelConcurrencyMap[channel] || 0 : channelConcurrencyMap; + }; + Agent.prototype.getName = function () { + return this.getConfiguration().name; + }; + Agent.prototype.getExtension = function () { + return this.getConfiguration().extension; + }; + Agent.prototype.getDialableCountries = function () { + return this.getConfiguration().dialableCountries; + }; + Agent.prototype.isSoftphoneEnabled = function () { + return this.getConfiguration().softphoneEnabled; + }; + Agent.prototype.setConfiguration = function (configuration, callbacks) { + var client = connect.core.getClient(); + if (configuration && configuration.agentPreferences && !connect.isValidLocale(configuration.agentPreferences.locale)) { + if (callbacks && callbacks.failure) { + callbacks.failure(connect.AgentErrorStates.INVALID_LOCALE); } - }, - "PutAgentState": { - "input": { - "type": "structure", - "required": [ - "authentication", - "state" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "state": { - "shape": "S20" - }, - "enqueueNextState": { - "type": "boolean" + } else { + client.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION, { + configuration: connect.assertNotNull(configuration, 'configuration') + }, { + success: function success(data) { + // We need to ask the shared worker to reload agent config + // once we change it so every tab has accurate config. + var conduit = connect.core.getUpstream(); + conduit.sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION); + if (callbacks.success) { + callbacks.success(data); } + }, + failure: callbacks && callbacks.failure + }); + } + }; + Agent.prototype.setState = function (state, callbacks, options) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.PUT_AGENT_STATE, { + state: connect.assertNotNull(state, 'state'), + enqueueNextState: options && !!options.enqueueNextState + }, callbacks); + }; + Agent.prototype.onEnqueuedNextState = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE, f); + }; + Agent.prototype.setStatus = Agent.prototype.setState; + Agent.prototype.connect = function (endpointIn, params) { + var client = connect.core.getClient(); + var endpoint = new connect.Endpoint(endpointIn); + // Have to remove the endpointId field or AWS JS SDK gets mad. + delete endpoint.endpointId; + client.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT, { + endpoint: connect.assertNotNull(endpoint, 'endpoint'), + queueARN: params && (params.queueARN || params.queueId) || this.getRoutingProfile().defaultOutboundQueue.queueARN + }, params && { + success: params.success, + failure: params.failure + }); + }; + Agent.prototype.getAllQueueARNs = function () { + return this.getConfiguration().routingProfile.queues.map(function (queue) { + return queue.queueARN; + }); + }; + Agent.prototype.getEndpoints = function (queueARNs, callbacks, pageInfoIn) { + var self = this; + var client = connect.core.getClient(); + connect.assertNotNull(callbacks, "callbacks"); + connect.assertNotNull(callbacks.success, "callbacks.success"); + var pageInfo = pageInfoIn || {}; + pageInfo.endpoints = pageInfo.endpoints || []; + pageInfo.maxResults = pageInfo.maxResults || connect.DEFAULT_BATCH_SIZE; + + // Backwards compatibility allowing a single queueARN to be specified + // instead of an array. + if (!connect.isArray(queueARNs)) { + queueARNs = [queueARNs]; + } + client.call(connect.ClientMethods.GET_ENDPOINTS, { + queueARNs: queueARNs, + nextToken: pageInfo.nextToken || null, + maxResults: pageInfo.maxResults + }, { + success: function success(data) { + if (data.nextToken) { + self.getEndpoints(queueARNs, callbacks, { + nextToken: data.nextToken, + maxResults: pageInfo.maxResults, + endpoints: pageInfo.endpoints.concat(data.endpoints) + }); + } else { + pageInfo.endpoints = pageInfo.endpoints.concat(data.endpoints); + var endpoints = pageInfo.endpoints.map(function (endpoint) { + return new connect.Endpoint(endpoint); + }); + callbacks.success({ + endpoints: endpoints, + addresses: endpoints + }); } }, - "output": { - "type": "structure", - "members": {} - } - }, - "RejectContact": { - "input": { - "type": "structure", - "required": [ - "contactId" - ], - "members": { - "contactId": {} + failure: callbacks.failure + }); + }; + Agent.prototype.getAddresses = Agent.prototype.getEndpoints; + + //Internal identifier. + Agent.prototype._getResourceId = function () { + queueArns = this.getAllQueueARNs(); + var _iterator = _createForOfIteratorHelper(queueArns), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var queueArn = _step.value; + var agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); + if (agentIdMatch) { + return agentIdMatch[1]; } - }, - "output": { - "type": "structure", - "members": {} } - }, - "ResumeConnection": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "SendClientLogs": { - "input": { - "type": "structure", - "required": [ - "authentication", - "logEvents" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "logEvents": { - "type": "list", - "member": { - "type": "structure", - "members": { - "timestamp": { - "type": "timestamp" - }, - "component": {}, - "message": {} - } - } - } - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "SendDigits": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId", - "digits" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {}, - "digits": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "SendSoftphoneCallMetrics": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "softphoneStreamStatistics" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "ccpVersion": {}, - "softphoneStreamStatistics": { - "shape": "S3r" - } - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "SendSoftphoneCallReport": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "report" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "ccpVersion": {}, - "report": { - "type": "structure", - "members": { - "callStartTime": { - "type": "timestamp" - }, - "callEndTime": { - "type": "timestamp" - }, - "softphoneStreamStatistics": { - "shape": "S3r" - }, - "gumTimeMillis": { - "type": "long" - }, - "initializationTimeMillis": { - "type": "long" - }, - "iceCollectionTimeMillis": { - "type": "long" - }, - "signallingConnectTimeMillis": { - "type": "long" - }, - "handshakeTimeMillis": { - "type": "long" - }, - "preTalkTimeMillis": { - "type": "long" - }, - "talkTimeMillis": { - "type": "long" - }, - "cleanupTimeMillis": { - "type": "long" - }, - "iceCollectionFailure": { - "type": "boolean" - }, - "signallingConnectionFailure": { - "type": "boolean" - }, - "handshakeFailure": { - "type": "boolean" - }, - "gumOtherFailure": { - "type": "boolean" - }, - "gumTimeoutFailure": { - "type": "boolean" - }, - "createOfferFailure": { - "type": "boolean" - }, - "setLocalDescriptionFailure": { - "type": "boolean" - }, - "userBusyFailure": { - "type": "boolean" - }, - "invalidRemoteSDPFailure": { - "type": "boolean" - }, - "noRemoteIceCandidateFailure": { - "type": "boolean" - }, - "setRemoteDescriptionFailure": { - "type": "boolean" - } - } - } - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "ToggleActiveConnections": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "UnmuteParticipant": { - "input": { - "type": "structure", - "required": [ - "authentication", - "contactId", - "connectionId" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "contactId": {}, - "connectionId": {} - } - }, - "output": { - "type": "structure", - "members": {} - } - }, - "UpdateAgentConfiguration": { - "input": { - "type": "structure", - "required": [ - "authentication", - "configuration" - ], - "members": { - "authentication": { - "shape": "S2" - }, - "configuration": { - "shape": "S1h" - } - } - }, - "output": { - "type": "structure", - "members": {} - } - } - }, - "shapes": { - "S2": { - "type": "structure", - "members": { - "agentARN": {}, - "authToken": {} - } - }, - "Se": { - "type": "structure", - "required": [ - "type" - ], - "members": { - "endpointARN": {}, - "type": {}, - "name": {}, - "phoneNumber": {}, - "agentLogin": {}, - "queue": { - "shape": "Sk" - } - } - }, - "Sk": { - "type": "structure", - "members": { - "queueARN": {}, - "name": {} - } - }, - "Sr": { - "type": "map", - "key": {}, - "value": { - "type": "structure", - "required": [ - "value", - "type" - ], - "members": { - "value": {}, - "type": {} - } - } - }, - "S1h": { - "type": "structure", - "required": [ - "name", - "softphoneEnabled", - "softphoneAutoAccept", - "extension", - "routingProfile" - ], - "members": { - "name": {}, - "username": {}, - "softphoneEnabled": { - "type": "boolean" - }, - "softphoneAutoAccept": { - "type": "boolean" - }, - "extension": {}, - "routingProfile": { - "type": "structure", - "members": { - "name": {}, - "routingProfileARN": {}, - "defaultOutboundQueue": { - "shape": "Sk" - }, - "channelConcurrencyMap": { - "type": "map", - "key": {}, - "value": { - "type": "long" - } - } - } - }, - "agentPreferences": { - "type": "map", - "key": {}, - "value": {} - } - } - }, - "S20": { - "type": "structure", - "required": [ - "type", - "name" - ], - "members": { - "agentStateARN": {}, - "type": {}, - "name": {}, - "startTimestamp": { - "type": "timestamp" - } - } - }, - "S3r": { - "type": "list", - "member": { - "type": "structure", - "members": { - "timestamp": { - "type": "timestamp" - }, - "softphoneStreamType": {}, - "packetCount": { - "type": "long" - }, - "packetsLost": { - "type": "long" - }, - "audioLevel": { - "type": "double" - }, - "jitterBufferMillis": { - "type": "long" - }, - "roundTripTimeMillis": { - "type": "long" - } - } - } - } - } -} -},{}],4:[function(require,module,exports){ -module.exports={ - "acm": { - "name": "ACM", - "cors": true - }, - "apigateway": { - "name": "APIGateway", - "cors": true - }, - "applicationautoscaling": { - "prefix": "application-autoscaling", - "name": "ApplicationAutoScaling", - "cors": true - }, - "appstream": { - "name": "AppStream" - }, - "autoscaling": { - "name": "AutoScaling", - "cors": true - }, - "batch": { - "name": "Batch" - }, - "budgets": { - "name": "Budgets" - }, - "clouddirectory": { - "name": "CloudDirectory", - "versions": [ - "2016-05-10*" - ] - }, - "cloudformation": { - "name": "CloudFormation", - "cors": true - }, - "cloudfront": { - "name": "CloudFront", - "versions": [ - "2013-05-12*", - "2013-11-11*", - "2014-05-31*", - "2014-10-21*", - "2014-11-06*", - "2015-04-17*", - "2015-07-27*", - "2015-09-17*", - "2016-01-13*", - "2016-01-28*", - "2016-08-01*", - "2016-08-20*", - "2016-09-07*", - "2016-09-29*", - "2016-11-25*", - "2017-03-25*", - "2017-10-30*", - "2018-06-18*", - "2018-11-05*" - ], - "cors": true - }, - "cloudhsm": { - "name": "CloudHSM", - "cors": true - }, - "cloudsearch": { - "name": "CloudSearch" - }, - "cloudsearchdomain": { - "name": "CloudSearchDomain" - }, - "cloudtrail": { - "name": "CloudTrail", - "cors": true - }, - "cloudwatch": { - "prefix": "monitoring", - "name": "CloudWatch", - "cors": true - }, - "cloudwatchevents": { - "prefix": "events", - "name": "CloudWatchEvents", - "versions": [ - "2014-02-03*" - ], - "cors": true - }, - "cloudwatchlogs": { - "prefix": "logs", - "name": "CloudWatchLogs", - "cors": true - }, - "codebuild": { - "name": "CodeBuild", - "cors": true - }, - "codecommit": { - "name": "CodeCommit", - "cors": true - }, - "codedeploy": { - "name": "CodeDeploy", - "cors": true - }, - "codepipeline": { - "name": "CodePipeline", - "cors": true - }, - "cognitoidentity": { - "prefix": "cognito-identity", - "name": "CognitoIdentity", - "cors": true - }, - "cognitoidentityserviceprovider": { - "prefix": "cognito-idp", - "name": "CognitoIdentityServiceProvider", - "cors": true - }, - "cognitosync": { - "prefix": "cognito-sync", - "name": "CognitoSync", - "cors": true - }, - "configservice": { - "prefix": "config", - "name": "ConfigService", - "cors": true - }, - "connect": { - "name": "Connect", - "cors": true - }, - "cur": { - "name": "CUR", - "cors": true - }, - "datapipeline": { - "name": "DataPipeline" - }, - "devicefarm": { - "name": "DeviceFarm", - "cors": true - }, - "directconnect": { - "name": "DirectConnect", - "cors": true - }, - "directoryservice": { - "prefix": "ds", - "name": "DirectoryService" - }, - "discovery": { - "name": "Discovery" - }, - "dms": { - "name": "DMS" - }, - "dynamodb": { - "name": "DynamoDB", - "cors": true - }, - "dynamodbstreams": { - "prefix": "streams.dynamodb", - "name": "DynamoDBStreams", - "cors": true - }, - "ec2": { - "name": "EC2", - "versions": [ - "2013-06-15*", - "2013-10-15*", - "2014-02-01*", - "2014-05-01*", - "2014-06-15*", - "2014-09-01*", - "2014-10-01*", - "2015-03-01*", - "2015-04-15*", - "2015-10-01*", - "2016-04-01*", - "2016-09-15*" - ], - "cors": true - }, - "ecr": { - "name": "ECR", - "cors": true - }, - "ecs": { - "name": "ECS", - "cors": true - }, - "efs": { - "prefix": "elasticfilesystem", - "name": "EFS", - "cors": true - }, - "elasticache": { - "name": "ElastiCache", - "versions": [ - "2012-11-15*", - "2014-03-24*", - "2014-07-15*", - "2014-09-30*" - ], - "cors": true - }, - "elasticbeanstalk": { - "name": "ElasticBeanstalk", - "cors": true - }, - "elb": { - "prefix": "elasticloadbalancing", - "name": "ELB", - "cors": true - }, - "elbv2": { - "prefix": "elasticloadbalancingv2", - "name": "ELBv2", - "cors": true - }, - "emr": { - "prefix": "elasticmapreduce", - "name": "EMR", - "cors": true - }, - "es": { - "name": "ES" - }, - "elastictranscoder": { - "name": "ElasticTranscoder", - "cors": true - }, - "firehose": { - "name": "Firehose", - "cors": true - }, - "gamelift": { - "name": "GameLift", - "cors": true - }, - "glacier": { - "name": "Glacier" - }, - "health": { - "name": "Health" - }, - "iam": { - "name": "IAM", - "cors": true - }, - "importexport": { - "name": "ImportExport" - }, - "inspector": { - "name": "Inspector", - "versions": [ - "2015-08-18*" - ], - "cors": true - }, - "iot": { - "name": "Iot", - "cors": true - }, - "iotdata": { - "prefix": "iot-data", - "name": "IotData", - "cors": true - }, - "kinesis": { - "name": "Kinesis", - "cors": true - }, - "kinesisanalytics": { - "name": "KinesisAnalytics" - }, - "kms": { - "name": "KMS", - "cors": true - }, - "lambda": { - "name": "Lambda", - "cors": true - }, - "lexruntime": { - "prefix": "runtime.lex", - "name": "LexRuntime", - "cors": true - }, - "lightsail": { - "name": "Lightsail" - }, - "machinelearning": { - "name": "MachineLearning", - "cors": true - }, - "marketplacecommerceanalytics": { - "name": "MarketplaceCommerceAnalytics", - "cors": true - }, - "marketplacemetering": { - "prefix": "meteringmarketplace", - "name": "MarketplaceMetering" - }, - "mturk": { - "prefix": "mturk-requester", - "name": "MTurk", - "cors": true - }, - "mobileanalytics": { - "name": "MobileAnalytics", - "cors": true - }, - "opsworks": { - "name": "OpsWorks", - "cors": true - }, - "opsworkscm": { - "name": "OpsWorksCM" - }, - "organizations": { - "name": "Organizations" - }, - "pinpoint": { - "name": "Pinpoint" - }, - "polly": { - "name": "Polly", - "cors": true - }, - "rds": { - "name": "RDS", - "versions": [ - "2014-09-01*" - ], - "cors": true - }, - "redshift": { - "name": "Redshift", - "cors": true - }, - "rekognition": { - "name": "Rekognition", - "cors": true - }, - "resourcegroupstaggingapi": { - "name": "ResourceGroupsTaggingAPI" - }, - "route53": { - "name": "Route53", - "cors": true - }, - "route53domains": { - "name": "Route53Domains", - "cors": true - }, - "s3": { - "name": "S3", - "dualstackAvailable": true, - "cors": true - }, - "s3control": { - "name": "S3Control", - "dualstackAvailable": true - }, - "servicecatalog": { - "name": "ServiceCatalog", - "cors": true - }, - "ses": { - "prefix": "email", - "name": "SES", - "cors": true - }, - "shield": { - "name": "Shield" - }, - "simpledb": { - "prefix": "sdb", - "name": "SimpleDB" - }, - "sms": { - "name": "SMS" - }, - "snowball": { - "name": "Snowball" - }, - "sns": { - "name": "SNS", - "cors": true - }, - "sqs": { - "name": "SQS", - "cors": true - }, - "ssm": { - "name": "SSM", - "cors": true - }, - "storagegateway": { - "name": "StorageGateway", - "cors": true - }, - "stepfunctions": { - "prefix": "states", - "name": "StepFunctions" - }, - "sts": { - "name": "STS", - "cors": true - }, - "support": { - "name": "Support" - }, - "swf": { - "name": "SWF" - }, - "xray": { - "name": "XRay", - "cors": true - }, - "waf": { - "name": "WAF", - "cors": true - }, - "wafregional": { - "prefix": "waf-regional", - "name": "WAFRegional" - }, - "workdocs": { - "name": "WorkDocs", - "cors": true - }, - "workspaces": { - "name": "WorkSpaces" - }, - "codestar": { - "name": "CodeStar" - }, - "lexmodelbuildingservice": { - "prefix": "lex-models", - "name": "LexModelBuildingService", - "cors": true - }, - "marketplaceentitlementservice": { - "prefix": "entitlement.marketplace", - "name": "MarketplaceEntitlementService" - }, - "athena": { - "name": "Athena" - }, - "greengrass": { - "name": "Greengrass" - }, - "dax": { - "name": "DAX" - }, - "migrationhub": { - "prefix": "AWSMigrationHub", - "name": "MigrationHub" - }, - "cloudhsmv2": { - "name": "CloudHSMV2" - }, - "glue": { - "name": "Glue" - }, - "mobile": { - "name": "Mobile" - }, - "pricing": { - "name": "Pricing", - "cors": true - }, - "costexplorer": { - "prefix": "ce", - "name": "CostExplorer", - "cors": true - }, - "mediaconvert": { - "name": "MediaConvert" - }, - "medialive": { - "name": "MediaLive" - }, - "mediapackage": { - "name": "MediaPackage" - }, - "mediastore": { - "name": "MediaStore" - }, - "mediastoredata": { - "prefix": "mediastore-data", - "name": "MediaStoreData", - "cors": true - }, - "appsync": { - "name": "AppSync" - }, - "guardduty": { - "name": "GuardDuty" - }, - "mq": { - "name": "MQ" - }, - "comprehend": { - "name": "Comprehend", - "cors": true - }, - "iotjobsdataplane": { - "prefix": "iot-jobs-data", - "name": "IoTJobsDataPlane" - }, - "kinesisvideoarchivedmedia": { - "prefix": "kinesis-video-archived-media", - "name": "KinesisVideoArchivedMedia", - "cors": true - }, - "kinesisvideomedia": { - "prefix": "kinesis-video-media", - "name": "KinesisVideoMedia", - "cors": true - }, - "kinesisvideo": { - "name": "KinesisVideo", - "cors": true - }, - "sagemakerruntime": { - "prefix": "runtime.sagemaker", - "name": "SageMakerRuntime" - }, - "sagemaker": { - "name": "SageMaker" - }, - "translate": { - "name": "Translate", - "cors": true - }, - "resourcegroups": { - "prefix": "resource-groups", - "name": "ResourceGroups", - "cors": true - }, - "alexaforbusiness": { - "name": "AlexaForBusiness" - }, - "cloud9": { - "name": "Cloud9" - }, - "serverlessapplicationrepository": { - "prefix": "serverlessrepo", - "name": "ServerlessApplicationRepository" - }, - "servicediscovery": { - "name": "ServiceDiscovery" - }, - "workmail": { - "name": "WorkMail" - }, - "autoscalingplans": { - "prefix": "autoscaling-plans", - "name": "AutoScalingPlans" - }, - "transcribeservice": { - "prefix": "transcribe", - "name": "TranscribeService" - }, - "acmpca": { - "prefix": "acm-pca", - "name": "ACMPCA" - }, - "fms": { - "name": "FMS" - }, - "secretsmanager": { - "name": "SecretsManager", - "cors": true - }, - "iotanalytics": { - "name": "IoTAnalytics", - "cors": true - }, - "iot1clickdevicesservice": { - "prefix": "iot1click-devices", - "name": "IoT1ClickDevicesService" - }, - "iot1clickprojects": { - "prefix": "iot1click-projects", - "name": "IoT1ClickProjects" - }, - "pi": { - "name": "PI" - }, - "neptune": { - "name": "Neptune" - }, - "mediatailor": { - "name": "MediaTailor" - }, - "eks": { - "name": "EKS" - }, - "macie": { - "name": "Macie" - }, - "dlm": { - "name": "DLM" - }, - "signer": { - "name": "Signer" - }, - "chime": { - "name": "Chime" - }, - "pinpointemail": { - "prefix": "pinpoint-email", - "name": "PinpointEmail" - }, - "ram": { - "name": "RAM" - }, - "route53resolver": { - "name": "Route53Resolver" - }, - "pinpointsmsvoice": { - "prefix": "sms-voice", - "name": "PinpointSMSVoice" - }, - "quicksight": { - "name": "QuickSight" - }, - "rdsdataservice": { - "prefix": "rds-data", - "name": "RDSDataService" - }, - "amplify": { - "name": "Amplify" - }, - "datasync": { - "name": "DataSync" - }, - "robomaker": { - "name": "RoboMaker" - }, - "transfer": { - "name": "Transfer" - }, - "globalaccelerator": { - "name": "GlobalAccelerator" - }, - "comprehendmedical": { - "name": "ComprehendMedical", - "cors": true - }, - "kinesisanalyticsv2": { - "name": "KinesisAnalyticsV2" - }, - "mediaconnect": { - "name": "MediaConnect" - }, - "fsx": { - "name": "FSx" - }, - "securityhub": { - "name": "SecurityHub" - }, - "appmesh": { - "name": "AppMesh", - "versions": [ - "2018-10-01*" - ] - }, - "licensemanager": { - "prefix": "license-manager", - "name": "LicenseManager" - }, - "kafka": { - "name": "Kafka" - }, - "apigatewaymanagementapi": { - "name": "ApiGatewayManagementApi" - }, - "apigatewayv2": { - "name": "ApiGatewayV2" - }, - "docdb": { - "name": "DocDB" - }, - "backup": { - "name": "Backup" - }, - "worklink": { - "name": "WorkLink" - }, - "textract": { - "name": "Textract" - }, - "managedblockchain": { - "name": "ManagedBlockchain" - }, - "mediapackagevod": { - "prefix": "mediapackage-vod", - "name": "MediaPackageVod" - }, - "groundstation": { - "name": "GroundStation" - }, - "iotthingsgraph": { - "name": "IoTThingsGraph" - }, - "iotevents": { - "name": "IoTEvents" - }, - "ioteventsdata": { - "prefix": "iotevents-data", - "name": "IoTEventsData" - }, - "personalize": { - "name": "Personalize", - "cors": true - }, - "personalizeevents": { - "prefix": "personalize-events", - "name": "PersonalizeEvents", - "cors": true - }, - "personalizeruntime": { - "prefix": "personalize-runtime", - "name": "PersonalizeRuntime", - "cors": true - }, - "applicationinsights": { - "prefix": "application-insights", - "name": "ApplicationInsights" - }, - "servicequotas": { - "prefix": "service-quotas", - "name": "ServiceQuotas" - }, - "ec2instanceconnect": { - "prefix": "ec2-instance-connect", - "name": "EC2InstanceConnect" - }, - "eventbridge": { - "name": "EventBridge" - }, - "lakeformation": { - "name": "LakeFormation" - }, - "forecastservice": { - "prefix": "forecast", - "name": "ForecastService", - "cors": true - }, - "forecastqueryservice": { - "prefix": "forecastquery", - "name": "ForecastQueryService", - "cors": true - }, - "qldb": { - "name": "QLDB" - }, - "qldbsession": { - "prefix": "qldb-session", - "name": "QLDBSession" - }, - "workmailmessageflow": { - "name": "WorkMailMessageFlow" - } -} - -},{}],5:[function(require,module,exports){ -module.exports={ - "version": "2.0", - "metadata": { - "apiVersion": "2011-06-15", - "endpointPrefix": "sts", - "globalEndpoint": "sts.amazonaws.com", - "protocol": "query", - "serviceAbbreviation": "AWS STS", - "serviceFullName": "AWS Security Token Service", - "serviceId": "STS", - "signatureVersion": "v4", - "uid": "sts-2011-06-15", - "xmlNamespace": "https://sts.amazonaws.com/doc/2011-06-15/" - }, - "operations": { - "AssumeRole": { - "input": { - "type": "structure", - "required": [ - "RoleArn", - "RoleSessionName" - ], - "members": { - "RoleArn": {}, - "RoleSessionName": {}, - "PolicyArns": { - "shape": "S4" - }, - "Policy": {}, - "DurationSeconds": { - "type": "integer" - }, - "ExternalId": {}, - "SerialNumber": {}, - "TokenCode": {} - } - }, - "output": { - "resultWrapper": "AssumeRoleResult", - "type": "structure", - "members": { - "Credentials": { - "shape": "Sc" - }, - "AssumedRoleUser": { - "shape": "Sh" - }, - "PackedPolicySize": { - "type": "integer" - } - } - } - }, - "AssumeRoleWithSAML": { - "input": { - "type": "structure", - "required": [ - "RoleArn", - "PrincipalArn", - "SAMLAssertion" - ], - "members": { - "RoleArn": {}, - "PrincipalArn": {}, - "SAMLAssertion": {}, - "PolicyArns": { - "shape": "S4" - }, - "Policy": {}, - "DurationSeconds": { - "type": "integer" - } - } - }, - "output": { - "resultWrapper": "AssumeRoleWithSAMLResult", - "type": "structure", - "members": { - "Credentials": { - "shape": "Sc" - }, - "AssumedRoleUser": { - "shape": "Sh" - }, - "PackedPolicySize": { - "type": "integer" - }, - "Subject": {}, - "SubjectType": {}, - "Issuer": {}, - "Audience": {}, - "NameQualifier": {} - } - } - }, - "AssumeRoleWithWebIdentity": { - "input": { - "type": "structure", - "required": [ - "RoleArn", - "RoleSessionName", - "WebIdentityToken" - ], - "members": { - "RoleArn": {}, - "RoleSessionName": {}, - "WebIdentityToken": {}, - "ProviderId": {}, - "PolicyArns": { - "shape": "S4" - }, - "Policy": {}, - "DurationSeconds": { - "type": "integer" - } - } - }, - "output": { - "resultWrapper": "AssumeRoleWithWebIdentityResult", - "type": "structure", - "members": { - "Credentials": { - "shape": "Sc" - }, - "SubjectFromWebIdentityToken": {}, - "AssumedRoleUser": { - "shape": "Sh" - }, - "PackedPolicySize": { - "type": "integer" - }, - "Provider": {}, - "Audience": {} - } - } - }, - "DecodeAuthorizationMessage": { - "input": { - "type": "structure", - "required": [ - "EncodedMessage" - ], - "members": { - "EncodedMessage": {} - } - }, - "output": { - "resultWrapper": "DecodeAuthorizationMessageResult", - "type": "structure", - "members": { - "DecodedMessage": {} - } - } - }, - "GetAccessKeyInfo": { - "input": { - "type": "structure", - "required": [ - "AccessKeyId" - ], - "members": { - "AccessKeyId": {} - } - }, - "output": { - "resultWrapper": "GetAccessKeyInfoResult", - "type": "structure", - "members": { - "Account": {} - } - } - }, - "GetCallerIdentity": { - "input": { - "type": "structure", - "members": {} - }, - "output": { - "resultWrapper": "GetCallerIdentityResult", - "type": "structure", - "members": { - "UserId": {}, - "Account": {}, - "Arn": {} - } - } - }, - "GetFederationToken": { - "input": { - "type": "structure", - "required": [ - "Name" - ], - "members": { - "Name": {}, - "Policy": {}, - "PolicyArns": { - "shape": "S4" - }, - "DurationSeconds": { - "type": "integer" - } - } - }, - "output": { - "resultWrapper": "GetFederationTokenResult", - "type": "structure", - "members": { - "Credentials": { - "shape": "Sc" - }, - "FederatedUser": { - "type": "structure", - "required": [ - "FederatedUserId", - "Arn" - ], - "members": { - "FederatedUserId": {}, - "Arn": {} - } - }, - "PackedPolicySize": { - "type": "integer" - } - } - } - }, - "GetSessionToken": { - "input": { - "type": "structure", - "members": { - "DurationSeconds": { - "type": "integer" - }, - "SerialNumber": {}, - "TokenCode": {} - } - }, - "output": { - "resultWrapper": "GetSessionTokenResult", - "type": "structure", - "members": { - "Credentials": { - "shape": "Sc" - } - } - } - } - }, - "shapes": { - "S4": { - "type": "list", - "member": { - "type": "structure", - "members": { - "arn": {} - } - } - }, - "Sc": { - "type": "structure", - "required": [ - "AccessKeyId", - "SecretAccessKey", - "SessionToken", - "Expiration" - ], - "members": { - "AccessKeyId": {}, - "SecretAccessKey": {}, - "SessionToken": {}, - "Expiration": { - "type": "timestamp" - } - } - }, - "Sh": { - "type": "structure", - "required": [ - "AssumedRoleId", - "Arn" - ], - "members": { - "AssumedRoleId": {}, - "Arn": {} - } - } - } -} -},{}],6:[function(require,module,exports){ -arguments[4][2][0].apply(exports,arguments) -},{"dup":2}],7:[function(require,module,exports){ -require('../lib/node_loader'); -var AWS = require('../lib/core'); -var Service = AWS.Service; -var apiLoader = AWS.apiLoader; - -apiLoader.services['cognitoidentity'] = {}; -AWS.CognitoIdentity = Service.defineService('cognitoidentity', ['2014-06-30']); -require('../lib/services/cognitoidentity'); -Object.defineProperty(apiLoader.services['cognitoidentity'], '2014-06-30', { - get: function get() { - var model = require('../apis/cognito-identity-2014-06-30.min.json'); - model.paginators = require('../apis/cognito-identity-2014-06-30.paginators.json').pagination; - return model; - }, - enumerable: true, - configurable: true -}); - -module.exports = AWS.CognitoIdentity; - -},{"../apis/cognito-identity-2014-06-30.min.json":1,"../apis/cognito-identity-2014-06-30.paginators.json":2,"../lib/core":18,"../lib/node_loader":16,"../lib/services/cognitoidentity":60}],8:[function(require,module,exports){ -require('../lib/node_loader'); -var AWS = require('../lib/core'); -var Service = AWS.Service; -var apiLoader = AWS.apiLoader; - -apiLoader.services['sts'] = {}; -AWS.STS = Service.defineService('sts', ['2011-06-15']); -require('../lib/services/sts'); -Object.defineProperty(apiLoader.services['sts'], '2011-06-15', { - get: function get() { - var model = require('../apis/sts-2011-06-15.min.json'); - model.paginators = require('../apis/sts-2011-06-15.paginators.json').pagination; - return model; - }, - enumerable: true, - configurable: true -}); - -module.exports = AWS.STS; - -},{"../apis/sts-2011-06-15.min.json":5,"../apis/sts-2011-06-15.paginators.json":6,"../lib/core":18,"../lib/node_loader":16,"../lib/services/sts":61}],9:[function(require,module,exports){ -function apiLoader(svc, version) { - if (!apiLoader.services.hasOwnProperty(svc)) { - throw new Error('InvalidService: Failed to load api for ' + svc); - } - return apiLoader.services[svc][version]; -} - -/** - * @api private - * - * This member of AWS.apiLoader is private, but changing it will necessitate a - * change to ../scripts/services-table-generator.ts - */ -apiLoader.services = {}; - -/** - * @api private - */ -module.exports = apiLoader; - -},{}],10:[function(require,module,exports){ -var Hmac = require('./browserHmac'); -var Md5 = require('./browserMd5'); -var Sha1 = require('./browserSha1'); -var Sha256 = require('./browserSha256'); - -/** - * @api private - */ -module.exports = exports = { - createHash: function createHash(alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') { - return new Md5(); - } else if (alg === 'sha256') { - return new Sha256(); - } else if (alg === 'sha1') { - return new Sha1(); - } - - throw new Error('Hash algorithm ' + alg + ' is not supported in the browser SDK'); - }, - createHmac: function createHmac(alg, key) { - alg = alg.toLowerCase(); - if (alg === 'md5') { - return new Hmac(Md5, key); - } else if (alg === 'sha256') { - return new Hmac(Sha256, key); - } else if (alg === 'sha1') { - return new Hmac(Sha1, key); - } - - throw new Error('HMAC algorithm ' + alg + ' is not supported in the browser SDK'); - }, - createSign: function() { - throw new Error('createSign is not implemented in the browser'); + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } + return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ", queueArns); + }; + Agent.prototype.toSnapshot = function () { + return new connect.AgentSnapshot(this._getData()); }; -},{"./browserHmac":12,"./browserMd5":13,"./browserSha1":14,"./browserSha256":15}],11:[function(require,module,exports){ -var Buffer = require('buffer/').Buffer; - -/** - * This is a polyfill for the static method `isView` of `ArrayBuffer`, which is - * e.g. missing in IE 10. - * - * @api private - */ -if ( - typeof ArrayBuffer !== 'undefined' && - typeof ArrayBuffer.isView === 'undefined' -) { - ArrayBuffer.isView = function(arg) { - return viewStrings.indexOf(Object.prototype.toString.call(arg)) > -1; - }; -} - -/** - * @api private - */ -var viewStrings = [ - '[object Int8Array]', - '[object Uint8Array]', - '[object Uint8ClampedArray]', - '[object Int16Array]', - '[object Uint16Array]', - '[object Int32Array]', - '[object Uint32Array]', - '[object Float32Array]', - '[object Float64Array]', - '[object DataView]', -]; - -/** - * @api private - */ -function isEmptyData(data) { - if (typeof data === 'string') { - return data.length === 0; - } - return data.byteLength === 0; -} - -/** - * @api private - */ -function convertToBuffer(data) { - if (typeof data === 'string') { - data = new Buffer(data, 'utf8'); - } - - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - - return new Uint8Array(data); -} - -/** - * @api private - */ -module.exports = exports = { - isEmptyData: isEmptyData, - convertToBuffer: convertToBuffer, -}; - -},{"buffer/":81}],12:[function(require,module,exports){ -var hashUtils = require('./browserHashUtils'); - -/** - * @api private - */ -function Hmac(hashCtor, secret) { - this.hash = new hashCtor(); - this.outer = new hashCtor(); - - var inner = bufferFromSecret(hashCtor, secret); - var outer = new Uint8Array(hashCtor.BLOCK_SIZE); - outer.set(inner); - - for (var i = 0; i < hashCtor.BLOCK_SIZE; i++) { - inner[i] ^= 0x36; - outer[i] ^= 0x5c; - } - - this.hash.update(inner); - this.outer.update(outer); - - // Zero out the copied key buffer. - for (var i = 0; i < inner.byteLength; i++) { - inner[i] = 0; - } -} - -/** - * @api private - */ -module.exports = exports = Hmac; + /*---------------------------------------------------------------- + * class AgentSnapshot + */ + var AgentSnapshot = function AgentSnapshot(agentData) { + connect.Agent.call(this); + this.agentData = agentData; + }; + AgentSnapshot.prototype = Object.create(Agent.prototype); + AgentSnapshot.prototype.constructor = AgentSnapshot; + AgentSnapshot.prototype._getData = function () { + return this.agentData; + }; + AgentSnapshot.prototype._createContactAPI = function (contactData) { + return new connect.ContactSnapshot(contactData); + }; -Hmac.prototype.update = function (toHash) { - if (hashUtils.isEmptyData(toHash) || this.error) { - return this; + /*---------------------------------------------------------------- + * class Contact + */ + var Contact = function Contact(contactId) { + this.contactId = contactId; + }; + Contact.prototype._getData = function () { + return connect.core.getAgentDataProvider().getContactData(this.getContactId()); + }; + Contact.prototype._createConnectionAPI = function (connectionData) { + if (this.getType() === connect.ContactType.CHAT) { + return new connect.ChatConnection(this.contactId, connectionData.connectionId); + } else if (this.getType() === connect.ContactType.TASK) { + return new connect.TaskConnection(this.contactId, connectionData.connectionId); + } else { + return new connect.VoiceConnection(this.contactId, connectionData.connectionId); } - - try { - this.hash.update(hashUtils.convertToBuffer(toHash)); - } catch (e) { - this.error = e; - } - - return this; -}; - -Hmac.prototype.digest = function (encoding) { - if (!this.outer.finished) { - this.outer.update(this.hash.digest()); - } - - return this.outer.digest(encoding); -}; - -function bufferFromSecret(hashCtor, secret) { - var input = hashUtils.convertToBuffer(secret); - if (input.byteLength > hashCtor.BLOCK_SIZE) { - var bufferHash = new hashCtor; - bufferHash.update(input); - input = bufferHash.digest(); - } - var buffer = new Uint8Array(hashCtor.BLOCK_SIZE); - buffer.set(input); - return buffer; -} - -},{"./browserHashUtils":11}],13:[function(require,module,exports){ -var hashUtils = require('./browserHashUtils'); -var Buffer = require('buffer/').Buffer; - -var BLOCK_SIZE = 64; - -var DIGEST_LENGTH = 16; - -var INIT = [ - 0x67452301, - 0xefcdab89, - 0x98badcfe, - 0x10325476, -]; - -/** - * @api private - */ -function Md5() { - this.state = [ - 0x67452301, - 0xefcdab89, - 0x98badcfe, - 0x10325476, - ]; - this.buffer = new DataView(new ArrayBuffer(BLOCK_SIZE)); - this.bufferLength = 0; - this.bytesHashed = 0; - this.finished = false; -} - -/** - * @api private - */ -module.exports = exports = Md5; - -Md5.BLOCK_SIZE = BLOCK_SIZE; - -Md5.prototype.update = function (sourceData) { - if (hashUtils.isEmptyData(sourceData)) { - return this; - } else if (this.finished) { - throw new Error('Attempted to update an already finished hash.'); - } - - var data = hashUtils.convertToBuffer(sourceData); - var position = 0; - var byteLength = data.byteLength; - this.bytesHashed += byteLength; - while (byteLength > 0) { - this.buffer.setUint8(this.bufferLength++, data[position++]); - byteLength--; - if (this.bufferLength === BLOCK_SIZE) { - this.hashBuffer(); - this.bufferLength = 0; - } - } - - return this; -}; - -Md5.prototype.digest = function (encoding) { - if (!this.finished) { - var _a = this, buffer = _a.buffer, undecoratedLength = _a.bufferLength, bytesHashed = _a.bytesHashed; - var bitsHashed = bytesHashed * 8; - buffer.setUint8(this.bufferLength++, 128); - // Ensure the final block has enough room for the hashed length - if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) { - for (var i = this.bufferLength; i < BLOCK_SIZE; i++) { - buffer.setUint8(i, 0); - } - this.hashBuffer(); - this.bufferLength = 0; - } - for (var i = this.bufferLength; i < BLOCK_SIZE - 8; i++) { - buffer.setUint8(i, 0); - } - buffer.setUint32(BLOCK_SIZE - 8, bitsHashed >>> 0, true); - buffer.setUint32(BLOCK_SIZE - 4, Math.floor(bitsHashed / 0x100000000), true); - this.hashBuffer(); - this.finished = true; - } - var out = new DataView(new ArrayBuffer(DIGEST_LENGTH)); - for (var i = 0; i < 4; i++) { - out.setUint32(i * 4, this.state[i], true); - } - var buff = new Buffer(out.buffer, out.byteOffset, out.byteLength); - return encoding ? buff.toString(encoding) : buff; -}; - -Md5.prototype.hashBuffer = function () { - var _a = this, buffer = _a.buffer, state = _a.state; - var a = state[0], b = state[1], c = state[2], d = state[3]; - a = ff(a, b, c, d, buffer.getUint32(0, true), 7, 0xd76aa478); - d = ff(d, a, b, c, buffer.getUint32(4, true), 12, 0xe8c7b756); - c = ff(c, d, a, b, buffer.getUint32(8, true), 17, 0x242070db); - b = ff(b, c, d, a, buffer.getUint32(12, true), 22, 0xc1bdceee); - a = ff(a, b, c, d, buffer.getUint32(16, true), 7, 0xf57c0faf); - d = ff(d, a, b, c, buffer.getUint32(20, true), 12, 0x4787c62a); - c = ff(c, d, a, b, buffer.getUint32(24, true), 17, 0xa8304613); - b = ff(b, c, d, a, buffer.getUint32(28, true), 22, 0xfd469501); - a = ff(a, b, c, d, buffer.getUint32(32, true), 7, 0x698098d8); - d = ff(d, a, b, c, buffer.getUint32(36, true), 12, 0x8b44f7af); - c = ff(c, d, a, b, buffer.getUint32(40, true), 17, 0xffff5bb1); - b = ff(b, c, d, a, buffer.getUint32(44, true), 22, 0x895cd7be); - a = ff(a, b, c, d, buffer.getUint32(48, true), 7, 0x6b901122); - d = ff(d, a, b, c, buffer.getUint32(52, true), 12, 0xfd987193); - c = ff(c, d, a, b, buffer.getUint32(56, true), 17, 0xa679438e); - b = ff(b, c, d, a, buffer.getUint32(60, true), 22, 0x49b40821); - a = gg(a, b, c, d, buffer.getUint32(4, true), 5, 0xf61e2562); - d = gg(d, a, b, c, buffer.getUint32(24, true), 9, 0xc040b340); - c = gg(c, d, a, b, buffer.getUint32(44, true), 14, 0x265e5a51); - b = gg(b, c, d, a, buffer.getUint32(0, true), 20, 0xe9b6c7aa); - a = gg(a, b, c, d, buffer.getUint32(20, true), 5, 0xd62f105d); - d = gg(d, a, b, c, buffer.getUint32(40, true), 9, 0x02441453); - c = gg(c, d, a, b, buffer.getUint32(60, true), 14, 0xd8a1e681); - b = gg(b, c, d, a, buffer.getUint32(16, true), 20, 0xe7d3fbc8); - a = gg(a, b, c, d, buffer.getUint32(36, true), 5, 0x21e1cde6); - d = gg(d, a, b, c, buffer.getUint32(56, true), 9, 0xc33707d6); - c = gg(c, d, a, b, buffer.getUint32(12, true), 14, 0xf4d50d87); - b = gg(b, c, d, a, buffer.getUint32(32, true), 20, 0x455a14ed); - a = gg(a, b, c, d, buffer.getUint32(52, true), 5, 0xa9e3e905); - d = gg(d, a, b, c, buffer.getUint32(8, true), 9, 0xfcefa3f8); - c = gg(c, d, a, b, buffer.getUint32(28, true), 14, 0x676f02d9); - b = gg(b, c, d, a, buffer.getUint32(48, true), 20, 0x8d2a4c8a); - a = hh(a, b, c, d, buffer.getUint32(20, true), 4, 0xfffa3942); - d = hh(d, a, b, c, buffer.getUint32(32, true), 11, 0x8771f681); - c = hh(c, d, a, b, buffer.getUint32(44, true), 16, 0x6d9d6122); - b = hh(b, c, d, a, buffer.getUint32(56, true), 23, 0xfde5380c); - a = hh(a, b, c, d, buffer.getUint32(4, true), 4, 0xa4beea44); - d = hh(d, a, b, c, buffer.getUint32(16, true), 11, 0x4bdecfa9); - c = hh(c, d, a, b, buffer.getUint32(28, true), 16, 0xf6bb4b60); - b = hh(b, c, d, a, buffer.getUint32(40, true), 23, 0xbebfbc70); - a = hh(a, b, c, d, buffer.getUint32(52, true), 4, 0x289b7ec6); - d = hh(d, a, b, c, buffer.getUint32(0, true), 11, 0xeaa127fa); - c = hh(c, d, a, b, buffer.getUint32(12, true), 16, 0xd4ef3085); - b = hh(b, c, d, a, buffer.getUint32(24, true), 23, 0x04881d05); - a = hh(a, b, c, d, buffer.getUint32(36, true), 4, 0xd9d4d039); - d = hh(d, a, b, c, buffer.getUint32(48, true), 11, 0xe6db99e5); - c = hh(c, d, a, b, buffer.getUint32(60, true), 16, 0x1fa27cf8); - b = hh(b, c, d, a, buffer.getUint32(8, true), 23, 0xc4ac5665); - a = ii(a, b, c, d, buffer.getUint32(0, true), 6, 0xf4292244); - d = ii(d, a, b, c, buffer.getUint32(28, true), 10, 0x432aff97); - c = ii(c, d, a, b, buffer.getUint32(56, true), 15, 0xab9423a7); - b = ii(b, c, d, a, buffer.getUint32(20, true), 21, 0xfc93a039); - a = ii(a, b, c, d, buffer.getUint32(48, true), 6, 0x655b59c3); - d = ii(d, a, b, c, buffer.getUint32(12, true), 10, 0x8f0ccc92); - c = ii(c, d, a, b, buffer.getUint32(40, true), 15, 0xffeff47d); - b = ii(b, c, d, a, buffer.getUint32(4, true), 21, 0x85845dd1); - a = ii(a, b, c, d, buffer.getUint32(32, true), 6, 0x6fa87e4f); - d = ii(d, a, b, c, buffer.getUint32(60, true), 10, 0xfe2ce6e0); - c = ii(c, d, a, b, buffer.getUint32(24, true), 15, 0xa3014314); - b = ii(b, c, d, a, buffer.getUint32(52, true), 21, 0x4e0811a1); - a = ii(a, b, c, d, buffer.getUint32(16, true), 6, 0xf7537e82); - d = ii(d, a, b, c, buffer.getUint32(44, true), 10, 0xbd3af235); - c = ii(c, d, a, b, buffer.getUint32(8, true), 15, 0x2ad7d2bb); - b = ii(b, c, d, a, buffer.getUint32(36, true), 21, 0xeb86d391); - state[0] = (a + state[0]) & 0xFFFFFFFF; - state[1] = (b + state[1]) & 0xFFFFFFFF; - state[2] = (c + state[2]) & 0xFFFFFFFF; - state[3] = (d + state[3]) & 0xFFFFFFFF; -}; - -function cmn(q, a, b, x, s, t) { - a = (((a + q) & 0xFFFFFFFF) + ((x + t) & 0xFFFFFFFF)) & 0xFFFFFFFF; - return (((a << s) | (a >>> (32 - s))) + b) & 0xFFFFFFFF; -} - -function ff(a, b, c, d, x, s, t) { - return cmn((b & c) | ((~b) & d), a, b, x, s, t); -} - -function gg(a, b, c, d, x, s, t) { - return cmn((b & d) | (c & (~d)), a, b, x, s, t); -} - -function hh(a, b, c, d, x, s, t) { - return cmn(b ^ c ^ d, a, b, x, s, t); -} - -function ii(a, b, c, d, x, s, t) { - return cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -},{"./browserHashUtils":11,"buffer/":81}],14:[function(require,module,exports){ -var Buffer = require('buffer/').Buffer; -var hashUtils = require('./browserHashUtils'); - -var BLOCK_SIZE = 64; - -var DIGEST_LENGTH = 20; - -var KEY = new Uint32Array([ - 0x5a827999, - 0x6ed9eba1, - 0x8f1bbcdc | 0, - 0xca62c1d6 | 0 -]); - -var INIT = [ - 0x6a09e667, - 0xbb67ae85, - 0x3c6ef372, - 0xa54ff53a, - 0x510e527f, - 0x9b05688c, - 0x1f83d9ab, - 0x5be0cd19, -]; - -var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1; - -/** - * @api private - */ -function Sha1() { - this.h0 = 0x67452301; - this.h1 = 0xEFCDAB89; - this.h2 = 0x98BADCFE; - this.h3 = 0x10325476; - this.h4 = 0xC3D2E1F0; - // The first 64 bytes (16 words) is the data chunk - this.block = new Uint32Array(80); - this.offset = 0; - this.shift = 24; - this.totalLength = 0; -} - -/** - * @api private - */ -module.exports = exports = Sha1; - -Sha1.BLOCK_SIZE = BLOCK_SIZE; - -Sha1.prototype.update = function (data) { - if (this.finished) { - throw new Error('Attempted to update an already finished hash.'); - } - - if (hashUtils.isEmptyData(data)) { - return this; - } - - data = hashUtils.convertToBuffer(data); - - var length = data.length; - this.totalLength += length * 8; - for (var i = 0; i < length; i++) { - this.write(data[i]); - } - - return this; -}; - -Sha1.prototype.write = function write(byte) { - this.block[this.offset] |= (byte & 0xff) << this.shift; - if (this.shift) { - this.shift -= 8; - } else { - this.offset++; - this.shift = 24; - } - - if (this.offset === 16) this.processBlock(); -}; - -Sha1.prototype.digest = function (encoding) { - // Pad - this.write(0x80); - if (this.offset > 14 || (this.offset === 14 && this.shift < 24)) { - this.processBlock(); - } - this.offset = 14; - this.shift = 24; - - // 64-bit length big-endian - this.write(0x00); // numbers this big aren't accurate in javascript anyway - this.write(0x00); // ..So just hard-code to zero. - this.write(this.totalLength > 0xffffffffff ? this.totalLength / 0x10000000000 : 0x00); - this.write(this.totalLength > 0xffffffff ? this.totalLength / 0x100000000 : 0x00); - for (var s = 24; s >= 0; s -= 8) { - this.write(this.totalLength >> s); - } - // The value in state is little-endian rather than big-endian, so flip - // each word into a new Uint8Array - var out = new Buffer(DIGEST_LENGTH); - var outView = new DataView(out.buffer); - outView.setUint32(0, this.h0, false); - outView.setUint32(4, this.h1, false); - outView.setUint32(8, this.h2, false); - outView.setUint32(12, this.h3, false); - outView.setUint32(16, this.h4, false); - - return encoding ? out.toString(encoding) : out; -}; - -Sha1.prototype.processBlock = function processBlock() { - // Extend the sixteen 32-bit words into eighty 32-bit words: - for (var i = 16; i < 80; i++) { - var w = this.block[i - 3] ^ this.block[i - 8] ^ this.block[i - 14] ^ this.block[i - 16]; - this.block[i] = (w << 1) | (w >>> 31); - } - - // Initialize hash value for this chunk: - var a = this.h0; - var b = this.h1; - var c = this.h2; - var d = this.h3; - var e = this.h4; - var f, k; - - // Main loop: - for (i = 0; i < 80; i++) { - if (i < 20) { - f = d ^ (b & (c ^ d)); - k = 0x5A827999; - } - else if (i < 40) { - f = b ^ c ^ d; - k = 0x6ED9EBA1; - } - else if (i < 60) { - f = (b & c) | (d & (b | c)); - k = 0x8F1BBCDC; - } - else { - f = b ^ c ^ d; - k = 0xCA62C1D6; + }; + Contact.prototype.getEventName = function (eventName) { + return connect.core.getContactEventName(eventName, this.getContactId()); + }; + Contact.prototype.onRefresh = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.REFRESH), f); + }; + Contact.prototype.onIncoming = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.INCOMING), f); + }; + Contact.prototype.onConnecting = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTING), f); + }; + Contact.prototype.onPending = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.PENDING), f); + }; + Contact.prototype.onAccepted = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ACCEPTED), f); + }; + Contact.prototype.onMissed = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.MISSED), f); + }; + Contact.prototype.onEnded = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ENDED), f); + bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); + }; + Contact.prototype.onDestroy = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); + }; + Contact.prototype.onACW = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ACW), f); + }; + Contact.prototype.onConnected = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTED), f); + }; + Contact.prototype.onError = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ERROR), f); + }; + Contact.prototype.getContactId = function () { + return this.contactId; + }; + Contact.prototype.getOriginalContactId = function () { + return this._getData().initialContactId; + }; + Contact.prototype.getInitialContactId = Contact.prototype.getOriginalContactId; + Contact.prototype.getType = function () { + return this._getData().type; + }; + Contact.prototype.getContactDuration = function () { + return this._getData().contactDuration; + }; + Contact.prototype.getState = function () { + return this._getData().state; + }; + Contact.prototype.getStatus = Contact.prototype.getState; + Contact.prototype.getStateDuration = function () { + return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); + }; + Contact.prototype.getStatusDuration = Contact.prototype.getStateDuration; + Contact.prototype.getQueue = function () { + return this._getData().queue; + }; + Contact.prototype.getQueueTimestamp = function () { + return this._getData().queueTimestamp; + }; + Contact.prototype.getConnections = function () { + var self = this; + return this._getData().connections.map(function (connData) { + if (self.getType() === connect.ContactType.CHAT) { + return new connect.ChatConnection(self.contactId, connData.connectionId); + } else if (self.getType() === connect.ContactType.TASK) { + return new connect.TaskConnection(self.contactId, connData.connectionId); + } else { + return new connect.VoiceConnection(self.contactId, connData.connectionId); } - var temp = (a << 5 | a >>> 27) + f + e + k + (this.block[i]|0); - e = d; - d = c; - c = (b << 30 | b >>> 2); - b = a; - a = temp; - } - - // Add this chunk's hash to result so far: - this.h0 = (this.h0 + a) | 0; - this.h1 = (this.h1 + b) | 0; - this.h2 = (this.h2 + c) | 0; - this.h3 = (this.h3 + d) | 0; - this.h4 = (this.h4 + e) | 0; - - // The block is now reusable. - this.offset = 0; - for (i = 0; i < 16; i++) { - this.block[i] = 0; - } -}; - -},{"./browserHashUtils":11,"buffer/":81}],15:[function(require,module,exports){ -var Buffer = require('buffer/').Buffer; -var hashUtils = require('./browserHashUtils'); - -var BLOCK_SIZE = 64; - -var DIGEST_LENGTH = 32; - -var KEY = new Uint32Array([ - 0x428a2f98, - 0x71374491, - 0xb5c0fbcf, - 0xe9b5dba5, - 0x3956c25b, - 0x59f111f1, - 0x923f82a4, - 0xab1c5ed5, - 0xd807aa98, - 0x12835b01, - 0x243185be, - 0x550c7dc3, - 0x72be5d74, - 0x80deb1fe, - 0x9bdc06a7, - 0xc19bf174, - 0xe49b69c1, - 0xefbe4786, - 0x0fc19dc6, - 0x240ca1cc, - 0x2de92c6f, - 0x4a7484aa, - 0x5cb0a9dc, - 0x76f988da, - 0x983e5152, - 0xa831c66d, - 0xb00327c8, - 0xbf597fc7, - 0xc6e00bf3, - 0xd5a79147, - 0x06ca6351, - 0x14292967, - 0x27b70a85, - 0x2e1b2138, - 0x4d2c6dfc, - 0x53380d13, - 0x650a7354, - 0x766a0abb, - 0x81c2c92e, - 0x92722c85, - 0xa2bfe8a1, - 0xa81a664b, - 0xc24b8b70, - 0xc76c51a3, - 0xd192e819, - 0xd6990624, - 0xf40e3585, - 0x106aa070, - 0x19a4c116, - 0x1e376c08, - 0x2748774c, - 0x34b0bcb5, - 0x391c0cb3, - 0x4ed8aa4a, - 0x5b9cca4f, - 0x682e6ff3, - 0x748f82ee, - 0x78a5636f, - 0x84c87814, - 0x8cc70208, - 0x90befffa, - 0xa4506ceb, - 0xbef9a3f7, - 0xc67178f2 -]); - -var INIT = [ - 0x6a09e667, - 0xbb67ae85, - 0x3c6ef372, - 0xa54ff53a, - 0x510e527f, - 0x9b05688c, - 0x1f83d9ab, - 0x5be0cd19, -]; - -var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1; - -/** - * @private - */ -function Sha256() { - this.state = [ - 0x6a09e667, - 0xbb67ae85, - 0x3c6ef372, - 0xa54ff53a, - 0x510e527f, - 0x9b05688c, - 0x1f83d9ab, - 0x5be0cd19, - ]; - this.temp = new Int32Array(64); - this.buffer = new Uint8Array(64); - this.bufferLength = 0; - this.bytesHashed = 0; - /** - * @private - */ - this.finished = false; -} - -/** - * @api private - */ -module.exports = exports = Sha256; - -Sha256.BLOCK_SIZE = BLOCK_SIZE; - -Sha256.prototype.update = function (data) { - if (this.finished) { - throw new Error('Attempted to update an already finished hash.'); - } - - if (hashUtils.isEmptyData(data)) { - return this; - } - - data = hashUtils.convertToBuffer(data); - - var position = 0; - var byteLength = data.byteLength; - this.bytesHashed += byteLength; - if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) { - throw new Error('Cannot hash more than 2^53 - 1 bits'); + }); + }; + Contact.prototype.getInitialConnection = function () { + return connect.find(this.getConnections(), function (conn) { + return conn.isInitialConnection(); + }) || null; + }; + Contact.prototype.getActiveInitialConnection = function () { + var initialConn = this.getInitialConnection(); + if (initialConn != null && initialConn.isActive()) { + return initialConn; + } else { + return null; } + }; + Contact.prototype.getThirdPartyConnections = function () { + return this.getConnections().filter(function (conn) { + return !conn.isInitialConnection() && conn.getType() !== connect.ConnectionType.AGENT; + }); + }; + Contact.prototype.getSingleActiveThirdPartyConnection = function () { + return this.getThirdPartyConnections().filter(function (conn) { + return conn.isActive(); + })[0] || null; + }; + Contact.prototype.getAgentConnection = function () { + return connect.find(this.getConnections(), function (conn) { + var connType = conn.getType(); + return connType === connect.ConnectionType.AGENT || connType === connect.ConnectionType.MONITORING; + }); + }; + Contact.prototype.getName = function () { + return this._getData().name; + }; + Contact.prototype.getContactMetadata = function () { + return this._getData().contactMetadata; + }; + Contact.prototype.getDescription = function () { + return this._getData().description; + }; + Contact.prototype.getReferences = function () { + return this._getData().references; + }; + Contact.prototype.getAttributes = function () { + return this._getData().attributes; + }; + Contact.prototype.getContactFeatures = function () { + return this._getData().contactFeatures; + }; + Contact.prototype.isSoftphoneCall = function () { + return connect.find(this.getConnections(), function (conn) { + return conn.getSoftphoneMediaInfo() != null; + }) != null; + }; + Contact.prototype._isInbound = function () { + var initiationMethod = this._getData().initiationMethod; + return initiationMethod === connect.ContactInitiationMethod.OUTBOUND ? false : true; + }; + Contact.prototype.isInbound = function () { + var conn = this.getInitialConnection(); - while (byteLength > 0) { - this.buffer[this.bufferLength++] = data[position++]; - byteLength--; - if (this.bufferLength === BLOCK_SIZE) { - this.hashBuffer(); - this.bufferLength = 0; - } + // We will gradually change checking inbound by relying on contact initiationMethod + if (conn.getMediaType() === connect.MediaType.TASK) { + return this._isInbound(); } + return conn ? conn.getType() === connect.ConnectionType.INBOUND : false; + }; + Contact.prototype.isConnected = function () { + return this.getStatus().type === connect.ContactStateType.CONNECTED; + }; + Contact.prototype.accept = function (callbacks) { + var client = connect.core.getClient(); + var self = this; + var contactId = this.getContactId(); + client.call(connect.ClientMethods.ACCEPT_CONTACT, { + contactId: contactId + }, { + success: function success(data) { + var conduit = connect.core.getUpstream(); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.ContactEvents.ACCEPTED, + data: new connect.Contact(contactId) + }); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, self.getContactId()), + data: new connect.Contact(contactId) + }); - return this; -}; - -Sha256.prototype.digest = function (encoding) { - if (!this.finished) { - var bitsHashed = this.bytesHashed * 8; - var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength); - var undecoratedLength = this.bufferLength; - bufferView.setUint8(this.bufferLength++, 0x80); - // Ensure the final block has enough room for the hashed length - if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) { - for (var i = this.bufferLength; i < BLOCK_SIZE; i++) { - bufferView.setUint8(i, 0); - } - this.hashBuffer(); - this.bufferLength = 0; + // In Firefox, there's a browser restriction that an unfocused browser tab is not allowed to access the user's microphone. + // The problem is that the restriction could cause a webrtc session creation timeout error when you get an incoming call while you are not on the primary tab. + // It was hard to workaround the issue especially when you have multiple tabs open because you needed to find the right tab and accept the contact before the timeout. + // To avoid the error, when multiple tabs are open in Firefox, a webrtc session is not immediately created as an incoming softphone contact is detected. + // Instead, it waits until contact.accept() is called on a tab and lets the tab become the new primary tab and start the web rtc session there + // because the tab should be focused at the moment and have access to the user's microphone. + var contact = new connect.Contact(contactId); + if (connect.isFirefoxBrowser() && contact.isSoftphoneCall()) { + connect.core.triggerReadyToStartSessionEvent(); } - for (var i = this.bufferLength; i < BLOCK_SIZE - 8; i++) { - bufferView.setUint8(i, 0); - } - bufferView.setUint32(BLOCK_SIZE - 8, Math.floor(bitsHashed / 0x100000000), true); - bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed); - this.hashBuffer(); - this.finished = true; - } - // The value in state is little-endian rather than big-endian, so flip - // each word into a new Uint8Array - var out = new Buffer(DIGEST_LENGTH); - for (var i = 0; i < 8; i++) { - out[i * 4] = (this.state[i] >>> 24) & 0xff; - out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff; - out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff; - out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff; - } - return encoding ? out.toString(encoding) : out; -}; - -Sha256.prototype.hashBuffer = function () { - var _a = this, - buffer = _a.buffer, - state = _a.state; - var state0 = state[0], - state1 = state[1], - state2 = state[2], - state3 = state[3], - state4 = state[4], - state5 = state[5], - state6 = state[6], - state7 = state[7]; - for (var i = 0; i < BLOCK_SIZE; i++) { - if (i < 16) { - this.temp[i] = (((buffer[i * 4] & 0xff) << 24) | - ((buffer[(i * 4) + 1] & 0xff) << 16) | - ((buffer[(i * 4) + 2] & 0xff) << 8) | - (buffer[(i * 4) + 3] & 0xff)); - } - else { - var u = this.temp[i - 2]; - var t1_1 = (u >>> 17 | u << 15) ^ - (u >>> 19 | u << 13) ^ - (u >>> 10); - u = this.temp[i - 15]; - var t2_1 = (u >>> 7 | u << 25) ^ - (u >>> 18 | u << 14) ^ - (u >>> 3); - this.temp[i] = (t1_1 + this.temp[i - 7] | 0) + - (t2_1 + this.temp[i - 16] | 0); + if (callbacks && callbacks.success) { + callbacks.success(data); } - var t1 = (((((state4 >>> 6 | state4 << 26) ^ - (state4 >>> 11 | state4 << 21) ^ - (state4 >>> 25 | state4 << 7)) - + ((state4 & state5) ^ (~state4 & state6))) | 0) - + ((state7 + ((KEY[i] + this.temp[i]) | 0)) | 0)) | 0; - var t2 = (((state0 >>> 2 | state0 << 30) ^ - (state0 >>> 13 | state0 << 19) ^ - (state0 >>> 22 | state0 << 10)) + ((state0 & state1) ^ (state0 & state2) ^ (state1 & state2))) | 0; - state7 = state6; - state6 = state5; - state5 = state4; - state4 = (state3 + t1) | 0; - state3 = state2; - state2 = state1; - state1 = state0; - state0 = (t1 + t2) | 0; - } - state[0] += state0; - state[1] += state1; - state[2] += state2; - state[3] += state3; - state[4] += state4; - state[5] += state5; - state[6] += state6; - state[7] += state7; -}; - -},{"./browserHashUtils":11,"buffer/":81}],16:[function(require,module,exports){ -(function (process){(function (){ -var util = require('./util'); - -// browser specific modules -util.crypto.lib = require('./browserCryptoLib'); -util.Buffer = require('buffer/').Buffer; -util.url = require('url/'); -util.querystring = require('querystring/'); -util.realClock = require('./realclock/browserClock'); -util.environment = 'js'; -util.createEventStream = require('./event-stream/buffered-create-event-stream').createEventStream; -util.isBrowser = function() { return true; }; -util.isNode = function() { return false; }; - -var AWS = require('./core'); - -/** - * @api private - */ -module.exports = AWS; + }, + failure: callbacks ? callbacks.failure : null + }); + }; + Contact.prototype.destroy = function () { + connect.getLog().warn("contact.destroy() has been deprecated."); + }; + Contact.prototype.reject = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.REJECT_CONTACT, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.complete = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.COMPLETE_CONTACT, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.clear = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.CLEAR_CONTACT, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.notifyIssue = function (issueCode, description, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE, { + contactId: this.getContactId(), + issueCode: issueCode, + description: description + }, callbacks); + }; + Contact.prototype.addConnection = function (endpointIn, callbacks) { + var client = connect.core.getClient(); + var endpoint = new connect.Endpoint(endpointIn); + // Have to remove the endpointId field or AWS JS SDK gets mad. + delete endpoint.endpointId; + client.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION, { + contactId: this.getContactId(), + endpoint: endpoint + }, callbacks); + }; + Contact.prototype.toggleActiveConnections = function (callbacks) { + var client = connect.core.getClient(); + var connectionId = null; + var holdingConn = connect.find(this.getConnections(), function (conn) { + return conn.getStatus().type === connect.ConnectionStateType.HOLD; + }); + if (holdingConn != null) { + connectionId = holdingConn.getConnectionId(); + } else { + var activeConns = this.getConnections().filter(function (conn) { + return conn.isActive(); + }); + if (activeConns.length > 0) { + connectionId = activeConns[0].getConnectionId(); + } + } + client.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS, { + contactId: this.getContactId(), + connectionId: connectionId + }, callbacks); + }; + Contact.prototype.sendSoftphoneMetrics = function (softphoneStreamStatistics, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, { + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + softphoneStreamStatistics: softphoneStreamStatistics + }, callbacks); + connect.publishSoftphoneStats({ + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + stats: softphoneStreamStatistics + }); + }; + Contact.prototype.sendSoftphoneReport = function (report, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT, { + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + report: report + }, callbacks); + connect.publishSoftphoneReport({ + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + report: report + }); + }; + Contact.prototype.conferenceConnections = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.CONFERENCE_CONNECTIONS, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.toSnapshot = function () { + return new connect.ContactSnapshot(this._getData()); + }; -require('./credentials'); -require('./credentials/credential_provider_chain'); -require('./credentials/temporary_credentials'); -require('./credentials/chainable_temporary_credentials'); -require('./credentials/web_identity_credentials'); -require('./credentials/cognito_identity_credentials'); -require('./credentials/saml_credentials'); + /*---------------------------------------------------------------- + * class ContactSnapshot + */ + var ContactSnapshot = function ContactSnapshot(contactData) { + connect.Contact.call(this, contactData.contactId); + this.contactData = contactData; + }; + ContactSnapshot.prototype = Object.create(Contact.prototype); + ContactSnapshot.prototype.constructor = ContactSnapshot; + ContactSnapshot.prototype._getData = function () { + return this.contactData; + }; + ContactSnapshot.prototype._createConnectionAPI = function (connectionData) { + return new connect.ConnectionSnapshot(connectionData); + }; -// Load the DOMParser XML parser -AWS.XML.Parser = require('./xml/browser_parser'); + /*---------------------------------------------------------------- + * class Connection + */ + var Connection = function Connection(contactId, connectionId) { + this.contactId = contactId; + this.connectionId = connectionId; + this._initMediaController(); + }; + Connection.prototype._getData = function () { + return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(), this.getConnectionId()); + }; + Connection.prototype.getContactId = function () { + return this.contactId; + }; + Connection.prototype.getConnectionId = function () { + return this.connectionId; + }; + Connection.prototype.getEndpoint = function () { + return new connect.Endpoint(this._getData().endpoint); + }; + Connection.prototype.getAddress = Connection.prototype.getEndpoint; + Connection.prototype.getState = function () { + return this._getData().state; + }; + Connection.prototype.getStatus = Connection.prototype.getState; + Connection.prototype.getStateDuration = function () { + return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); + }; + Connection.prototype.getStatusDuration = Connection.prototype.getStateDuration; + Connection.prototype.getType = function () { + return this._getData().type; + }; + Connection.prototype.isInitialConnection = function () { + return this._getData().initial; + }; + Connection.prototype.isActive = function () { + return connect.contains(connect.CONNECTION_ACTIVE_STATES, this.getStatus().type); + }; + Connection.prototype.isConnected = function () { + return this.getStatus().type === connect.ConnectionStateType.CONNECTED; + }; + Connection.prototype.isConnecting = function () { + return this.getStatus().type === connect.ConnectionStateType.CONNECTING; + }; + Connection.prototype.isOnHold = function () { + return this.getStatus().type === connect.ConnectionStateType.HOLD; + }; + Connection.prototype.getSoftphoneMediaInfo = function () { + return this._getData().softphoneMediaInfo; + }; -// Load the XHR HttpClient -require('./http/xhr'); + /** + * Gets the currently monitored contact info, Returns null if does not exists. + * @return {{agentName:string, customerName:string, joinTime:Date}} + */ + Connection.prototype.getMonitorInfo = function () { + return this._getData().monitoringInfo; + }; + Connection.prototype.destroy = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.DESTROY_CONNECTION, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + Connection.prototype.sendDigits = function (digits, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.SEND_DIGITS, { + contactId: this.getContactId(), + connectionId: this.getConnectionId(), + digits: digits + }, callbacks); + }; + Connection.prototype.hold = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.HOLD_CONNECTION, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + Connection.prototype.resume = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.RESUME_CONNECTION, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + Connection.prototype.toSnapshot = function () { + return new connect.ConnectionSnapshot(this._getData()); + }; + Connection.prototype._initMediaController = function () { + if (this.getMediaInfo()) { + connect.core.mediaFactory.get(this)["catch"](function () {}); + } + }; -if (typeof process === 'undefined') { - var process = { - browser: true + // Method for checking whether this connection is an agent-side connection + // (type AGENT or MONITORING) + Connection.prototype._isAgentConnectionType = function () { + var connectionType = this.getType(); + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; }; -} -}).call(this)}).call(this,require('_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(require,module,exports){ -var AWS = require('./core'); -require('./credentials'); -require('./credentials/credential_provider_chain'); -var PromisesDependency; + /** + * Utility method for checking whether this connection is an agent-side connection + * (type AGENT or MONITORING) + * @return {boolean} True if this connection is an agent-side connection. False otherwise. + */ + Connection.prototype._isAgentConnectionType = function () { + var connectionType = this.getType(); + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; + }; -/** - * The main configuration class used by all service objects to set - * the region, credentials, and other options for requests. - * - * By default, credentials and region settings are left unconfigured. - * This should be configured by the application before using any - * AWS service APIs. - * - * In order to set global configuration options, properties should - * be assigned to the global {AWS.config} object. - * - * @see AWS.config - * - * @!group General Configuration Options - * - * @!attribute credentials - * @return [AWS.Credentials] the AWS credentials to sign requests with. - * - * @!attribute region - * @example Set the global region setting to us-west-2 - * AWS.config.update({region: 'us-west-2'}); - * @return [AWS.Credentials] The region to send service requests to. - * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html - * A list of available endpoints for each AWS service - * - * @!attribute maxRetries - * @return [Integer] the maximum amount of retries to perform for a - * service request. By default this value is calculated by the specific - * service object that the request is being made to. - * - * @!attribute maxRedirects - * @return [Integer] the maximum amount of redirects to follow for a - * service request. Defaults to 10. - * - * @!attribute paramValidation - * @return [Boolean|map] whether input parameters should be validated against - * the operation description before sending the request. Defaults to true. - * Pass a map to enable any of the following specific validation features: - * - * * **min** [Boolean] — Validates that a value meets the min - * constraint. This is enabled by default when paramValidation is set - * to `true`. - * * **max** [Boolean] — Validates that a value meets the max - * constraint. - * * **pattern** [Boolean] — Validates that a string value matches a - * regular expression. - * * **enum** [Boolean] — Validates that a string value matches one - * of the allowable enum values. - * - * @!attribute computeChecksums - * @return [Boolean] whether to compute checksums for payload bodies when - * the service accepts it (currently supported in S3 only). - * - * @!attribute convertResponseTypes - * @return [Boolean] whether types are converted when parsing response data. - * Currently only supported for JSON based services. Turning this off may - * improve performance on large response payloads. Defaults to `true`. - * - * @!attribute correctClockSkew - * @return [Boolean] whether to apply a clock skew correction and retry - * requests that fail because of an skewed client clock. Defaults to - * `false`. - * - * @!attribute sslEnabled - * @return [Boolean] whether SSL is enabled for requests - * - * @!attribute s3ForcePathStyle - * @return [Boolean] whether to force path style URLs for S3 objects - * - * @!attribute s3BucketEndpoint - * @note Setting this configuration option requires an `endpoint` to be - * provided explicitly to the service constructor. - * @return [Boolean] whether the provided endpoint addresses an individual - * bucket (false if it addresses the root API endpoint). - * - * @!attribute s3DisableBodySigning - * @return [Boolean] whether to disable S3 body signing when using signature version `v4`. - * Body signing can only be disabled when using https. Defaults to `true`. - * - * @!attribute useAccelerateEndpoint - * @note This configuration option is only compatible with S3 while accessing - * dns-compatible buckets. - * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service. - * Defaults to `false`. - * - * @!attribute retryDelayOptions - * @example Set the base retry delay for all services to 300 ms - * AWS.config.update({retryDelayOptions: {base: 300}}); - * // Delays with maxRetries = 3: 300, 600, 1200 - * @example Set a custom backoff function to provide delay values on retries - * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) { - * // returns delay in ms - * }}}); - * @return [map] A set of options to configure the retry delay on retryable errors. - * Currently supported options are: - * - * * **base** [Integer] — The base number of milliseconds to use in the - * exponential backoff for operation retries. Defaults to 100 ms for all services except - * DynamoDB, where it defaults to 50ms. - * * **customBackoff ** [function] — A custom function that accepts a retry count - * and returns the amount of time to delay in milliseconds. The `base` option will be - * ignored if this option is supplied. - * - * @!attribute httpOptions - * @return [map] A set of options to pass to the low-level HTTP request. - * Currently supported options are: - * - * * **proxy** [String] — the URL to proxy requests through - * * **agent** [http.Agent, https.Agent] — the Agent object to perform - * HTTP requests with. Used for connection pooling. Note that for - * SSL connections, a special Agent object is used in order to enable - * peer certificate verification. This feature is only supported in the - * Node.js environment. - * * **connectTimeout** [Integer] — Sets the socket to timeout after - * failing to establish a connection with the server after - * `connectTimeout` milliseconds. This timeout has no effect once a socket - * connection has been established. - * * **timeout** [Integer] — Sets the socket to timeout after timeout - * milliseconds of inactivity on the socket. Defaults to two minutes - * (120000) - * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous - * HTTP requests. Used in the browser environment only. Set to false to - * send requests synchronously. Defaults to true (async on). - * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" - * property of an XMLHttpRequest object. Used in the browser environment - * only. Defaults to false. - * @!attribute logger - * @return [#write,#log] an object that responds to .write() (like a stream) - * or .log() (like the console object) in order to log information about - * requests - * - * @!attribute systemClockOffset - * @return [Number] an offset value in milliseconds to apply to all signing - * times. Use this to compensate for clock skew when your system may be - * out of sync with the service time. Note that this configuration option - * can only be applied to the global `AWS.config` object and cannot be - * overridden in service-specific configuration. Defaults to 0 milliseconds. - * - * @!attribute signatureVersion - * @return [String] the signature version to sign requests with (overriding - * the API configuration). Possible values are: 'v2', 'v3', 'v4'. - * - * @!attribute signatureCache - * @return [Boolean] whether the signature to sign requests with (overriding - * the API configuration) is cached. Only applies to the signature version 'v4'. - * Defaults to `true`. - * - * @!attribute endpointDiscoveryEnabled - * @return [Boolean] whether to enable endpoint discovery for operations that - * allow optionally using an endpoint returned by the service. - * Defaults to 'false' - * - * @!attribute endpointCacheSize - * @return [Number] the size of the global cache storing endpoints from endpoint - * discovery operations. Once endpoint cache is created, updating this setting - * cannot change existing cache size. - * Defaults to 1000 - * - * @!attribute hostPrefixEnabled - * @return [Boolean] whether to marshal request parameters to the prefix of - * hostname. Defaults to `true`. - * - * @!attribute stsRegionalEndpoints - * @return ['legacy'|'regional'] whether to send sts request to global endpoints or - * regional endpoints. - * Defaults to 'legacy' - */ -AWS.Config = AWS.util.inherit({ - /** - * @!endgroup - */ + /*---------------------------------------------------------------- + * Voice authenticator VoiceId + */ - /** - * Creates a new configuration object. This is the object that passes - * option data along to service requests, including credentials, security, - * region information, and some service specific settings. - * - * @example Creating a new configuration object with credentials and region - * var config = new AWS.Config({ - * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2' - * }); - * @option options accessKeyId [String] your AWS access key ID. - * @option options secretAccessKey [String] your AWS secret access key. - * @option options sessionToken [AWS.Credentials] the optional AWS - * session token to sign requests with. - * @option options credentials [AWS.Credentials] the AWS credentials - * to sign requests with. You can either specify this object, or - * specify the accessKeyId and secretAccessKey options directly. - * @option options credentialProvider [AWS.CredentialProviderChain] the - * provider chain used to resolve credentials if no static `credentials` - * property is set. - * @option options region [String] the region to send service requests to. - * See {region} for more information. - * @option options maxRetries [Integer] the maximum amount of retries to - * attempt with a request. See {maxRetries} for more information. - * @option options maxRedirects [Integer] the maximum amount of redirects to - * follow with a request. See {maxRedirects} for more information. - * @option options sslEnabled [Boolean] whether to enable SSL for - * requests. - * @option options paramValidation [Boolean|map] whether input parameters - * should be validated against the operation description before sending - * the request. Defaults to true. Pass a map to enable any of the - * following specific validation features: - * - * * **min** [Boolean] — Validates that a value meets the min - * constraint. This is enabled by default when paramValidation is set - * to `true`. - * * **max** [Boolean] — Validates that a value meets the max - * constraint. - * * **pattern** [Boolean] — Validates that a string value matches a - * regular expression. - * * **enum** [Boolean] — Validates that a string value matches one - * of the allowable enum values. - * @option options computeChecksums [Boolean] whether to compute checksums - * for payload bodies when the service accepts it (currently supported - * in S3 only) - * @option options convertResponseTypes [Boolean] whether types are converted - * when parsing response data. Currently only supported for JSON based - * services. Turning this off may improve performance on large response - * payloads. Defaults to `true`. - * @option options correctClockSkew [Boolean] whether to apply a clock skew - * correction and retry requests that fail because of an skewed client - * clock. Defaults to `false`. - * @option options s3ForcePathStyle [Boolean] whether to force path - * style URLs for S3 objects. - * @option options s3BucketEndpoint [Boolean] whether the provided endpoint - * addresses an individual bucket (false if it addresses the root API - * endpoint). Note that setting this configuration option requires an - * `endpoint` to be provided explicitly to the service constructor. - * @option options s3DisableBodySigning [Boolean] whether S3 body signing - * should be disabled when using signature version `v4`. Body signing - * can only be disabled when using https. Defaults to `true`. - * - * @option options retryDelayOptions [map] A set of options to configure - * the retry delay on retryable errors. Currently supported options are: - * - * * **base** [Integer] — The base number of milliseconds to use in the - * exponential backoff for operation retries. Defaults to 100 ms for all - * services except DynamoDB, where it defaults to 50ms. - * * **customBackoff ** [function] — A custom function that accepts a retry count - * and returns the amount of time to delay in milliseconds. The `base` option will be - * ignored if this option is supplied. - * @option options httpOptions [map] A set of options to pass to the low-level - * HTTP request. Currently supported options are: - * - * * **proxy** [String] — the URL to proxy requests through - * * **agent** [http.Agent, https.Agent] — the Agent object to perform - * HTTP requests with. Used for connection pooling. Defaults to the global - * agent (`http.globalAgent`) for non-SSL connections. Note that for - * SSL connections, a special Agent object is used in order to enable - * peer certificate verification. This feature is only available in the - * Node.js environment. - * * **connectTimeout** [Integer] — Sets the socket to timeout after - * failing to establish a connection with the server after - * `connectTimeout` milliseconds. This timeout has no effect once a socket - * connection has been established. - * * **timeout** [Integer] — Sets the socket to timeout after timeout - * milliseconds of inactivity on the socket. Defaults to two minutes - * (120000). - * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous - * HTTP requests. Used in the browser environment only. Set to false to - * send requests synchronously. Defaults to true (async on). - * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" - * property of an XMLHttpRequest object. Used in the browser environment - * only. Defaults to false. - * @option options apiVersion [String, Date] a String in YYYY-MM-DD format - * (or a date) that represents the latest possible API version that can be - * used in all services (unless overridden by `apiVersions`). Specify - * 'latest' to use the latest possible version. - * @option options apiVersions [map] a map of service - * identifiers (the lowercase service class name) with the API version to - * use when instantiating a service. Specify 'latest' for each individual - * that can use the latest available version. - * @option options logger [#write,#log] an object that responds to .write() - * (like a stream) or .log() (like the console object) in order to log - * information about requests - * @option options systemClockOffset [Number] an offset value in milliseconds - * to apply to all signing times. Use this to compensate for clock skew - * when your system may be out of sync with the service time. Note that - * this configuration option can only be applied to the global `AWS.config` - * object and cannot be overridden in service-specific configuration. - * Defaults to 0 milliseconds. - * @option options signatureVersion [String] the signature version to sign - * requests with (overriding the API configuration). Possible values are: - * 'v2', 'v3', 'v4'. - * @option options signatureCache [Boolean] whether the signature to sign - * requests with (overriding the API configuration) is cached. Only applies - * to the signature version 'v4'. Defaults to `true`. - * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32 - * checksum of HTTP response bodies returned by DynamoDB. Default: `true`. - * @option options useAccelerateEndpoint [Boolean] Whether to use the - * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`. - * @option options clientSideMonitoring [Boolean] whether to collect and - * publish this client's performance metrics of all its API requests. - * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint - * discovery for operations that allow optionally using an endpoint returned by - * the service. - * Defaults to 'false' - * @option options endpointCacheSize [Number] the size of the global cache storing - * endpoints from endpoint discovery operations. Once endpoint cache is created, - * updating this setting cannot change existing cache size. - * Defaults to 1000 - * @option options hostPrefixEnabled [Boolean] whether to marshal request - * parameters to the prefix of hostname. - * Defaults to `true`. - * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request - * to global endpoints or regional endpoints. - * Defaults to 'legacy'. - */ - constructor: function Config(options) { - if (options === undefined) options = {}; - options = this.extractCredentials(options); - - AWS.util.each.call(this, this.keys, function (key, value) { - this.set(key, options[key], value); + var VoiceId = function VoiceId(contactId) { + this.contactId = contactId; + }; + VoiceId.prototype.getSpeakerId = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + client.call(connect.AgentAppClientMethods.GET_CONTACT, { + "contactId": self.contactId, + "instanceId": connect.core.getAgentDataProvider().getInstanceId(), + "awsAccountId": connect.core.getAgentDataProvider().getAWSAccountId() + }, { + success: function success(data) { + if (data.contactData.customerId) { + var obj = { + speakerId: data.contactData.customerId + }; + connect.getLog().info("getSpeakerId succeeded").withObject(data).sendInternalLogToServer(); + resolve(obj); + } else { + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND, "No speakerId assotiated with this call"); + reject(error); + } + }, + failure: function failure(err) { + connect.getLog().error("Get SpeakerId failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED, "Get SpeakerId failed", err); + reject(error); + } + }); }); - }, - - /** - * @!group Managing Credentials - */ - - /** - * Loads credentials from the configuration object. This is used internally - * by the SDK to ensure that refreshable {Credentials} objects are properly - * refreshed and loaded when sending a request. If you want to ensure that - * your credentials are loaded prior to a request, you can use this method - * directly to provide accurate credential data stored in the object. - * - * @note If you configure the SDK with static or environment credentials, - * the credential data should already be present in {credentials} attribute. - * This method is primarily necessary to load credentials from asynchronous - * sources, or sources that can refresh credentials periodically. - * @example Getting your access key - * AWS.config.getCredentials(function(err) { - * if (err) console.log(err.stack); // credentials not loaded - * else console.log("Access Key:", AWS.config.credentials.accessKeyId); - * }) - * @callback callback function(err) - * Called when the {credentials} have been properly set on the configuration - * object. - * - * @param err [Error] if this is set, credentials were not successfully - * loaded and this error provides information why. - * @see credentials - * @see Credentials - */ - getCredentials: function getCredentials(callback) { + }; + VoiceId.prototype.getSpeakerStatus = function () { var self = this; - - function finish(err) { - callback(err, err ? null : self.credentials); - } - - function credError(msg, err) { - return new AWS.util.error(err || new Error(), { - code: 'CredentialsError', - message: msg, - name: 'CredentialsError' + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER, { + "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + connect.getLog().info("getSpeakerStatus succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + var error; + var parsedErr = JSON.parse(err); + switch (parsedErr.status) { + case 400: + case 404: + var data = parsedErr; + data.type = data.type ? data.type : connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED; + connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(); + resolve(data); + break; + default: + connect.getLog().error("getSpeakerStatus failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED, "Get SpeakerStatus failed", err); + reject(error); + } + } + }); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); }); - } + }); + }; - function getAsyncCredentials() { - self.credentials.get(function(err) { - if (err) { - var msg = 'Could not load credentials from ' + - self.credentials.constructor.name; - err = credError(msg, err); + // internal only + VoiceId.prototype._optOutSpeakerInLcms = function (speakerId) { + var self = this; + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { + "ContactId": self.contactId, + "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), + "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), + "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), + "VoiceIdResult": { + "SpeakerOptedOut": true } - finish(err); - }); - } - - function getStaticCredentials() { - var err = null; - if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) { - err = credError('Missing credentials'); - } - finish(err); - } - - if (self.credentials) { - if (typeof self.credentials.get === 'function') { - getAsyncCredentials(); - } else { // static credentials - getStaticCredentials(); - } - } else if (self.credentialProvider) { - self.credentialProvider.resolve(function(err, creds) { - if (err) { - err = credError('Could not load credentials from any providers', err); + }, { + success: function success(data) { + connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("optOutSpeakerInLcms failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED, "optOutSpeakerInLcms failed", err); + reject(error); } - self.credentials = creds; - finish(err); }); - } else { - finish(credError('No credentials to load')); - } - }, - - /** - * @!group Loading and Setting Configuration Options - */ - - /** - * @overload update(options, allowUnknownKeys = false) - * Updates the current configuration object with new options. - * - * @example Update maxRetries property of a configuration object - * config.update({maxRetries: 10}); - * @param [Object] options a map of option keys and values. - * @param [Boolean] allowUnknownKeys whether unknown keys can be set on - * the configuration object. Defaults to `false`. - * @see constructor - */ - update: function update(options, allowUnknownKeys) { - allowUnknownKeys = allowUnknownKeys || false; - options = this.extractCredentials(options); - AWS.util.each.call(this, options, function (key, value) { - if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) || - AWS.Service.hasService(key)) { - this.set(key, value); - } }); - }, - - /** - * Loads configuration data from a JSON file into this config object. - * @note Loading configuration will reset all existing configuration - * on the object. - * @!macro nobrowser - * @param path [String] the path relative to your process's current - * working directory to load configuration from. - * @return [AWS.Config] the same configuration object - */ - loadFromPath: function loadFromPath(path) { - this.clear(); - - var options = JSON.parse(AWS.util.readFileSync(path)); - var fileSystemCreds = new AWS.FileSystemCredentials(path); - var chain = new AWS.CredentialProviderChain(); - chain.providers.unshift(fileSystemCreds); - chain.resolve(function (err, creds) { - if (err) throw err; - else options.credentials = creds; + }; + VoiceId.prototype.optOutSpeaker = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.getDomainId().then(function (domainId) { + var speakerId = data.speakerId; + client.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER, { + "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + self._optOutSpeakerInLcms(speakerId)["catch"](function () {}); + connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("optOutSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED, "optOutSpeaker failed.", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); }); - - this.constructor(options); - - return this; - }, - - /** - * Clears configuration data on this object - * - * @api private - */ - clear: function clear() { - /*jshint forin:false */ - AWS.util.each.call(this, this.keys, function (key) { - delete this[key]; + }; + VoiceId.prototype.deleteSpeaker = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.DELETE_SPEAKER, { + "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + connect.getLog().info("deleteSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("deleteSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED, "deleteSpeaker failed.", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); }); + }; + VoiceId.prototype.startSession = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION, { + "contactId": self.contactId, + "instanceId": connect.core.getAgentDataProvider().getInstanceId(), + "customerAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), + "clientToken": AWS.util.uuid.v4(), + "domainId": domainId + }, { + success: function success(data) { + if (data.sessionId) { + resolve(data); + } else { + connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({ + data: data + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "No session id returned from start session api"); + reject(error); + } + }, + failure: function failure(err) { + connect.getLog().error("startVoiceIdSession failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "startVoiceIdSession failed", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.evaluateSpeaker = function (startNew) { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var pollTimes = 0; + return new Promise(function (resolve, reject) { + function evaluate() { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.EVALUATE_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "DomainId": domainId + }, { + success: function success(data) { + if (++pollTimes < connect.VoiceIdConstants.EVALUATION_MAX_POLL_TIMES) { + if (data.StreamingStatus === connect.VoiceIdStreamingStatus.PENDING_CONFIGURATION) { + setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); + } else { + if (!data.AuthenticationResult) { + data.AuthenticationResult = {}; + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENABLED; + } + if (!data.FraudDetectionResult) { + data.FraudDetectionResult = {}; + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; + } - // reset credential provider - this.set('credentials', undefined); - this.set('credentialProvider', undefined); - }, - - /** - * Sets a property on the configuration object, allowing for a - * default value - * @api private - */ - set: function set(property, value, defaultValue) { - if (value === undefined) { - if (defaultValue === undefined) { - defaultValue = this.keys[property]; - } - if (typeof defaultValue === 'function') { - this[property] = defaultValue.call(this); - } else { - this[property] = defaultValue; - } - } else if (property === 'httpOptions' && this[property]) { - // deep merge httpOptions - this[property] = AWS.util.merge(this[property], value); - } else { - this[property] = value; - } - }, - - /** - * All of the keys with their default values. - * - * @constant - * @api private - */ - keys: { - credentials: null, - credentialProvider: null, - region: null, - logger: null, - apiVersions: {}, - apiVersion: null, - endpoint: undefined, - httpOptions: { - timeout: 120000 - }, - maxRetries: undefined, - maxRedirects: 10, - paramValidation: true, - sslEnabled: true, - s3ForcePathStyle: false, - s3BucketEndpoint: false, - s3DisableBodySigning: true, - computeChecksums: true, - convertResponseTypes: true, - correctClockSkew: false, - customUserAgent: null, - dynamoDbCrc32: true, - systemClockOffset: 0, - signatureVersion: null, - signatureCache: true, - retryDelayOptions: {}, - useAccelerateEndpoint: false, - clientSideMonitoring: false, - endpointDiscoveryEnabled: false, - endpointCacheSize: 1000, - hostPrefixEnabled: true, - stsRegionalEndpoints: null - }, - - /** - * Extracts accessKeyId, secretAccessKey and sessionToken - * from a configuration hash. - * - * @api private - */ - extractCredentials: function extractCredentials(options) { - if (options.accessKeyId && options.secretAccessKey) { - options = AWS.util.copy(options); - options.credentials = new AWS.Credentials(options); - } - return options; - }, - - /** - * Sets the promise dependency the SDK will use wherever Promises are returned. - * Passing `null` will force the SDK to use native Promises if they are available. - * If native Promises are not available, passing `null` will have no effect. - * @param [Constructor] dep A reference to a Promise constructor - */ - setPromisesDependency: function setPromisesDependency(dep) { - PromisesDependency = dep; - // if null was passed in, we should try to use native promises - if (dep === null && typeof Promise === 'function') { - PromisesDependency = Promise; - } - var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain]; - if (AWS.S3) { - constructors.push(AWS.S3); - if (AWS.S3.ManagedUpload) { - constructors.push(AWS.S3.ManagedUpload); + // Resolve if both authentication and fraud detection are not enabled. + if (!self.isAuthEnabled(data.AuthenticationResult.Decision) && !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { + connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + return; + } + if (data.StreamingStatus === connect.VoiceIdStreamingStatus.ENDED) { + if (self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision)) { + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; + } + if (self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; + } + } + // Voice print is not long enough for both authentication and fraud detection + if (self.isAuthResultInconclusive(data.AuthenticationResult.Decision) && self.isFraudResultInconclusive(data.FraudDetectionResult.Decision)) { + connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + return; + } + if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && self.isAuthEnabled(data.AuthenticationResult.Decision)) { + switch (data.AuthenticationResult.Decision) { + case connect.VoiceIdAuthenticationDecision.ACCEPT: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.AUTHENTICATED; + break; + case connect.VoiceIdAuthenticationDecision.REJECT: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_AUTHENTICATED; + break; + case connect.VoiceIdAuthenticationDecision.SPEAKER_OPTED_OUT: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.OPTED_OUT; + break; + case connect.VoiceIdAuthenticationDecision.SPEAKER_NOT_ENROLLED: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENROLLED; + break; + default: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.ERROR; + } + } + if (!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && self.isFraudEnabled(data.FraudDetectionResult.Decision)) { + switch (data.FraudDetectionResult.Decision) { + case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.HIGH_RISK; + break; + case connect.VoiceIdFraudDetectionDecision.LOW_RISK: + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.LOW_RISK; + break; + default: + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.ERROR; + } + } + if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && !self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { + // Resolve only when both authentication and fraud detection have results. Otherwise, keep polling. + connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + return; + } else { + setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); + } + } + } else { + connect.getLog().error("evaluateSpeaker timeout").sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_TIMEOUT, "evaluateSpeaker timeout"); + reject(error); + } + }, + failure: function failure(err) { + var error; + var parsedErr = JSON.parse(err); + switch (parsedErr.status) { + case 400: + case 404: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "evaluateSpeaker failed, session not exists", err); + connect.getLog().error("evaluateSpeaker failed, session not exists").withObject({ + err: err + }).sendInternalLogToServer(); + break; + default: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); + connect.getLog().error("evaluateSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + } + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); } - } - AWS.util.addPromises(constructors, PromisesDependency); - }, - - /** - * Gets the promise dependency set by `AWS.config.setPromisesDependency`. - */ - getPromisesDependency: function getPromisesDependency() { - return PromisesDependency; - } -}); - -/** - * @return [AWS.Config] The global configuration object singleton instance - * @readonly - * @see AWS.Config - */ -AWS.config = new AWS.Config(); - -},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(require,module,exports){ -/** - * The main AWS namespace - */ -var AWS = { util: require('./util') }; - -/** - * @api private - * @!macro [new] nobrowser - * @note This feature is not supported in the browser environment of the SDK. - */ -var _hidden = {}; _hidden.toString(); // hack to parse macro - -/** - * @api private - */ -module.exports = AWS; - -AWS.util.update(AWS, { - - /** - * @constant - */ - VERSION: '2.553.0', - - /** - * @api private - */ - Signers: {}, - - /** - * @api private - */ - Protocol: { - Json: require('./protocol/json'), - Query: require('./protocol/query'), - Rest: require('./protocol/rest'), - RestJson: require('./protocol/rest_json'), - RestXml: require('./protocol/rest_xml') - }, - - /** - * @api private - */ - XML: { - Builder: require('./xml/builder'), - Parser: null // conditionally set based on environment - }, - - /** - * @api private - */ - JSON: { - Builder: require('./json/builder'), - Parser: require('./json/parser') - }, - - /** - * @api private - */ - Model: { - Api: require('./model/api'), - Operation: require('./model/operation'), - Shape: require('./model/shape'), - Paginator: require('./model/paginator'), - ResourceWaiter: require('./model/resource_waiter') - }, - - /** - * @api private - */ - apiLoader: require('./api_loader'), - - /** - * @api private - */ - EndpointCache: require('../vendor/endpoint-cache').EndpointCache -}); -require('./sequential_executor'); -require('./service'); -require('./config'); -require('./http'); -require('./event_listeners'); -require('./request'); -require('./response'); -require('./resource_waiter'); -require('./signers/request_signer'); -require('./param_validator'); + if (!startNew) { + self.syncSpeakerId().then(function () { + evaluate(); + })["catch"](function (err) { + connect.getLog().error("syncSpeakerId failed when session startNew=false").withObject({ + err: err + }).sendInternalLogToServer(); + reject(err); + }); + } else { + self.startSession().then(function (data) { + self.syncSpeakerId().then(function (data) { + setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); + })["catch"](function (err) { + connect.getLog().error("syncSpeakerId failed when session startNew=true").withObject({ + err: err + }).sendInternalLogToServer(); + reject(err); + }); + })["catch"](function (err) { + connect.getLog().error("startSession failed when session startNew=true").withObject({ + err: err + }).sendInternalLogToServer(); + reject(err); + }); + } + }); + }; + VoiceId.prototype.describeSession = function () { + var self = this; + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + return new Promise(function (resolve, reject) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.DESCRIBE_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "DomainId": domainId + }, { + success: function success(data) { + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("describeSession failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DESCRIBE_SESSION_FAILED, "describeSession failed", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.checkEnrollmentStatus = function () { + var self = this; + var pollingTimes = 0; + return new Promise(function (resolve, reject) { + function describe() { + if (++pollingTimes < connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES) { + self.describeSession().then(function (data) { + switch (data.Session.EnrollmentRequestDetails.Status) { + case connect.VoiceIdEnrollmentRequestStatus.COMPLETED: + resolve(data); + break; + case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: + setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); + break; + case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: + if (data.Session.StreamingStatus !== connect.VoiceIdStreamingStatus.ENDED) { + setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); + } else { + setTimeout(function () { + self.startSession().then(function (data) { + describe(); + })["catch"](function (err, data) { + reject(err); + }); + }, connect.VoiceIdConstants.START_SESSION_DELAY); + } + break; + default: + var message = data.Session.EnrollmentRequestDetails.Message ? data.Session.EnrollmentRequestDetails.Message : "enrollSpeaker failed. Unknown enrollment status has been received"; + connect.getLog().error(message).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, message, data.Session.EnrollmentRequestDetails.Status); + reject(error); + } + }); + } else { + connect.getLog().error("enrollSpeaker timeout").sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT, "enrollSpeaker timeout"); + reject(error); + } + } + describe(); + }); + }; + VoiceId.prototype.enrollSpeaker = function () { + var self = this; + self.checkConferenceCall(); + return new Promise(function (resolve, reject) { + self.syncSpeakerId().then(function () { + self.getSpeakerStatus().then(function (data) { + if (data.Speaker && data.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT) { + self.deleteSpeaker().then(function () { + self.enrollSpeakerHelper(resolve, reject); + })["catch"](function (err) { + reject(err); + }); + } else { + self.enrollSpeakerHelper(resolve, reject); + } + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject) { + var self = this; + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.ENROLL_BY_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "DomainId": domainId + }, { + success: function success(data) { + if (data.Status === connect.VoiceIdEnrollmentRequestStatus.COMPLETED) { + connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + } else { + self.checkEnrollmentStatus().then(function (data) { + connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + })["catch"](function (err) { + reject(err); + }); + } + }, + failure: function failure(err) { + connect.getLog().error("enrollSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, "enrollSpeaker failed", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }; -/** - * @readonly - * @return [AWS.SequentialExecutor] a collection of global event listeners that - * are attached to every sent request. - * @see AWS.Request AWS.Request for a list of events to listen for - * @example Logging the time taken to send a request - * AWS.events.on('send', function startSend(resp) { - * resp.startTime = new Date().getTime(); - * }).on('complete', function calculateTime(resp) { - * var time = (new Date().getTime() - resp.startTime) / 1000; - * console.log('Request took ' + time + ' seconds'); - * }); - * - * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' - */ -AWS.events = new AWS.SequentialExecutor(); - -//create endpoint cache lazily -AWS.util.memoizedProperty(AWS, 'endpointCache', function() { - return new AWS.EndpointCache(AWS.config.endpointCacheSize); -}, true); - -},{"../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(require,module,exports){ -var AWS = require('./core'); - -/** - * Represents your AWS security credentials, specifically the - * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}. - * Creating a `Credentials` object allows you to pass around your - * security information to configuration and service objects. - * - * Note that this class typically does not need to be constructed manually, - * as the {AWS.Config} and {AWS.Service} classes both accept simple - * options hashes with the three keys. These structures will be converted - * into Credentials objects automatically. - * - * ## Expiring and Refreshing Credentials - * - * Occasionally credentials can expire in the middle of a long-running - * application. In this case, the SDK will automatically attempt to - * refresh the credentials from the storage location if the Credentials - * class implements the {refresh} method. - * - * If you are implementing a credential storage location, you - * will want to create a subclass of the `Credentials` class and - * override the {refresh} method. This method allows credentials to be - * retrieved from the backing store, be it a file system, database, or - * some network storage. The method should reset the credential attributes - * on the object. - * - * @!attribute expired - * @return [Boolean] whether the credentials have been expired and - * require a refresh. Used in conjunction with {expireTime}. - * @!attribute expireTime - * @return [Date] a time when credentials should be considered expired. Used - * in conjunction with {expired}. - * @!attribute accessKeyId - * @return [String] the AWS access key ID - * @!attribute secretAccessKey - * @return [String] the AWS secret access key - * @!attribute sessionToken - * @return [String] an optional AWS session token - */ -AWS.Credentials = AWS.util.inherit({ - /** - * A credentials object can be created using positional arguments or an options - * hash. - * - * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null) - * Creates a Credentials object with a given set of credential information - * as positional arguments. - * @param accessKeyId [String] the AWS access key ID - * @param secretAccessKey [String] the AWS secret access key - * @param sessionToken [String] the optional AWS session token - * @example Create a credentials object with AWS credentials - * var creds = new AWS.Credentials('akid', 'secret', 'session'); - * @overload AWS.Credentials(options) - * Creates a Credentials object with a given set of credential information - * as an options hash. - * @option options accessKeyId [String] the AWS access key ID - * @option options secretAccessKey [String] the AWS secret access key - * @option options sessionToken [String] the optional AWS session token - * @example Create a credentials object with AWS credentials - * var creds = new AWS.Credentials({ - * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' - * }); - */ - constructor: function Credentials() { - // hide secretAccessKey from being displayed with util.inspect - AWS.util.hideProperties(this, ['secretAccessKey']); - - this.expired = false; - this.expireTime = null; - this.refreshCallbacks = []; - if (arguments.length === 1 && typeof arguments[0] === 'object') { - var creds = arguments[0].credentials || arguments[0]; - this.accessKeyId = creds.accessKeyId; - this.secretAccessKey = creds.secretAccessKey; - this.sessionToken = creds.sessionToken; - } else { - this.accessKeyId = arguments[0]; - this.secretAccessKey = arguments[1]; - this.sessionToken = arguments[2]; - } - }, - - /** - * @return [Integer] the number of seconds before {expireTime} during which - * the credentials will be considered expired. - */ - expiryWindow: 15, - - /** - * @return [Boolean] whether the credentials object should call {refresh} - * @note Subclasses should override this method to provide custom refresh - * logic. - */ - needsRefresh: function needsRefresh() { - var currentTime = AWS.util.date.getDate().getTime(); - var adjustedTime = new Date(currentTime + this.expiryWindow * 1000); - - if (this.expireTime && adjustedTime > this.expireTime) { - return true; - } else { - return this.expired || !this.accessKeyId || !this.secretAccessKey; - } - }, - - /** - * Gets the existing credentials, refreshing them if they are not yet loaded - * or have expired. Users should call this method before using {refresh}, - * as this will not attempt to reload credentials when they are already - * loaded into the object. - * - * @callback callback function(err) - * When this callback is called with no error, it means either credentials - * do not need to be refreshed or refreshed credentials information has - * been loaded into the object (as the `accessKeyId`, `secretAccessKey`, - * and `sessionToken` properties). - * @param err [Error] if an error occurred, this value will be filled - */ - get: function get(callback) { + // internal only + VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId) { + var self = this; + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { + "ContactId": self.contactId, + "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), + "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), + "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), + "VoiceIdResult": { + "generatedSpeakerId": speakerId + } + }, { + success: function success(data) { + connect.getLog().info("updateSpeakerIdInLcms succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("updateSpeakerIdInLcms failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_IN_LCMS_FAILED, "updateSpeakerIdInLcms failed", err); + reject(error); + } + }); + }); + }; + VoiceId.prototype.updateSpeakerIdInVoiceId = function (speakerId) { var self = this; - if (this.needsRefresh()) { - this.refresh(function(err) { - if (!err) self.expired = false; // reset expired flag - if (callback) callback(err); + self.checkConferenceCall(); + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + return new Promise(function (resolve, reject) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.UPDATE_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); + self._updateSpeakerIdInLcms(speakerId).then(function () { + resolve(data); + })["catch"](function (err) { + reject(err); + }); + }, + failure: function failure(err) { + var error; + var parsedErr = JSON.parse(err); + switch (parsedErr.status) { + case 400: + case 404: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "updateSpeakerIdInVoiceId failed, session not exists", err); + connect.getLog().error("updateSpeakerIdInVoiceId failed, session not exists").withObject({ + err: err + }).sendInternalLogToServer(); + break; + default: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); + connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ + err: err + }).sendInternalLogToServer(); + } + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.syncSpeakerId = function () { + var self = this; + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.updateSpeakerIdInVoiceId(data.speakerId).then(function (data) { + resolve(data); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); }); - } else if (callback) { - callback(); + }); + }; + VoiceId.prototype.getDomainId = function () { + return new Promise(function (resolve, reject) { + var agent = new connect.Agent(); + if (!agent.getPermissions().includes(connect.AgentPermissions.VOICE_ID)) { + reject(new Error("Agent doesn't have the permission for Voice ID")); + } else if (connect.core.voiceIdDomainId) { + resolve(connect.core.voiceIdDomainId); + } else { + var client = connect.core.getClient(); + client.call(connect.AgentAppClientMethods.LIST_INTEGRATION_ASSOCIATIONS, { + "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), + "IntegrationType": "VOICE_ID" + }, { + success: function success(data) { + try { + var domainId; + if (data.IntegrationAssociationSummaryList.length >= 1) { + var integrationArn = data.IntegrationAssociationSummaryList[0].IntegrationArn; + domainId = integrationArn.replace(/^.*domain\//i, ''); + } + if (!domainId) { + connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND); + reject(error); + return; + } + connect.getLog().info("getDomainId succeeded").withObject(data).sendInternalLogToServer(); + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.VoiceIdEvents.UPDATE_DOMAIN_ID, + data: { + domainId: domainId + } + }); + resolve(domainId); + } catch (err) { + connect.getLog().error("getDomainId failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); + reject(error); + } + }, + failure: function failure(err) { + connect.getLog().error("getDomainId failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); + reject(error); + } + }); + } + }); + }; + VoiceId.prototype.checkConferenceCall = function () { + var self = this; + var isConferenceCall = connect.core.getAgentDataProvider().getContactData(self.contactId).connections.filter(function (conn) { + return connect.contains(connect.CONNECTION_ACTIVE_STATES, conn.state.type); + }).length > 2; + if (isConferenceCall) { + throw new connect.NotImplementedError("VoiceId is not supported for conference calls"); } - }, + }; + VoiceId.prototype.isAuthEnabled = function (authResult) { + return authResult !== connect.ContactFlowAuthenticationDecision.NOT_ENABLED; + }; + VoiceId.prototype.isAuthResultNotEnoughSpeech = function (authResult) { + return authResult === connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH; + }; + VoiceId.prototype.isAuthResultInconclusive = function (authResult) { + return authResult === connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; + }; + VoiceId.prototype.isFraudEnabled = function (fraudResult) { + return fraudResult !== connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; + }; + VoiceId.prototype.isFraudResultNotEnoughSpeech = function (fraudResult) { + return fraudResult === connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH; + }; + VoiceId.prototype.isFraudResultInconclusive = function (fraudResult) { + return fraudResult === connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; + }; /** - * @!method getPromise() - * Returns a 'thenable' promise. - * Gets the existing credentials, refreshing them if they are not yet loaded - * or have expired. Users should call this method before using {refresh}, - * as this will not attempt to reload credentials when they are already - * loaded into the object. - * - * Two callbacks can be provided to the `then` method on the returned promise. - * The first callback will be called if the promise is fulfilled, and the second - * callback will be called if the promise is rejected. - * @callback fulfilledCallback function() - * Called if the promise is fulfilled. When this callback is called, it - * means either credentials do not need to be refreshed or refreshed - * credentials information has been loaded into the object (as the - * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). - * @callback rejectedCallback function(err) - * Called if the promise is rejected. - * @param err [Error] if an error occurred, this value will be filled - * @return [Promise] A promise that represents the state of the `get` call. - * @example Calling the `getPromise` method. - * var promise = credProvider.getPromise(); - * promise.then(function() { ... }, function(err) { ... }); + * @class VoiceConnection + * @param {number} contactId + * @param {number} connectionId + * @description - Provides voice media specific operations */ + var VoiceConnection = function VoiceConnection(contactId, connectionId) { + this._speakerAuthenticator = new VoiceId(contactId); + Connection.call(this, contactId, connectionId); + }; + VoiceConnection.prototype = Object.create(Connection.prototype); + VoiceConnection.prototype.constructor = VoiceConnection; /** - * @!method refreshPromise() - * Returns a 'thenable' promise. - * Refreshes the credentials. Users should call {get} before attempting - * to forcibly refresh credentials. - * - * Two callbacks can be provided to the `then` method on the returned promise. - * The first callback will be called if the promise is fulfilled, and the second - * callback will be called if the promise is rejected. - * @callback fulfilledCallback function() - * Called if the promise is fulfilled. When this callback is called, it - * means refreshed credentials information has been loaded into the object - * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). - * @callback rejectedCallback function(err) - * Called if the promise is rejected. - * @param err [Error] if an error occurred, this value will be filled - * @return [Promise] A promise that represents the state of the `refresh` call. - * @example Calling the `refreshPromise` method. - * var promise = credProvider.refreshPromise(); - * promise.then(function() { ... }, function(err) { ... }); - */ + * @deprecated + * Please use getMediaInfo + */ + VoiceConnection.prototype.getSoftphoneMediaInfo = function () { + return this._getData().softphoneMediaInfo; + }; + VoiceConnection.prototype.getMediaInfo = function () { + return this._getData().softphoneMediaInfo; + }; + VoiceConnection.prototype.getMediaType = function () { + return connect.MediaType.SOFTPHONE; + }; + VoiceConnection.prototype.getMediaController = function () { + return connect.core.mediaFactory.get(this); + }; + VoiceConnection.prototype.getVoiceIdSpeakerId = function () { + return this._speakerAuthenticator.getSpeakerId(); + }; + VoiceConnection.prototype.getVoiceIdSpeakerStatus = function () { + return this._speakerAuthenticator.getSpeakerStatus(); + }; + VoiceConnection.prototype.optOutVoiceIdSpeaker = function () { + return this._speakerAuthenticator.optOutSpeaker(); + }; + VoiceConnection.prototype.deleteVoiceIdSpeaker = function () { + return this._speakerAuthenticator.deleteSpeaker(); + }; + VoiceConnection.prototype.evaluateSpeakerWithVoiceId = function (startNew) { + return this._speakerAuthenticator.evaluateSpeaker(startNew); + }; + VoiceConnection.prototype.enrollSpeakerInVoiceId = function () { + return this._speakerAuthenticator.enrollSpeaker(); + }; + VoiceConnection.prototype.updateVoiceIdSpeakerId = function (speakerId) { + return this._speakerAuthenticator.updateSpeakerIdInVoiceId(speakerId); + }; + VoiceConnection.prototype.getQuickConnectName = function () { + return this._getData().quickConnectName; + }; + VoiceConnection.prototype.isMute = function () { + return this._getData().mute; + }; + VoiceConnection.prototype.muteParticipant = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.MUTE_PARTICIPANT, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + VoiceConnection.prototype.unmuteParticipant = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.UNMUTE_PARTICIPANT, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; /** - * Refreshes the credentials. Users should call {get} before attempting - * to forcibly refresh credentials. - * - * @callback callback function(err) - * When this callback is called with no error, it means refreshed - * credentials information has been loaded into the object (as the - * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). - * @param err [Error] if an error occurred, this value will be filled - * @note Subclasses should override this class to reset the - * {accessKeyId}, {secretAccessKey} and optional {sessionToken} - * on the credentials object and then call the callback with - * any error information. - * @see get + * @class ChatConnection + * @param {*} contactId + * @param {*} connectionId + * @description adds the chat media specific functionality */ - refresh: function refresh(callback) { - this.expired = false; - callback(); - }, + var ChatConnection = function ChatConnection(contactId, connectionId) { + Connection.call(this, contactId, connectionId); + }; + ChatConnection.prototype = Object.create(Connection.prototype); + ChatConnection.prototype.constructor = ChatConnection; + ChatConnection.prototype.getMediaInfo = function () { + var data = this._getData().chatMediaInfo; + if (!data) { + return null; + } else { + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var mediaObject = { + contactId: this.contactId, + initialContactId: contactData.initialContactId || this.contactId, + participantId: this.connectionId, + getConnectionToken: connect.hitch(this, this.getConnectionToken) + }; + if (data.connectionData) { + try { + mediaObject.participantToken = JSON.parse(data.connectionData).ConnectionAuthenticationToken; + } catch (e) { + connect.getLog().error(connect.LogComponent.CHAT, "Connection data is invalid").withObject(data).withException(e).sendInternalLogToServer(); + mediaObject.participantToken = null; + } + } + mediaObject.participantToken = mediaObject.participantToken || null; + /** Just to keep the data accessible */ + mediaObject.originalInfo = this._getData().chatMediaInfo; + return mediaObject; + } + }; /** - * @api private - * @param callback - */ - coalesceRefresh: function coalesceRefresh(callback, sync) { - var self = this; - if (self.refreshCallbacks.push(callback) === 1) { - self.load(function onLoad(err) { - AWS.util.arrayEach(self.refreshCallbacks, function(callback) { - if (sync) { - callback(err); - } else { - // callback could throw, so defer to ensure all callbacks are notified - AWS.util.defer(function () { - callback(err); - }); - } - }); - self.refreshCallbacks.length = 0; + * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. + * @returns a promise which, upon success, returns the response from the createTransport API. + * Usage: + * connection.getConnectionToken() + * .then(response => {}) + * .catch(error => {}) + */ + ChatConnection.prototype.getConnectionToken = function () { + client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var transportDetails = { + transportType: connect.TRANSPORT_TYPES.CHAT_TOKEN, + participantId: this.connectionId, + contactId: contactData.initialContactId || this.contactId + }; + return new Promise(function (resolve, reject) { + client.call(connect.ClientMethods.CREATE_TRANSPORT, transportDetails, { + success: function success(data) { + connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err, data) { + connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + reject(Error("getConnectionToken failed")); + } }); + }); + }; + ChatConnection.prototype.getMediaType = function () { + return connect.MediaType.CHAT; + }; + ChatConnection.prototype.getMediaController = function () { + return connect.core.mediaFactory.get(this); + }; + ChatConnection.prototype._initMediaController = function () { + // Note that a chat media controller only needs to be produced for agent type connections. + if (this._isAgentConnectionType()) { + connect.core.mediaFactory.get(this)["catch"](function () {}); } - }, + }; /** - * @api private - * @param callback + * @class TaskConnection + * @param {*} contactId + * @param {*} connectionId + * @description adds the task media specific functionality */ - load: function load(callback) { - callback(); - } -}); + var TaskConnection = function TaskConnection(contactId, connectionId) { + Connection.call(this, contactId, connectionId); + }; + TaskConnection.prototype = Object.create(Connection.prototype); + TaskConnection.prototype.constructor = TaskConnection; + TaskConnection.prototype.getMediaType = function () { + return connect.MediaType.TASK; + }; + TaskConnection.prototype.getMediaInfo = function () { + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var mediaObject = { + contactId: this.contactId, + initialContactId: contactData.initialContactId || this.contactId + }; + return mediaObject; + }; + TaskConnection.prototype.getMediaController = function () { + return connect.core.mediaFactory.get(this); + }; -/** - * @api private - */ -AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) { - this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency); - this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency); -}; + /*---------------------------------------------------------------- + * class ConnectionSnapshot + */ + var ConnectionSnapshot = function ConnectionSnapshot(connectionData) { + connect.Connection.call(this, connectionData.contactId, connectionData.connectionId); + this.connectionData = connectionData; + }; + ConnectionSnapshot.prototype = Object.create(Connection.prototype); + ConnectionSnapshot.prototype.constructor = ConnectionSnapshot; + ConnectionSnapshot.prototype._getData = function () { + return this.connectionData; + }; + ConnectionSnapshot.prototype._initMediaController = function () {}; + var Endpoint = function Endpoint(paramsIn) { + var params = paramsIn || {}; + this.endpointARN = params.endpointId || params.endpointARN || null; + this.endpointId = this.endpointARN; + this.type = params.type || null; + this.name = params.name || null; + this.phoneNumber = params.phoneNumber || null; + this.agentLogin = params.agentLogin || null; + this.queue = params.queue || null; + }; -/** - * @api private - */ -AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() { - delete this.prototype.getPromise; - delete this.prototype.refreshPromise; -}; + /** + * Strip the SIP endpoint components from the phoneNumber field. + */ + Endpoint.prototype.stripPhoneNumber = function () { + return this.phoneNumber ? this.phoneNumber.replace(/sip:([^@]*)@.*/, "$1") : ""; + }; -AWS.util.addPromises(AWS.Credentials); + /** + * Create an Endpoint object from the given phone number and name. + */ + Endpoint.byPhoneNumber = function (number, name) { + return new Endpoint({ + type: connect.EndpointType.PHONE_NUMBER, + phoneNumber: number, + name: name || null + }); + }; -},{"./core":18}],20:[function(require,module,exports){ -var AWS = require('../core'); -var STS = require('../../clients/sts'); + /*---------------------------------------------------------------- + * class SoftphoneError + */ + var SoftphoneError = function SoftphoneError(errorType, errorMessage, endPointUrl) { + this.errorType = errorType; + this.errorMessage = errorMessage; + this.endPointUrl = endPointUrl; + }; + SoftphoneError.prototype.getErrorType = function () { + return this.errorType; + }; + SoftphoneError.prototype.getErrorMessage = function () { + return this.errorMessage; + }; + SoftphoneError.prototype.getEndPointUrl = function () { + return this.endPointUrl; + }; -/** - * Represents temporary credentials retrieved from {AWS.STS}. Without any - * extra parameters, credentials will be fetched from the - * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the - * {AWS.STS.assumeRole} operation will be used to fetch credentials for the - * role instead. - * - * AWS.ChainableTemporaryCredentials differs from AWS.TemporaryCredentials in - * the way masterCredentials and refreshes are handled. - * AWS.ChainableTemporaryCredentials refreshes expired credentials using the - * masterCredentials passed by the user to support chaining of STS credentials. - * However, AWS.TemporaryCredentials recursively collapses the masterCredentials - * during instantiation, precluding the ability to refresh credentials which - * require intermediate, temporary credentials. - * - * For example, if the application should use RoleA, which must be assumed from - * RoleB, and the environment provides credentials which can assume RoleB, then - * AWS.ChainableTemporaryCredentials must be used to support refreshing the - * temporary credentials for RoleA: - * - * ```javascript - * var roleACreds = new AWS.ChainableTemporaryCredentials({ - * params: {RoleArn: 'RoleA'}, - * masterCredentials: new AWS.ChainableTemporaryCredentials({ - * params: {RoleArn: 'RoleB'}, - * masterCredentials: new AWS.EnvironmentCredentials('AWS') - * }) - * }); - * ``` - * - * If AWS.TemporaryCredentials had been used in the previous example, - * `roleACreds` would fail to refresh because `roleACreds` would - * use the environment credentials for the AssumeRole request. - * - * Another difference is that AWS.ChainableTemporaryCredentials creates the STS - * service instance during instantiation while AWS.TemporaryCredentials creates - * the STS service instance during the first refresh. Creating the service - * instance during instantiation effectively captures the master credentials - * from the global config, so that subsequent changes to the global config do - * not affect the master credentials used to refresh the temporary credentials. - * - * This allows an instance of AWS.ChainableTemporaryCredentials to be assigned - * to AWS.config.credentials: - * - * ```javascript - * var envCreds = new AWS.EnvironmentCredentials('AWS'); - * AWS.config.credentials = envCreds; - * // masterCredentials will be envCreds - * AWS.config.credentials = new AWS.ChainableTemporaryCredentials({ - * params: {RoleArn: '...'} - * }); - * ``` - * - * Similarly, to use the CredentialProviderChain's default providers as the - * master credentials, simply create a new instance of - * AWS.ChainableTemporaryCredentials: - * - * ```javascript - * AWS.config.credentials = new ChainableTemporaryCredentials({ - * params: {RoleArn: '...'} - * }); - * ``` - * - * @!attribute service - * @return [AWS.STS] the STS service instance used to - * get and refresh temporary credentials from AWS STS. - * @note (see constructor) - */ -AWS.ChainableTemporaryCredentials = AWS.util.inherit(AWS.Credentials, { - /** - * Creates a new temporary credentials object. - * - * @param options [map] a set of options - * @option options params [map] ({}) a map of options that are passed to the - * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. - * If a `RoleArn` parameter is passed in, credentials will be based on the - * IAM role. If a `SerialNumber` parameter is passed in, {tokenCodeFn} must - * also be passed in or an error will be thrown. - * @option options masterCredentials [AWS.Credentials] the master credentials - * used to get and refresh temporary credentials from AWS STS. By default, - * AWS.config.credentials or AWS.config.credentialProvider will be used. - * @option options tokenCodeFn [Function] (null) Function to provide - * `TokenCode`, if `SerialNumber` is provided for profile in {params}. Function - * is called with value of `SerialNumber` and `callback`, and should provide - * the `TokenCode` or an error to the callback in the format - * `callback(err, token)`. - * @example Creating a new credentials object for generic temporary credentials - * AWS.config.credentials = new AWS.ChainableTemporaryCredentials(); - * @example Creating a new credentials object for an IAM role - * AWS.config.credentials = new AWS.ChainableTemporaryCredentials({ - * params: { - * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials' - * } - * }); - * @see AWS.STS.assumeRole - * @see AWS.STS.getSessionToken + /*---------------------------------------------------------------- + * Root Subscription APIs. */ - constructor: function ChainableTemporaryCredentials(options) { - AWS.Credentials.call(this); - options = options || {}; - this.errorCode = 'ChainableTemporaryCredentialsProviderFailure'; - this.expired = true; - this.tokenCodeFn = null; - - var params = AWS.util.copy(options.params) || {}; - if (params.RoleArn) { - params.RoleSessionName = params.RoleSessionName || 'temporary-credentials'; + connect.agent = function (f) { + var bus = connect.core.getEventBus(); + var sub = bus.subscribe(connect.AgentEvents.INIT, f); + if (connect.agent.initialized) { + f(new connect.Agent()); } - if (params.SerialNumber) { - if (!options.tokenCodeFn || (typeof options.tokenCodeFn !== 'function')) { - throw new AWS.util.error( - new Error('tokenCodeFn must be a function when params.SerialNumber is given'), - {code: this.errorCode} - ); - } else { - this.tokenCodeFn = options.tokenCodeFn; - } + return sub; + }; + connect.agent.initialized = false; + connect.contact = function (f) { + var bus = connect.core.getEventBus(); + return bus.subscribe(connect.ContactEvents.INIT, f); + }; + connect.onWebsocketInitFailure = function (f) { + var bus = connect.core.getEventBus(); + var sub = bus.subscribe(connect.WebSocketEvents.INIT_FAILURE, f); + if (connect.webSocketInitFailed) { + f(); } - var config = AWS.util.merge( - { - params: params, - credentials: options.masterCredentials || AWS.config.credentials - }, - options.stsConfig || {} - ); - this.service = new STS(config); - }, + return sub; + }; /** - * Refreshes credentials using {AWS.STS.assumeRole} or - * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed - * to the credentials {constructor}. + * Starts the given function asynchronously only if the shared worker + * says we are the master for the given topic. If there is no master for + * the given topic, we become the master and start the function unless + * shouldNotBecomeMasterIfNone is true. * - * @callback callback function(err) - * Called when the STS service responds (or fails). When - * this callback is called with no error, it means that the credentials - * information has been loaded into the object (as the `accessKeyId`, - * `secretAccessKey`, and `sessionToken` properties). - * @param err [Error] if an error occurred, this value will be filled - * @see AWS.Credentials.get - */ - refresh: function refresh(callback) { - this.coalesceRefresh(callback || AWS.util.fn.callback); - }, - - /** - * @api private - * @param callback + * @param topic The master topic we are concerned about. + * @param f_true The callback to be invoked if we are the master. + * @param f_else [optional] A callback to be invoked if we are not the master. + * @param shouldNotBecomeMasterIfNone [optional] if true, this tab won't become master. */ - load: function load(callback) { - var self = this; - var operation = self.service.config.params.RoleArn ? 'assumeRole' : 'getSessionToken'; - this.getTokenCode(function (err, tokenCode) { - var params = {}; - if (err) { - callback(err); - return; - } - if (tokenCode) { - params.TokenCode = tokenCode; + connect.ifMaster = function (topic, f_true, f_else, shouldNotBecomeMasterIfNone) { + connect.assertNotNull(topic, "A topic must be provided."); + connect.assertNotNull(f_true, "A true callback must be provided."); + if (!connect.core.masterClient) { + // We can't be the master because there is no master client! + connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic).sendInternalLogToServer(); + if (f_else) { + f_else(); } - self.service[operation](params, function (err, data) { - if (!err) { - self.service.credentialsFrom(data, self); + return; + } + var masterClient = connect.core.getMasterClient(); + masterClient.call(connect.MasterMethods.CHECK_MASTER, { + topic: topic, + shouldNotBecomeMasterIfNone: shouldNotBecomeMasterIfNone + }, { + success: function success(data) { + if (data.isMaster) { + f_true(); + } else if (f_else) { + f_else(); } - callback(err); - }); + } }); - }, + }; /** - * @api private + * Notify the shared worker and other CCP tabs that we are now the master for the given topic. */ - getTokenCode: function getTokenCode(callback) { - var self = this; - if (this.tokenCodeFn) { - this.tokenCodeFn(this.service.config.params.SerialNumber, function (err, token) { - if (err) { - var message = err; - if (err instanceof Error) { - message = err.message; + connect.becomeMaster = function (topic, successCallback, failureCallback) { + connect.assertNotNull(topic, "A topic must be provided."); + if (!connect.core.masterClient) { + // We can't be the master because there is no master client! + connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic); + if (failureCallback) { + failureCallback(); + } + } else { + var masterClient = connect.core.getMasterClient(); + masterClient.call(connect.MasterMethods.BECOME_MASTER, { + topic: topic + }, { + success: function success() { + if (successCallback) { + successCallback(); } - callback( - AWS.util.error( - new Error('Error fetching MFA token: ' + message), - { code: self.errorCode} - ) - ); - return; } - callback(null, token); }); - } else { - callback(null); } - } -}); + }; + connect.Agent = Agent; + connect.AgentSnapshot = AgentSnapshot; + connect.Contact = Contact; + connect.ContactSnapshot = ContactSnapshot; + /** Default will get the Voice connection */ + connect.Connection = VoiceConnection; + connect.BaseConnection = Connection; + connect.VoiceConnection = VoiceConnection; + connect.ChatConnection = ChatConnection; + connect.TaskConnection = TaskConnection; + connect.ConnectionSnapshot = ConnectionSnapshot; + connect.Endpoint = Endpoint; + connect.Address = Endpoint; + connect.SoftphoneError = SoftphoneError; + connect.VoiceId = VoiceId; +})(); -},{"../../clients/sts":8,"../core":18}],21:[function(require,module,exports){ -var AWS = require('../core'); -var CognitoIdentity = require('../../clients/cognitoidentity'); -var STS = require('../../clients/sts'); +/***/ }), -/** - * Represents credentials retrieved from STS Web Identity Federation using - * the Amazon Cognito Identity service. +/***/ 538: +/***/ ((module, exports, __webpack_require__) => { + +var __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o;}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o;},_typeof(o);}// AWS SDK for JavaScript v2.553.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=undefined;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r);},p,p.exports,r,e,n,t);}return n[i].exports;}for(var u=undefined,i=0;i-1;};}/** + * @api private + */var viewStrings=['[object Int8Array]','[object Uint8Array]','[object Uint8ClampedArray]','[object Int16Array]','[object Uint16Array]','[object Int32Array]','[object Uint32Array]','[object Float32Array]','[object Float64Array]','[object DataView]'];/** + * @api private + */function isEmptyData(data){if(typeof data==='string'){return data.length===0;}return data.byteLength===0;}/** + * @api private + */function convertToBuffer(data){if(typeof data==='string'){data=new Buffer(data,'utf8');}if(ArrayBuffer.isView(data)){return new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT);}return new Uint8Array(data);}/** + * @api private + */module.exports=exports={isEmptyData:isEmptyData,convertToBuffer:convertToBuffer};},{"buffer/":81}],12:[function(require,module,exports){var hashUtils=require('./browserHashUtils');/** + * @api private + */function Hmac(hashCtor,secret){this.hash=new hashCtor();this.outer=new hashCtor();var inner=bufferFromSecret(hashCtor,secret);var outer=new Uint8Array(hashCtor.BLOCK_SIZE);outer.set(inner);for(var i=0;ihashCtor.BLOCK_SIZE){var bufferHash=new hashCtor();bufferHash.update(input);input=bufferHash.digest();}var buffer=new Uint8Array(hashCtor.BLOCK_SIZE);buffer.set(input);return buffer;}},{"./browserHashUtils":11}],13:[function(require,module,exports){var hashUtils=require('./browserHashUtils');var Buffer=require('buffer/').Buffer;var BLOCK_SIZE=64;var DIGEST_LENGTH=16;var INIT=[0x67452301,0xefcdab89,0x98badcfe,0x10325476];/** + * @api private + */function Md5(){this.state=[0x67452301,0xefcdab89,0x98badcfe,0x10325476];this.buffer=new DataView(new ArrayBuffer(BLOCK_SIZE));this.bufferLength=0;this.bytesHashed=0;this.finished=false;}/** + * @api private + */module.exports=exports=Md5;Md5.BLOCK_SIZE=BLOCK_SIZE;Md5.prototype.update=function(sourceData){if(hashUtils.isEmptyData(sourceData)){return this;}else if(this.finished){throw new Error('Attempted to update an already finished hash.');}var data=hashUtils.convertToBuffer(sourceData);var position=0;var byteLength=data.byteLength;this.bytesHashed+=byteLength;while(byteLength>0){this.buffer.setUint8(this.bufferLength++,data[position++]);byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0;}}return this;};Md5.prototype.digest=function(encoding){if(!this.finished){var _a=this,buffer=_a.buffer,undecoratedLength=_a.bufferLength,bytesHashed=_a.bytesHashed;var bitsHashed=bytesHashed*8;buffer.setUint8(this.bufferLength++,128);// Ensure the final block has enough room for the hashed length +if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(var i=this.bufferLength;i>>0,true);buffer.setUint32(BLOCK_SIZE-4,Math.floor(bitsHashed/0x100000000),true);this.hashBuffer();this.finished=true;}var out=new DataView(new ArrayBuffer(DIGEST_LENGTH));for(var i=0;i<4;i++){out.setUint32(i*4,this.state[i],true);}var buff=new Buffer(out.buffer,out.byteOffset,out.byteLength);return encoding?buff.toString(encoding):buff;};Md5.prototype.hashBuffer=function(){var _a=this,buffer=_a.buffer,state=_a.state;var a=state[0],b=state[1],c=state[2],d=state[3];a=ff(a,b,c,d,buffer.getUint32(0,true),7,0xd76aa478);d=ff(d,a,b,c,buffer.getUint32(4,true),12,0xe8c7b756);c=ff(c,d,a,b,buffer.getUint32(8,true),17,0x242070db);b=ff(b,c,d,a,buffer.getUint32(12,true),22,0xc1bdceee);a=ff(a,b,c,d,buffer.getUint32(16,true),7,0xf57c0faf);d=ff(d,a,b,c,buffer.getUint32(20,true),12,0x4787c62a);c=ff(c,d,a,b,buffer.getUint32(24,true),17,0xa8304613);b=ff(b,c,d,a,buffer.getUint32(28,true),22,0xfd469501);a=ff(a,b,c,d,buffer.getUint32(32,true),7,0x698098d8);d=ff(d,a,b,c,buffer.getUint32(36,true),12,0x8b44f7af);c=ff(c,d,a,b,buffer.getUint32(40,true),17,0xffff5bb1);b=ff(b,c,d,a,buffer.getUint32(44,true),22,0x895cd7be);a=ff(a,b,c,d,buffer.getUint32(48,true),7,0x6b901122);d=ff(d,a,b,c,buffer.getUint32(52,true),12,0xfd987193);c=ff(c,d,a,b,buffer.getUint32(56,true),17,0xa679438e);b=ff(b,c,d,a,buffer.getUint32(60,true),22,0x49b40821);a=gg(a,b,c,d,buffer.getUint32(4,true),5,0xf61e2562);d=gg(d,a,b,c,buffer.getUint32(24,true),9,0xc040b340);c=gg(c,d,a,b,buffer.getUint32(44,true),14,0x265e5a51);b=gg(b,c,d,a,buffer.getUint32(0,true),20,0xe9b6c7aa);a=gg(a,b,c,d,buffer.getUint32(20,true),5,0xd62f105d);d=gg(d,a,b,c,buffer.getUint32(40,true),9,0x02441453);c=gg(c,d,a,b,buffer.getUint32(60,true),14,0xd8a1e681);b=gg(b,c,d,a,buffer.getUint32(16,true),20,0xe7d3fbc8);a=gg(a,b,c,d,buffer.getUint32(36,true),5,0x21e1cde6);d=gg(d,a,b,c,buffer.getUint32(56,true),9,0xc33707d6);c=gg(c,d,a,b,buffer.getUint32(12,true),14,0xf4d50d87);b=gg(b,c,d,a,buffer.getUint32(32,true),20,0x455a14ed);a=gg(a,b,c,d,buffer.getUint32(52,true),5,0xa9e3e905);d=gg(d,a,b,c,buffer.getUint32(8,true),9,0xfcefa3f8);c=gg(c,d,a,b,buffer.getUint32(28,true),14,0x676f02d9);b=gg(b,c,d,a,buffer.getUint32(48,true),20,0x8d2a4c8a);a=hh(a,b,c,d,buffer.getUint32(20,true),4,0xfffa3942);d=hh(d,a,b,c,buffer.getUint32(32,true),11,0x8771f681);c=hh(c,d,a,b,buffer.getUint32(44,true),16,0x6d9d6122);b=hh(b,c,d,a,buffer.getUint32(56,true),23,0xfde5380c);a=hh(a,b,c,d,buffer.getUint32(4,true),4,0xa4beea44);d=hh(d,a,b,c,buffer.getUint32(16,true),11,0x4bdecfa9);c=hh(c,d,a,b,buffer.getUint32(28,true),16,0xf6bb4b60);b=hh(b,c,d,a,buffer.getUint32(40,true),23,0xbebfbc70);a=hh(a,b,c,d,buffer.getUint32(52,true),4,0x289b7ec6);d=hh(d,a,b,c,buffer.getUint32(0,true),11,0xeaa127fa);c=hh(c,d,a,b,buffer.getUint32(12,true),16,0xd4ef3085);b=hh(b,c,d,a,buffer.getUint32(24,true),23,0x04881d05);a=hh(a,b,c,d,buffer.getUint32(36,true),4,0xd9d4d039);d=hh(d,a,b,c,buffer.getUint32(48,true),11,0xe6db99e5);c=hh(c,d,a,b,buffer.getUint32(60,true),16,0x1fa27cf8);b=hh(b,c,d,a,buffer.getUint32(8,true),23,0xc4ac5665);a=ii(a,b,c,d,buffer.getUint32(0,true),6,0xf4292244);d=ii(d,a,b,c,buffer.getUint32(28,true),10,0x432aff97);c=ii(c,d,a,b,buffer.getUint32(56,true),15,0xab9423a7);b=ii(b,c,d,a,buffer.getUint32(20,true),21,0xfc93a039);a=ii(a,b,c,d,buffer.getUint32(48,true),6,0x655b59c3);d=ii(d,a,b,c,buffer.getUint32(12,true),10,0x8f0ccc92);c=ii(c,d,a,b,buffer.getUint32(40,true),15,0xffeff47d);b=ii(b,c,d,a,buffer.getUint32(4,true),21,0x85845dd1);a=ii(a,b,c,d,buffer.getUint32(32,true),6,0x6fa87e4f);d=ii(d,a,b,c,buffer.getUint32(60,true),10,0xfe2ce6e0);c=ii(c,d,a,b,buffer.getUint32(24,true),15,0xa3014314);b=ii(b,c,d,a,buffer.getUint32(52,true),21,0x4e0811a1);a=ii(a,b,c,d,buffer.getUint32(16,true),6,0xf7537e82);d=ii(d,a,b,c,buffer.getUint32(44,true),10,0xbd3af235);c=ii(c,d,a,b,buffer.getUint32(8,true),15,0x2ad7d2bb);b=ii(b,c,d,a,buffer.getUint32(36,true),21,0xeb86d391);state[0]=a+state[0]&0xFFFFFFFF;state[1]=b+state[1]&0xFFFFFFFF;state[2]=c+state[2]&0xFFFFFFFF;state[3]=d+state[3]&0xFFFFFFFF;};function cmn(q,a,b,x,s,t){a=(a+q&0xFFFFFFFF)+(x+t&0xFFFFFFFF)&0xFFFFFFFF;return(a<>>32-s)+b&0xFFFFFFFF;}function ff(a,b,c,d,x,s,t){return cmn(b&c|~b&d,a,b,x,s,t);}function gg(a,b,c,d,x,s,t){return cmn(b&d|c&~d,a,b,x,s,t);}function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);}function ii(a,b,c,d,x,s,t){return cmn(c^(b|~d),a,b,x,s,t);}},{"./browserHashUtils":11,"buffer/":81}],14:[function(require,module,exports){var Buffer=require('buffer/').Buffer;var hashUtils=require('./browserHashUtils');var BLOCK_SIZE=64;var DIGEST_LENGTH=20;var KEY=new Uint32Array([0x5a827999,0x6ed9eba1,0x8f1bbcdc|0,0xca62c1d6|0]);var INIT=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];var MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;/** + * @api private + */function Sha1(){this.h0=0x67452301;this.h1=0xEFCDAB89;this.h2=0x98BADCFE;this.h3=0x10325476;this.h4=0xC3D2E1F0;// The first 64 bytes (16 words) is the data chunk +this.block=new Uint32Array(80);this.offset=0;this.shift=24;this.totalLength=0;}/** + * @api private + */module.exports=exports=Sha1;Sha1.BLOCK_SIZE=BLOCK_SIZE;Sha1.prototype.update=function(data){if(this.finished){throw new Error('Attempted to update an already finished hash.');}if(hashUtils.isEmptyData(data)){return this;}data=hashUtils.convertToBuffer(data);var length=data.length;this.totalLength+=length*8;for(var i=0;i14||this.offset===14&&this.shift<24){this.processBlock();}this.offset=14;this.shift=24;// 64-bit length big-endian +this.write(0x00);// numbers this big aren't accurate in javascript anyway +this.write(0x00);// ..So just hard-code to zero. +this.write(this.totalLength>0xffffffffff?this.totalLength/0x10000000000:0x00);this.write(this.totalLength>0xffffffff?this.totalLength/0x100000000:0x00);for(var s=24;s>=0;s-=8){this.write(this.totalLength>>s);}// The value in state is little-endian rather than big-endian, so flip +// each word into a new Uint8Array +var out=new Buffer(DIGEST_LENGTH);var outView=new DataView(out.buffer);outView.setUint32(0,this.h0,false);outView.setUint32(4,this.h1,false);outView.setUint32(8,this.h2,false);outView.setUint32(12,this.h3,false);outView.setUint32(16,this.h4,false);return encoding?out.toString(encoding):out;};Sha1.prototype.processBlock=function processBlock(){// Extend the sixteen 32-bit words into eighty 32-bit words: +for(var i=16;i<80;i++){var w=this.block[i-3]^this.block[i-8]^this.block[i-14]^this.block[i-16];this.block[i]=w<<1|w>>>31;}// Initialize hash value for this chunk: +var a=this.h0;var b=this.h1;var c=this.h2;var d=this.h3;var e=this.h4;var f,k;// Main loop: +for(i=0;i<80;i++){if(i<20){f=d^b&(c^d);k=0x5A827999;}else if(i<40){f=b^c^d;k=0x6ED9EBA1;}else if(i<60){f=b&c|d&(b|c);k=0x8F1BBCDC;}else{f=b^c^d;k=0xCA62C1D6;}var temp=(a<<5|a>>>27)+f+e+k+(this.block[i]|0);e=d;d=c;c=b<<30|b>>>2;b=a;a=temp;}// Add this chunk's hash to result so far: +this.h0=this.h0+a|0;this.h1=this.h1+b|0;this.h2=this.h2+c|0;this.h3=this.h3+d|0;this.h4=this.h4+e|0;// The block is now reusable. +this.offset=0;for(i=0;i<16;i++){this.block[i]=0;}};},{"./browserHashUtils":11,"buffer/":81}],15:[function(require,module,exports){var Buffer=require('buffer/').Buffer;var hashUtils=require('./browserHashUtils');var BLOCK_SIZE=64;var DIGEST_LENGTH=32;var KEY=new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]);var INIT=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];var MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;/** + * @private + */function Sha256(){this.state=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];this.temp=new Int32Array(64);this.buffer=new Uint8Array(64);this.bufferLength=0;this.bytesHashed=0;/** + * @private + */this.finished=false;}/** + * @api private + */module.exports=exports=Sha256;Sha256.BLOCK_SIZE=BLOCK_SIZE;Sha256.prototype.update=function(data){if(this.finished){throw new Error('Attempted to update an already finished hash.');}if(hashUtils.isEmptyData(data)){return this;}data=hashUtils.convertToBuffer(data);var position=0;var byteLength=data.byteLength;this.bytesHashed+=byteLength;if(this.bytesHashed*8>MAX_HASHABLE_LENGTH){throw new Error('Cannot hash more than 2^53 - 1 bits');}while(byteLength>0){this.buffer[this.bufferLength++]=data[position++];byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0;}}return this;};Sha256.prototype.digest=function(encoding){if(!this.finished){var bitsHashed=this.bytesHashed*8;var bufferView=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength);var undecoratedLength=this.bufferLength;bufferView.setUint8(this.bufferLength++,0x80);// Ensure the final block has enough room for the hashed length +if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(var i=this.bufferLength;i>>24&0xff;out[i*4+1]=this.state[i]>>>16&0xff;out[i*4+2]=this.state[i]>>>8&0xff;out[i*4+3]=this.state[i]>>>0&0xff;}return encoding?out.toString(encoding):out;};Sha256.prototype.hashBuffer=function(){var _a=this,buffer=_a.buffer,state=_a.state;var state0=state[0],state1=state[1],state2=state[2],state3=state[3],state4=state[4],state5=state[5],state6=state[6],state7=state[7];for(var i=0;i>>17|u<<15)^(u>>>19|u<<13)^u>>>10;u=this.temp[i-15];var t2_1=(u>>>7|u<<25)^(u>>>18|u<<14)^u>>>3;this.temp[i]=(t1_1+this.temp[i-7]|0)+(t2_1+this.temp[i-16]|0);}var t1=(((state4>>>6|state4<<26)^(state4>>>11|state4<<21)^(state4>>>25|state4<<7))+(state4&state5^~state4&state6)|0)+(state7+(KEY[i]+this.temp[i]|0)|0)|0;var t2=((state0>>>2|state0<<30)^(state0>>>13|state0<<19)^(state0>>>22|state0<<10))+(state0&state1^state0&state2^state1&state2)|0;state7=state6;state6=state5;state5=state4;state4=state3+t1|0;state3=state2;state2=state1;state1=state0;state0=t1+t2|0;}state[0]+=state0;state[1]+=state1;state[2]+=state2;state[3]+=state3;state[4]+=state4;state[5]+=state5;state[6]+=state6;state[7]+=state7;};},{"./browserHashUtils":11,"buffer/":81}],16:[function(require,module,exports){(function(process){(function(){var util=require('./util');// browser specific modules +util.crypto.lib=require('./browserCryptoLib');util.Buffer=require('buffer/').Buffer;util.url=require('url/');util.querystring=require('querystring/');util.realClock=require('./realclock/browserClock');util.environment='js';util.createEventStream=require('./event-stream/buffered-create-event-stream').createEventStream;util.isBrowser=function(){return true;};util.isNode=function(){return false;};var AWS=require('./core');/** + * @api private + */module.exports=AWS;require('./credentials');require('./credentials/credential_provider_chain');require('./credentials/temporary_credentials');require('./credentials/chainable_temporary_credentials');require('./credentials/web_identity_credentials');require('./credentials/cognito_identity_credentials');require('./credentials/saml_credentials');// Load the DOMParser XML parser +AWS.XML.Parser=require('./xml/browser_parser');// Load the XHR HttpClient +require('./http/xhr');if(typeof process==='undefined'){var process={browser:true};}}).call(this);}).call(this,require('_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(require,module,exports){var AWS=require('./core');require('./credentials');require('./credentials/credential_provider_chain');var PromisesDependency;/** + * The main configuration class used by all service objects to set + * the region, credentials, and other options for requests. * - * ## Refreshing Credentials from Identity Service + * By default, credentials and region settings are left unconfigured. + * This should be configured by the application before using any + * AWS service APIs. * - * In addition to AWS credentials expiring after a given amount of time, the - * login token from the identity provider will also expire. Once this token - * expires, it will not be usable to refresh AWS credentials, and another - * token will be needed. The SDK does not manage refreshing of the token value, - * but this can be done through a "refresh token" supported by most identity - * providers. Consult the documentation for the identity provider for refreshing - * tokens. Once the refreshed token is acquired, you should make sure to update - * this new token in the credentials object's {params} property. The following - * code will update the WebIdentityToken, assuming you have retrieved an updated - * token from the identity provider: + * In order to set global configuration options, properties should + * be assigned to the global {AWS.config} object. * - * ```javascript - * AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken; - * ``` + * @see AWS.config * - * Future calls to `credentials.refresh()` will now use the new token. + * @!group General Configuration Options * - * @!attribute params - * @return [map] the map of params passed to - * {AWS.CognitoIdentity.getId}, - * {AWS.CognitoIdentity.getOpenIdToken}, and - * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the - * `params.WebIdentityToken` property. - * @!attribute data - * @return [map] the raw data response from the call to - * {AWS.CognitoIdentity.getCredentialsForIdentity}, or - * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get - * access to other properties from the response. - * @!attribute identityId - * @return [String] the Cognito ID returned by the last call to - * {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual - * final resolved identity ID from Amazon Cognito. - */ -AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, { - /** - * @api private - */ - localStorageKey: { - id: 'aws.cognito.identity-id.', - providers: 'aws.cognito.identity-providers.' - }, - - /** - * Creates a new credentials object. - * @example Creating a new credentials object - * AWS.config.credentials = new AWS.CognitoIdentityCredentials({ - * - * // either IdentityPoolId or IdentityId is required - * // See the IdentityPoolId param for AWS.CognitoIdentity.getID (linked below) - * // See the IdentityId param for AWS.CognitoIdentity.getCredentialsForIdentity - * // or AWS.CognitoIdentity.getOpenIdToken (linked below) - * IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030', - * IdentityId: 'us-east-1:128d0a74-c82f-4553-916d-90053e4a8b0f' - * - * // optional, only necessary when the identity pool is not configured - * // to use IAM roles in the Amazon Cognito Console - * // See the RoleArn param for AWS.STS.assumeRoleWithWebIdentity (linked below) - * RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity', - * - * // optional tokens, used for authenticated login - * // See the Logins param for AWS.CognitoIdentity.getID (linked below) - * Logins: { - * 'graph.facebook.com': 'FBTOKEN', - * 'www.amazon.com': 'AMAZONTOKEN', - * 'accounts.google.com': 'GOOGLETOKEN', - * 'api.twitter.com': 'TWITTERTOKEN', - * 'www.digits.com': 'DIGITSTOKEN' - * }, - * - * // optional name, defaults to web-identity - * // See the RoleSessionName param for AWS.STS.assumeRoleWithWebIdentity (linked below) - * RoleSessionName: 'web', - * - * // optional, only necessary when application runs in a browser - * // and multiple users are signed in at once, used for caching - * LoginId: 'example@gmail.com' - * - * }, { - * // optionally provide configuration to apply to the underlying service clients - * // if configuration is not provided, then configuration will be pulled from AWS.config - * - * // region should match the region your identity pool is located in - * region: 'us-east-1', - * - * // specify timeout options - * httpOptions: { - * timeout: 100 - * } - * }); - * @see AWS.CognitoIdentity.getId - * @see AWS.CognitoIdentity.getCredentialsForIdentity - * @see AWS.STS.assumeRoleWithWebIdentity - * @see AWS.CognitoIdentity.getOpenIdToken - * @see AWS.Config - * @note If a region is not provided in the global AWS.config, or - * specified in the `clientConfig` to the CognitoIdentityCredentials - * constructor, you may encounter a 'Missing credentials in config' error - * when calling making a service call. - */ - constructor: function CognitoIdentityCredentials(params, clientConfig) { - AWS.Credentials.call(this); - this.expired = true; - this.params = params; - this.data = null; - this._identityId = null; - this._clientConfig = AWS.util.copy(clientConfig || {}); - this.loadCachedId(); - var self = this; - Object.defineProperty(this, 'identityId', { - get: function() { - self.loadCachedId(); - return self._identityId || self.params.IdentityId; - }, - set: function(identityId) { - self._identityId = identityId; - } - }); - }, - - /** - * Refreshes credentials using {AWS.CognitoIdentity.getCredentialsForIdentity}, - * or {AWS.STS.assumeRoleWithWebIdentity}. - * - * @callback callback function(err) - * Called when the STS service responds (or fails). When - * this callback is called with no error, it means that the credentials - * information has been loaded into the object (as the `accessKeyId`, - * `secretAccessKey`, and `sessionToken` properties). - * @param err [Error] if an error occurred, this value will be filled - * @see AWS.Credentials.get - */ - refresh: function refresh(callback) { - this.coalesceRefresh(callback || AWS.util.fn.callback); - }, - - /** - * @api private - * @param callback - */ - load: function load(callback) { - var self = this; - self.createClients(); - self.data = null; - self._identityId = null; - self.getId(function(err) { - if (!err) { - if (!self.params.RoleArn) { - self.getCredentialsForIdentity(callback); - } else { - self.getCredentialsFromSTS(callback); - } - } else { - self.clearIdOnNotAuthorized(err); - callback(err); - } - }); - }, - - /** - * Clears the cached Cognito ID associated with the currently configured - * identity pool ID. Use this to manually invalidate your cache if - * the identity pool ID was deleted. - */ - clearCachedId: function clearCache() { - this._identityId = null; - delete this.params.IdentityId; - - var poolId = this.params.IdentityPoolId; - var loginId = this.params.LoginId || ''; - delete this.storage[this.localStorageKey.id + poolId + loginId]; - delete this.storage[this.localStorageKey.providers + poolId + loginId]; - }, - - /** - * @api private - */ - clearIdOnNotAuthorized: function clearIdOnNotAuthorized(err) { - var self = this; - if (err.code == 'NotAuthorizedException') { - self.clearCachedId(); - } - }, - - /** - * Retrieves a Cognito ID, loading from cache if it was already retrieved - * on this device. - * - * @callback callback function(err, identityId) - * @param err [Error, null] an error object if the call failed or null if - * it succeeded. - * @param identityId [String, null] if successful, the callback will return - * the Cognito ID. - * @note If not loaded explicitly, the Cognito ID is loaded and stored in - * localStorage in the browser environment of a device. - * @api private - */ - getId: function getId(callback) { - var self = this; - if (typeof self.params.IdentityId === 'string') { - return callback(null, self.params.IdentityId); - } - - self.cognito.getId(function(err, data) { - if (!err && data.IdentityId) { - self.params.IdentityId = data.IdentityId; - callback(null, data.IdentityId); - } else { - callback(err); - } - }); - }, - - - /** - * @api private - */ - loadCredentials: function loadCredentials(data, credentials) { - if (!data || !credentials) return; - credentials.expired = false; - credentials.accessKeyId = data.Credentials.AccessKeyId; - credentials.secretAccessKey = data.Credentials.SecretKey; - credentials.sessionToken = data.Credentials.SessionToken; - credentials.expireTime = data.Credentials.Expiration; - }, - - /** - * @api private - */ - getCredentialsForIdentity: function getCredentialsForIdentity(callback) { - var self = this; - self.cognito.getCredentialsForIdentity(function(err, data) { - if (!err) { - self.cacheId(data); - self.data = data; - self.loadCredentials(self.data, self); - } else { - self.clearIdOnNotAuthorized(err); - } - callback(err); - }); - }, - - /** - * @api private - */ - getCredentialsFromSTS: function getCredentialsFromSTS(callback) { - var self = this; - self.cognito.getOpenIdToken(function(err, data) { - if (!err) { - self.cacheId(data); - self.params.WebIdentityToken = data.Token; - self.webIdentityCredentials.refresh(function(webErr) { - if (!webErr) { - self.data = self.webIdentityCredentials.data; - self.sts.credentialsFrom(self.data, self); - } - callback(webErr); - }); - } else { - self.clearIdOnNotAuthorized(err); - callback(err); - } - }); - }, - - /** - * @api private - */ - loadCachedId: function loadCachedId() { - var self = this; - - // in the browser we source default IdentityId from localStorage - if (AWS.util.isBrowser() && !self.params.IdentityId) { - var id = self.getStorage('id'); - if (id && self.params.Logins) { - var actualProviders = Object.keys(self.params.Logins); - var cachedProviders = - (self.getStorage('providers') || '').split(','); - - // only load ID if at least one provider used this ID before - var intersect = cachedProviders.filter(function(n) { - return actualProviders.indexOf(n) !== -1; - }); - if (intersect.length !== 0) { - self.params.IdentityId = id; - } - } else if (id) { - self.params.IdentityId = id; - } - } - }, - - /** - * @api private - */ - createClients: function() { - var clientConfig = this._clientConfig; - this.webIdentityCredentials = this.webIdentityCredentials || - new AWS.WebIdentityCredentials(this.params, clientConfig); - if (!this.cognito) { - var cognitoConfig = AWS.util.merge({}, clientConfig); - cognitoConfig.params = this.params; - this.cognito = new CognitoIdentity(cognitoConfig); - } - this.sts = this.sts || new STS(clientConfig); - }, - - /** - * @api private - */ - cacheId: function cacheId(data) { - this._identityId = data.IdentityId; - this.params.IdentityId = this._identityId; - - // cache this IdentityId in browser localStorage if possible - if (AWS.util.isBrowser()) { - this.setStorage('id', data.IdentityId); - - if (this.params.Logins) { - this.setStorage('providers', Object.keys(this.params.Logins).join(',')); - } - } - }, - - /** - * @api private - */ - getStorage: function getStorage(key) { - return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')]; - }, - - /** - * @api private - */ - setStorage: function setStorage(key, val) { - try { - this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')] = val; - } catch (_) {} - }, - - /** - * @api private - */ - storage: (function() { - try { - var storage = AWS.util.isBrowser() && window.localStorage !== null && typeof window.localStorage === 'object' ? - window.localStorage : {}; - - // Test set/remove which would throw an error in Safari's private browsing - storage['aws.test-storage'] = 'foobar'; - delete storage['aws.test-storage']; - - return storage; - } catch (_) { - return {}; - } - })() -}); - -},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(require,module,exports){ -var AWS = require('../core'); - -/** - * Creates a credential provider chain that searches for AWS credentials - * in a list of credential providers specified by the {providers} property. + * @!attribute credentials + * @return [AWS.Credentials] the AWS credentials to sign requests with. * - * By default, the chain will use the {defaultProviders} to resolve credentials. - * These providers will look in the environment using the - * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes. + * @!attribute region + * @example Set the global region setting to us-west-2 + * AWS.config.update({region: 'us-west-2'}); + * @return [AWS.Credentials] The region to send service requests to. + * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html + * A list of available endpoints for each AWS service * - * ## Setting Providers + * @!attribute maxRetries + * @return [Integer] the maximum amount of retries to perform for a + * service request. By default this value is calculated by the specific + * service object that the request is being made to. * - * Each provider in the {providers} list should be a function that returns - * a {AWS.Credentials} object, or a hardcoded credentials object. The function - * form allows for delayed execution of the credential construction. + * @!attribute maxRedirects + * @return [Integer] the maximum amount of redirects to follow for a + * service request. Defaults to 10. * - * ## Resolving Credentials from a Chain + * @!attribute paramValidation + * @return [Boolean|map] whether input parameters should be validated against + * the operation description before sending the request. Defaults to true. + * Pass a map to enable any of the following specific validation features: * - * Call {resolve} to return the first valid credential object that can be - * loaded by the provider chain. + * * **min** [Boolean] — Validates that a value meets the min + * constraint. This is enabled by default when paramValidation is set + * to `true`. + * * **max** [Boolean] — Validates that a value meets the max + * constraint. + * * **pattern** [Boolean] — Validates that a string value matches a + * regular expression. + * * **enum** [Boolean] — Validates that a string value matches one + * of the allowable enum values. * - * For example, to resolve a chain with a custom provider that checks a file - * on disk after the set of {defaultProviders}: + * @!attribute computeChecksums + * @return [Boolean] whether to compute checksums for payload bodies when + * the service accepts it (currently supported in S3 only). * - * ```javascript - * var diskProvider = new AWS.FileSystemCredentials('./creds.json'); - * var chain = new AWS.CredentialProviderChain(); - * chain.providers.push(diskProvider); - * chain.resolve(); - * ``` + * @!attribute convertResponseTypes + * @return [Boolean] whether types are converted when parsing response data. + * Currently only supported for JSON based services. Turning this off may + * improve performance on large response payloads. Defaults to `true`. * - * The above code will return the `diskProvider` object if the - * file contains credentials and the `defaultProviders` do not contain - * any credential settings. - * - * @!attribute providers - * @return [Array] - * a list of credentials objects or functions that return credentials - * objects. If the provider is a function, the function will be - * executed lazily when the provider needs to be checked for valid - * credentials. By default, this object will be set to the - * {defaultProviders}. - * @see defaultProviders - */ -AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, { - - /** - * Creates a new CredentialProviderChain with a default set of providers - * specified by {defaultProviders}. - */ - constructor: function CredentialProviderChain(providers) { - if (providers) { - this.providers = providers; - } else { - this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0); - } - this.resolveCallbacks = []; - }, - - /** - * @!method resolvePromise() - * Returns a 'thenable' promise. - * Resolves the provider chain by searching for the first set of - * credentials in {providers}. - * - * Two callbacks can be provided to the `then` method on the returned promise. - * The first callback will be called if the promise is fulfilled, and the second - * callback will be called if the promise is rejected. - * @callback fulfilledCallback function(credentials) - * Called if the promise is fulfilled and the provider resolves the chain - * to a credentials object - * @param credentials [AWS.Credentials] the credentials object resolved - * by the provider chain. - * @callback rejectedCallback function(error) - * Called if the promise is rejected. - * @param err [Error] the error object returned if no credentials are found. - * @return [Promise] A promise that represents the state of the `resolve` method call. - * @example Calling the `resolvePromise` method. - * var promise = chain.resolvePromise(); - * promise.then(function(credentials) { ... }, function(err) { ... }); - */ - - /** - * Resolves the provider chain by searching for the first set of - * credentials in {providers}. - * - * @callback callback function(err, credentials) - * Called when the provider resolves the chain to a credentials object - * or null if no credentials can be found. - * - * @param err [Error] the error object returned if no credentials are - * found. - * @param credentials [AWS.Credentials] the credentials object resolved - * by the provider chain. - * @return [AWS.CredentialProviderChain] the provider, for chaining. - */ - resolve: function resolve(callback) { - var self = this; - if (self.providers.length === 0) { - callback(new Error('No providers')); - return self; - } - - if (self.resolveCallbacks.push(callback) === 1) { - var index = 0; - var providers = self.providers.slice(0); - - function resolveNext(err, creds) { - if ((!err && creds) || index === providers.length) { - AWS.util.arrayEach(self.resolveCallbacks, function (callback) { - callback(err, creds); - }); - self.resolveCallbacks.length = 0; - return; - } - - var provider = providers[index++]; - if (typeof provider === 'function') { - creds = provider.call(); - } else { - creds = provider; - } - - if (creds.get) { - creds.get(function (getErr) { - resolveNext(getErr, getErr ? null : creds); - }); - } else { - resolveNext(null, creds); - } - } - - resolveNext(); - } - - return self; - } -}); - -/** - * The default set of providers used by a vanilla CredentialProviderChain. + * @!attribute correctClockSkew + * @return [Boolean] whether to apply a clock skew correction and retry + * requests that fail because of an skewed client clock. Defaults to + * `false`. * - * In the browser: + * @!attribute sslEnabled + * @return [Boolean] whether SSL is enabled for requests * - * ```javascript - * AWS.CredentialProviderChain.defaultProviders = [] - * ``` + * @!attribute s3ForcePathStyle + * @return [Boolean] whether to force path style URLs for S3 objects * - * In Node.js: + * @!attribute s3BucketEndpoint + * @note Setting this configuration option requires an `endpoint` to be + * provided explicitly to the service constructor. + * @return [Boolean] whether the provided endpoint addresses an individual + * bucket (false if it addresses the root API endpoint). * - * ```javascript - * AWS.CredentialProviderChain.defaultProviders = [ - * function () { return new AWS.EnvironmentCredentials('AWS'); }, - * function () { return new AWS.EnvironmentCredentials('AMAZON'); }, - * function () { return new AWS.SharedIniFileCredentials(); }, - * function () { return new AWS.ECSCredentials(); }, - * function () { return new AWS.ProcessCredentials(); }, - * function () { return new AWS.TokenFileWebIdentityCredentials(); }, - * function () { return new AWS.EC2MetadataCredentials() } - * ] - * ``` - */ -AWS.CredentialProviderChain.defaultProviders = []; - -/** - * @api private - */ -AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) { - this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency); -}; - -/** - * @api private - */ -AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() { - delete this.prototype.resolvePromise; -}; - -AWS.util.addPromises(AWS.CredentialProviderChain); - -},{"../core":18}],23:[function(require,module,exports){ -var AWS = require('../core'); -var STS = require('../../clients/sts'); - -/** - * Represents credentials retrieved from STS SAML support. + * @!attribute s3DisableBodySigning + * @return [Boolean] whether to disable S3 body signing when using signature version `v4`. + * Body signing can only be disabled when using https. Defaults to `true`. * - * By default this provider gets credentials using the - * {AWS.STS.assumeRoleWithSAML} service operation. This operation - * requires a `RoleArn` containing the ARN of the IAM trust policy for the - * application for which credentials will be given, as well as a `PrincipalArn` - * representing the ARN for the SAML identity provider. In addition, the - * `SAMLAssertion` must be set to the token provided by the identity - * provider. See {constructor} for an example on creating a credentials - * object with proper `RoleArn`, `PrincipalArn`, and `SAMLAssertion` values. + * @!attribute useAccelerateEndpoint + * @note This configuration option is only compatible with S3 while accessing + * dns-compatible buckets. + * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service. + * Defaults to `false`. * - * ## Refreshing Credentials from Identity Service + * @!attribute retryDelayOptions + * @example Set the base retry delay for all services to 300 ms + * AWS.config.update({retryDelayOptions: {base: 300}}); + * // Delays with maxRetries = 3: 300, 600, 1200 + * @example Set a custom backoff function to provide delay values on retries + * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) { + * // returns delay in ms + * }}}); + * @return [map] A set of options to configure the retry delay on retryable errors. + * Currently supported options are: * - * In addition to AWS credentials expiring after a given amount of time, the - * login token from the identity provider will also expire. Once this token - * expires, it will not be usable to refresh AWS credentials, and another - * token will be needed. The SDK does not manage refreshing of the token value, - * but this can be done through a "refresh token" supported by most identity - * providers. Consult the documentation for the identity provider for refreshing - * tokens. Once the refreshed token is acquired, you should make sure to update - * this new token in the credentials object's {params} property. The following - * code will update the SAMLAssertion, assuming you have retrieved an updated - * token from the identity provider: + * * **base** [Integer] — The base number of milliseconds to use in the + * exponential backoff for operation retries. Defaults to 100 ms for all services except + * DynamoDB, where it defaults to 50ms. + * * **customBackoff ** [function] — A custom function that accepts a retry count + * and returns the amount of time to delay in milliseconds. The `base` option will be + * ignored if this option is supplied. * - * ```javascript - * AWS.config.credentials.params.SAMLAssertion = updatedToken; - * ``` + * @!attribute httpOptions + * @return [map] A set of options to pass to the low-level HTTP request. + * Currently supported options are: * - * Future calls to `credentials.refresh()` will now use the new token. + * * **proxy** [String] — the URL to proxy requests through + * * **agent** [http.Agent, https.Agent] — the Agent object to perform + * HTTP requests with. Used for connection pooling. Note that for + * SSL connections, a special Agent object is used in order to enable + * peer certificate verification. This feature is only supported in the + * Node.js environment. + * * **connectTimeout** [Integer] — Sets the socket to timeout after + * failing to establish a connection with the server after + * `connectTimeout` milliseconds. This timeout has no effect once a socket + * connection has been established. + * * **timeout** [Integer] — Sets the socket to timeout after timeout + * milliseconds of inactivity on the socket. Defaults to two minutes + * (120000) + * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous + * HTTP requests. Used in the browser environment only. Set to false to + * send requests synchronously. Defaults to true (async on). + * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" + * property of an XMLHttpRequest object. Used in the browser environment + * only. Defaults to false. + * @!attribute logger + * @return [#write,#log] an object that responds to .write() (like a stream) + * or .log() (like the console object) in order to log information about + * requests * - * @!attribute params - * @return [map] the map of params passed to - * {AWS.STS.assumeRoleWithSAML}. To update the token, set the - * `params.SAMLAssertion` property. - */ -AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, { - /** - * Creates a new credentials object. - * @param (see AWS.STS.assumeRoleWithSAML) - * @example Creating a new credentials object - * AWS.config.credentials = new AWS.SAMLCredentials({ - * RoleArn: 'arn:aws:iam::1234567890:role/SAMLRole', - * PrincipalArn: 'arn:aws:iam::1234567890:role/SAMLPrincipal', - * SAMLAssertion: 'base64-token', // base64-encoded token from IdP - * }); - * @see AWS.STS.assumeRoleWithSAML - */ - constructor: function SAMLCredentials(params) { - AWS.Credentials.call(this); - this.expired = true; - this.params = params; - }, - - /** - * Refreshes credentials using {AWS.STS.assumeRoleWithSAML} - * - * @callback callback function(err) - * Called when the STS service responds (or fails). When - * this callback is called with no error, it means that the credentials - * information has been loaded into the object (as the `accessKeyId`, - * `secretAccessKey`, and `sessionToken` properties). - * @param err [Error] if an error occurred, this value will be filled - * @see get - */ - refresh: function refresh(callback) { - this.coalesceRefresh(callback || AWS.util.fn.callback); - }, - - /** - * @api private - */ - load: function load(callback) { - var self = this; - self.createClients(); - self.service.assumeRoleWithSAML(function (err, data) { - if (!err) { - self.service.credentialsFrom(data, self); - } - callback(err); - }); - }, - - /** - * @api private - */ - createClients: function() { - this.service = this.service || new STS({params: this.params}); - } - -}); - -},{"../../clients/sts":8,"../core":18}],24:[function(require,module,exports){ -var AWS = require('../core'); -var STS = require('../../clients/sts'); - -/** - * Represents temporary credentials retrieved from {AWS.STS}. Without any - * extra parameters, credentials will be fetched from the - * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the - * {AWS.STS.assumeRole} operation will be used to fetch credentials for the - * role instead. + * @!attribute systemClockOffset + * @return [Number] an offset value in milliseconds to apply to all signing + * times. Use this to compensate for clock skew when your system may be + * out of sync with the service time. Note that this configuration option + * can only be applied to the global `AWS.config` object and cannot be + * overridden in service-specific configuration. Defaults to 0 milliseconds. * - * @note AWS.TemporaryCredentials is deprecated, but remains available for - * backwards compatibility. {AWS.ChainableTemporaryCredentials} is the - * preferred class for temporary credentials. + * @!attribute signatureVersion + * @return [String] the signature version to sign requests with (overriding + * the API configuration). Possible values are: 'v2', 'v3', 'v4'. * - * To setup temporary credentials, configure a set of master credentials - * using the standard credentials providers (environment, EC2 instance metadata, - * or from the filesystem), then set the global credentials to a new - * temporary credentials object: + * @!attribute signatureCache + * @return [Boolean] whether the signature to sign requests with (overriding + * the API configuration) is cached. Only applies to the signature version 'v4'. + * Defaults to `true`. * - * ```javascript - * // Note that environment credentials are loaded by default, - * // the following line is shown for clarity: - * AWS.config.credentials = new AWS.EnvironmentCredentials('AWS'); + * @!attribute endpointDiscoveryEnabled + * @return [Boolean] whether to enable endpoint discovery for operations that + * allow optionally using an endpoint returned by the service. + * Defaults to 'false' * - * // Now set temporary credentials seeded from the master credentials - * AWS.config.credentials = new AWS.TemporaryCredentials(); + * @!attribute endpointCacheSize + * @return [Number] the size of the global cache storing endpoints from endpoint + * discovery operations. Once endpoint cache is created, updating this setting + * cannot change existing cache size. + * Defaults to 1000 * - * // subsequent requests will now use temporary credentials from AWS STS. - * new AWS.S3().listBucket(function(err, data) { ... }); - * ``` + * @!attribute hostPrefixEnabled + * @return [Boolean] whether to marshal request parameters to the prefix of + * hostname. Defaults to `true`. * - * @!attribute masterCredentials - * @return [AWS.Credentials] the master (non-temporary) credentials used to - * get and refresh temporary credentials from AWS STS. - * @note (see constructor) - */ -AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, { - /** - * Creates a new temporary credentials object. + * @!attribute stsRegionalEndpoints + * @return ['legacy'|'regional'] whether to send sts request to global endpoints or + * regional endpoints. + * Defaults to 'legacy' + */AWS.Config=AWS.util.inherit({/** + * @!endgroup + */ /** + * Creates a new configuration object. This is the object that passes + * option data along to service requests, including credentials, security, + * region information, and some service specific settings. * - * @note In order to create temporary credentials, you first need to have - * "master" credentials configured in {AWS.Config.credentials}. These - * master credentials are necessary to retrieve the temporary credentials, - * as well as refresh the credentials when they expire. - * @param params [map] a map of options that are passed to the - * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. - * If a `RoleArn` parameter is passed in, credentials will be based on the - * IAM role. - * @param masterCredentials [AWS.Credentials] the master (non-temporary) credentials - * used to get and refresh temporary credentials from AWS STS. - * @example Creating a new credentials object for generic temporary credentials - * AWS.config.credentials = new AWS.TemporaryCredentials(); - * @example Creating a new credentials object for an IAM role - * AWS.config.credentials = new AWS.TemporaryCredentials({ - * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials', + * @example Creating a new configuration object with credentials and region + * var config = new AWS.Config({ + * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2' * }); - * @see AWS.STS.assumeRole - * @see AWS.STS.getSessionToken - */ - constructor: function TemporaryCredentials(params, masterCredentials) { - AWS.Credentials.call(this); - this.loadMasterCredentials(masterCredentials); - this.expired = true; - - this.params = params || {}; - if (this.params.RoleArn) { - this.params.RoleSessionName = - this.params.RoleSessionName || 'temporary-credentials'; - } - }, - - /** - * Refreshes credentials using {AWS.STS.assumeRole} or - * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed - * to the credentials {constructor}. + * @option options accessKeyId [String] your AWS access key ID. + * @option options secretAccessKey [String] your AWS secret access key. + * @option options sessionToken [AWS.Credentials] the optional AWS + * session token to sign requests with. + * @option options credentials [AWS.Credentials] the AWS credentials + * to sign requests with. You can either specify this object, or + * specify the accessKeyId and secretAccessKey options directly. + * @option options credentialProvider [AWS.CredentialProviderChain] the + * provider chain used to resolve credentials if no static `credentials` + * property is set. + * @option options region [String] the region to send service requests to. + * See {region} for more information. + * @option options maxRetries [Integer] the maximum amount of retries to + * attempt with a request. See {maxRetries} for more information. + * @option options maxRedirects [Integer] the maximum amount of redirects to + * follow with a request. See {maxRedirects} for more information. + * @option options sslEnabled [Boolean] whether to enable SSL for + * requests. + * @option options paramValidation [Boolean|map] whether input parameters + * should be validated against the operation description before sending + * the request. Defaults to true. Pass a map to enable any of the + * following specific validation features: + * + * * **min** [Boolean] — Validates that a value meets the min + * constraint. This is enabled by default when paramValidation is set + * to `true`. + * * **max** [Boolean] — Validates that a value meets the max + * constraint. + * * **pattern** [Boolean] — Validates that a string value matches a + * regular expression. + * * **enum** [Boolean] — Validates that a string value matches one + * of the allowable enum values. + * @option options computeChecksums [Boolean] whether to compute checksums + * for payload bodies when the service accepts it (currently supported + * in S3 only) + * @option options convertResponseTypes [Boolean] whether types are converted + * when parsing response data. Currently only supported for JSON based + * services. Turning this off may improve performance on large response + * payloads. Defaults to `true`. + * @option options correctClockSkew [Boolean] whether to apply a clock skew + * correction and retry requests that fail because of an skewed client + * clock. Defaults to `false`. + * @option options s3ForcePathStyle [Boolean] whether to force path + * style URLs for S3 objects. + * @option options s3BucketEndpoint [Boolean] whether the provided endpoint + * addresses an individual bucket (false if it addresses the root API + * endpoint). Note that setting this configuration option requires an + * `endpoint` to be provided explicitly to the service constructor. + * @option options s3DisableBodySigning [Boolean] whether S3 body signing + * should be disabled when using signature version `v4`. Body signing + * can only be disabled when using https. Defaults to `true`. + * + * @option options retryDelayOptions [map] A set of options to configure + * the retry delay on retryable errors. Currently supported options are: + * + * * **base** [Integer] — The base number of milliseconds to use in the + * exponential backoff for operation retries. Defaults to 100 ms for all + * services except DynamoDB, where it defaults to 50ms. + * * **customBackoff ** [function] — A custom function that accepts a retry count + * and returns the amount of time to delay in milliseconds. The `base` option will be + * ignored if this option is supplied. + * @option options httpOptions [map] A set of options to pass to the low-level + * HTTP request. Currently supported options are: + * + * * **proxy** [String] — the URL to proxy requests through + * * **agent** [http.Agent, https.Agent] — the Agent object to perform + * HTTP requests with. Used for connection pooling. Defaults to the global + * agent (`http.globalAgent`) for non-SSL connections. Note that for + * SSL connections, a special Agent object is used in order to enable + * peer certificate verification. This feature is only available in the + * Node.js environment. + * * **connectTimeout** [Integer] — Sets the socket to timeout after + * failing to establish a connection with the server after + * `connectTimeout` milliseconds. This timeout has no effect once a socket + * connection has been established. + * * **timeout** [Integer] — Sets the socket to timeout after timeout + * milliseconds of inactivity on the socket. Defaults to two minutes + * (120000). + * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous + * HTTP requests. Used in the browser environment only. Set to false to + * send requests synchronously. Defaults to true (async on). + * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" + * property of an XMLHttpRequest object. Used in the browser environment + * only. Defaults to false. + * @option options apiVersion [String, Date] a String in YYYY-MM-DD format + * (or a date) that represents the latest possible API version that can be + * used in all services (unless overridden by `apiVersions`). Specify + * 'latest' to use the latest possible version. + * @option options apiVersions [map] a map of service + * identifiers (the lowercase service class name) with the API version to + * use when instantiating a service. Specify 'latest' for each individual + * that can use the latest available version. + * @option options logger [#write,#log] an object that responds to .write() + * (like a stream) or .log() (like the console object) in order to log + * information about requests + * @option options systemClockOffset [Number] an offset value in milliseconds + * to apply to all signing times. Use this to compensate for clock skew + * when your system may be out of sync with the service time. Note that + * this configuration option can only be applied to the global `AWS.config` + * object and cannot be overridden in service-specific configuration. + * Defaults to 0 milliseconds. + * @option options signatureVersion [String] the signature version to sign + * requests with (overriding the API configuration). Possible values are: + * 'v2', 'v3', 'v4'. + * @option options signatureCache [Boolean] whether the signature to sign + * requests with (overriding the API configuration) is cached. Only applies + * to the signature version 'v4'. Defaults to `true`. + * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32 + * checksum of HTTP response bodies returned by DynamoDB. Default: `true`. + * @option options useAccelerateEndpoint [Boolean] Whether to use the + * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`. + * @option options clientSideMonitoring [Boolean] whether to collect and + * publish this client's performance metrics of all its API requests. + * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint + * discovery for operations that allow optionally using an endpoint returned by + * the service. + * Defaults to 'false' + * @option options endpointCacheSize [Number] the size of the global cache storing + * endpoints from endpoint discovery operations. Once endpoint cache is created, + * updating this setting cannot change existing cache size. + * Defaults to 1000 + * @option options hostPrefixEnabled [Boolean] whether to marshal request + * parameters to the prefix of hostname. + * Defaults to `true`. + * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request + * to global endpoints or regional endpoints. + * Defaults to 'legacy'. + */constructor:function Config(options){if(options===undefined)options={};options=this.extractCredentials(options);AWS.util.each.call(this,this.keys,function(key,value){this.set(key,options[key],value);});},/** + * @!group Managing Credentials + */ /** + * Loads credentials from the configuration object. This is used internally + * by the SDK to ensure that refreshable {Credentials} objects are properly + * refreshed and loaded when sending a request. If you want to ensure that + * your credentials are loaded prior to a request, you can use this method + * directly to provide accurate credential data stored in the object. * + * @note If you configure the SDK with static or environment credentials, + * the credential data should already be present in {credentials} attribute. + * This method is primarily necessary to load credentials from asynchronous + * sources, or sources that can refresh credentials periodically. + * @example Getting your access key + * AWS.config.getCredentials(function(err) { + * if (err) console.log(err.stack); // credentials not loaded + * else console.log("Access Key:", AWS.config.credentials.accessKeyId); + * }) * @callback callback function(err) - * Called when the STS service responds (or fails). When - * this callback is called with no error, it means that the credentials - * information has been loaded into the object (as the `accessKeyId`, - * `secretAccessKey`, and `sessionToken` properties). - * @param err [Error] if an error occurred, this value will be filled - * @see get - */ - refresh: function refresh (callback) { - this.coalesceRefresh(callback || AWS.util.fn.callback); - }, - - /** + * Called when the {credentials} have been properly set on the configuration + * object. + * + * @param err [Error] if this is set, credentials were not successfully + * loaded and this error provides information why. + * @see credentials + * @see Credentials + */getCredentials:function getCredentials(callback){var self=this;function finish(err){callback(err,err?null:self.credentials);}function credError(msg,err){return new AWS.util.error(err||new Error(),{code:'CredentialsError',message:msg,name:'CredentialsError'});}function getAsyncCredentials(){self.credentials.get(function(err){if(err){var msg='Could not load credentials from '+self.credentials.constructor.name;err=credError(msg,err);}finish(err);});}function getStaticCredentials(){var err=null;if(!self.credentials.accessKeyId||!self.credentials.secretAccessKey){err=credError('Missing credentials');}finish(err);}if(self.credentials){if(typeof self.credentials.get==='function'){getAsyncCredentials();}else{// static credentials +getStaticCredentials();}}else if(self.credentialProvider){self.credentialProvider.resolve(function(err,creds){if(err){err=credError('Could not load credentials from any providers',err);}self.credentials=creds;finish(err);});}else{finish(credError('No credentials to load'));}},/** + * @!group Loading and Setting Configuration Options + */ /** + * @overload update(options, allowUnknownKeys = false) + * Updates the current configuration object with new options. + * + * @example Update maxRetries property of a configuration object + * config.update({maxRetries: 10}); + * @param [Object] options a map of option keys and values. + * @param [Boolean] allowUnknownKeys whether unknown keys can be set on + * the configuration object. Defaults to `false`. + * @see constructor + */update:function update(options,allowUnknownKeys){allowUnknownKeys=allowUnknownKeys||false;options=this.extractCredentials(options);AWS.util.each.call(this,options,function(key,value){if(allowUnknownKeys||Object.prototype.hasOwnProperty.call(this.keys,key)||AWS.Service.hasService(key)){this.set(key,value);}});},/** + * Loads configuration data from a JSON file into this config object. + * @note Loading configuration will reset all existing configuration + * on the object. + * @!macro nobrowser + * @param path [String] the path relative to your process's current + * working directory to load configuration from. + * @return [AWS.Config] the same configuration object + */loadFromPath:function loadFromPath(path){this.clear();var options=JSON.parse(AWS.util.readFileSync(path));var fileSystemCreds=new AWS.FileSystemCredentials(path);var chain=new AWS.CredentialProviderChain();chain.providers.unshift(fileSystemCreds);chain.resolve(function(err,creds){if(err)throw err;else options.credentials=creds;});this.constructor(options);return this;},/** + * Clears configuration data on this object + * * @api private - */ - load: function load (callback) { - var self = this; - self.createClients(); - self.masterCredentials.get(function () { - self.service.config.credentials = self.masterCredentials; - var operation = self.params.RoleArn ? - self.service.assumeRole : self.service.getSessionToken; - operation.call(self.service, function (err, data) { - if (!err) { - self.service.credentialsFrom(data, self); - } - callback(err); - }); - }); - }, - - /** + */clear:function clear(){/*jshint forin:false */AWS.util.each.call(this,this.keys,function(key){delete this[key];});// reset credential provider +this.set('credentials',undefined);this.set('credentialProvider',undefined);},/** + * Sets a property on the configuration object, allowing for a + * default value * @api private - */ - loadMasterCredentials: function loadMasterCredentials (masterCredentials) { - this.masterCredentials = masterCredentials || AWS.config.credentials; - while (this.masterCredentials.masterCredentials) { - this.masterCredentials = this.masterCredentials.masterCredentials; - } - - if (typeof this.masterCredentials.get !== 'function') { - this.masterCredentials = new AWS.Credentials(this.masterCredentials); - } - }, - - /** + */set:function set(property,value,defaultValue){if(value===undefined){if(defaultValue===undefined){defaultValue=this.keys[property];}if(typeof defaultValue==='function'){this[property]=defaultValue.call(this);}else{this[property]=defaultValue;}}else if(property==='httpOptions'&&this[property]){// deep merge httpOptions +this[property]=AWS.util.merge(this[property],value);}else{this[property]=value;}},/** + * All of the keys with their default values. + * + * @constant * @api private - */ - createClients: function () { - this.service = this.service || new STS({params: this.params}); - } - -}); - -},{"../../clients/sts":8,"../core":18}],25:[function(require,module,exports){ -var AWS = require('../core'); -var STS = require('../../clients/sts'); - + */keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:undefined,httpOptions:{timeout:120000},maxRetries:undefined,maxRedirects:10,paramValidation:true,sslEnabled:true,s3ForcePathStyle:false,s3BucketEndpoint:false,s3DisableBodySigning:true,computeChecksums:true,convertResponseTypes:true,correctClockSkew:false,customUserAgent:null,dynamoDbCrc32:true,systemClockOffset:0,signatureVersion:null,signatureCache:true,retryDelayOptions:{},useAccelerateEndpoint:false,clientSideMonitoring:false,endpointDiscoveryEnabled:false,endpointCacheSize:1000,hostPrefixEnabled:true,stsRegionalEndpoints:null},/** + * Extracts accessKeyId, secretAccessKey and sessionToken + * from a configuration hash. + * + * @api private + */extractCredentials:function extractCredentials(options){if(options.accessKeyId&&options.secretAccessKey){options=AWS.util.copy(options);options.credentials=new AWS.Credentials(options);}return options;},/** + * Sets the promise dependency the SDK will use wherever Promises are returned. + * Passing `null` will force the SDK to use native Promises if they are available. + * If native Promises are not available, passing `null` will have no effect. + * @param [Constructor] dep A reference to a Promise constructor + */setPromisesDependency:function setPromisesDependency(dep){PromisesDependency=dep;// if null was passed in, we should try to use native promises +if(dep===null&&typeof Promise==='function'){PromisesDependency=Promise;}var constructors=[AWS.Request,AWS.Credentials,AWS.CredentialProviderChain];if(AWS.S3){constructors.push(AWS.S3);if(AWS.S3.ManagedUpload){constructors.push(AWS.S3.ManagedUpload);}}AWS.util.addPromises(constructors,PromisesDependency);},/** + * Gets the promise dependency set by `AWS.config.setPromisesDependency`. + */getPromisesDependency:function getPromisesDependency(){return PromisesDependency;}});/** + * @return [AWS.Config] The global configuration object singleton instance + * @readonly + * @see AWS.Config + */AWS.config=new AWS.Config();},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(require,module,exports){/** + * The main AWS namespace + */var AWS={util:require('./util')};/** + * @api private + * @!macro [new] nobrowser + * @note This feature is not supported in the browser environment of the SDK. + */var _hidden={};_hidden.toString();// hack to parse macro /** - * Represents credentials retrieved from STS Web Identity Federation support. + * @api private + */module.exports=AWS;AWS.util.update(AWS,{/** + * @constant + */VERSION:'2.553.0',/** + * @api private + */Signers:{},/** + * @api private + */Protocol:{Json:require('./protocol/json'),Query:require('./protocol/query'),Rest:require('./protocol/rest'),RestJson:require('./protocol/rest_json'),RestXml:require('./protocol/rest_xml')},/** + * @api private + */XML:{Builder:require('./xml/builder'),Parser:null// conditionally set based on environment +},/** + * @api private + */JSON:{Builder:require('./json/builder'),Parser:require('./json/parser')},/** + * @api private + */Model:{Api:require('./model/api'),Operation:require('./model/operation'),Shape:require('./model/shape'),Paginator:require('./model/paginator'),ResourceWaiter:require('./model/resource_waiter')},/** + * @api private + */apiLoader:require('./api_loader'),/** + * @api private + */EndpointCache:require('../vendor/endpoint-cache').EndpointCache});require('./sequential_executor');require('./service');require('./config');require('./http');require('./event_listeners');require('./request');require('./response');require('./resource_waiter');require('./signers/request_signer');require('./param_validator');/** + * @readonly + * @return [AWS.SequentialExecutor] a collection of global event listeners that + * are attached to every sent request. + * @see AWS.Request AWS.Request for a list of events to listen for + * @example Logging the time taken to send a request + * AWS.events.on('send', function startSend(resp) { + * resp.startTime = new Date().getTime(); + * }).on('complete', function calculateTime(resp) { + * var time = (new Date().getTime() - resp.startTime) / 1000; + * console.log('Request took ' + time + ' seconds'); + * }); * - * By default this provider gets credentials using the - * {AWS.STS.assumeRoleWithWebIdentity} service operation. This operation - * requires a `RoleArn` containing the ARN of the IAM trust policy for the - * application for which credentials will be given. In addition, the - * `WebIdentityToken` must be set to the token provided by the identity - * provider. See {constructor} for an example on creating a credentials - * object with proper `RoleArn` and `WebIdentityToken` values. + * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' + */AWS.events=new AWS.SequentialExecutor();//create endpoint cache lazily +AWS.util.memoizedProperty(AWS,'endpointCache',function(){return new AWS.EndpointCache(AWS.config.endpointCacheSize);},true);},{"../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(require,module,exports){var AWS=require('./core');/** + * Represents your AWS security credentials, specifically the + * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}. + * Creating a `Credentials` object allows you to pass around your + * security information to configuration and service objects. * - * ## Refreshing Credentials from Identity Service + * Note that this class typically does not need to be constructed manually, + * as the {AWS.Config} and {AWS.Service} classes both accept simple + * options hashes with the three keys. These structures will be converted + * into Credentials objects automatically. * - * In addition to AWS credentials expiring after a given amount of time, the - * login token from the identity provider will also expire. Once this token - * expires, it will not be usable to refresh AWS credentials, and another - * token will be needed. The SDK does not manage refreshing of the token value, - * but this can be done through a "refresh token" supported by most identity - * providers. Consult the documentation for the identity provider for refreshing - * tokens. Once the refreshed token is acquired, you should make sure to update - * this new token in the credentials object's {params} property. The following - * code will update the WebIdentityToken, assuming you have retrieved an updated - * token from the identity provider: + * ## Expiring and Refreshing Credentials * - * ```javascript - * AWS.config.credentials.params.WebIdentityToken = updatedToken; - * ``` + * Occasionally credentials can expire in the middle of a long-running + * application. In this case, the SDK will automatically attempt to + * refresh the credentials from the storage location if the Credentials + * class implements the {refresh} method. * - * Future calls to `credentials.refresh()` will now use the new token. + * If you are implementing a credential storage location, you + * will want to create a subclass of the `Credentials` class and + * override the {refresh} method. This method allows credentials to be + * retrieved from the backing store, be it a file system, database, or + * some network storage. The method should reset the credential attributes + * on the object. * - * @!attribute params - * @return [map] the map of params passed to - * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the - * `params.WebIdentityToken` property. - * @!attribute data - * @return [map] the raw data response from the call to - * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get - * access to other properties from the response. - */ -AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, { - /** - * Creates a new credentials object. - * @param (see AWS.STS.assumeRoleWithWebIdentity) - * @example Creating a new credentials object - * AWS.config.credentials = new AWS.WebIdentityCredentials({ - * RoleArn: 'arn:aws:iam::1234567890:role/WebIdentity', - * WebIdentityToken: 'ABCDEFGHIJKLMNOP', // token from identity service - * RoleSessionName: 'web' // optional name, defaults to web-identity - * }, { - * // optionally provide configuration to apply to the underlying AWS.STS service client - * // if configuration is not provided, then configuration will be pulled from AWS.config + * @!attribute expired + * @return [Boolean] whether the credentials have been expired and + * require a refresh. Used in conjunction with {expireTime}. + * @!attribute expireTime + * @return [Date] a time when credentials should be considered expired. Used + * in conjunction with {expired}. + * @!attribute accessKeyId + * @return [String] the AWS access key ID + * @!attribute secretAccessKey + * @return [String] the AWS secret access key + * @!attribute sessionToken + * @return [String] an optional AWS session token + */AWS.Credentials=AWS.util.inherit({/** + * A credentials object can be created using positional arguments or an options + * hash. * - * // specify timeout options - * httpOptions: { - * timeout: 100 - * } - * }); - * @see AWS.STS.assumeRoleWithWebIdentity - * @see AWS.Config - */ - constructor: function WebIdentityCredentials(params, clientConfig) { - AWS.Credentials.call(this); - this.expired = true; - this.params = params; - this.params.RoleSessionName = this.params.RoleSessionName || 'web-identity'; - this.data = null; - this._clientConfig = AWS.util.copy(clientConfig || {}); - }, - - /** - * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity} + * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null) + * Creates a Credentials object with a given set of credential information + * as positional arguments. + * @param accessKeyId [String] the AWS access key ID + * @param secretAccessKey [String] the AWS secret access key + * @param sessionToken [String] the optional AWS session token + * @example Create a credentials object with AWS credentials + * var creds = new AWS.Credentials('akid', 'secret', 'session'); + * @overload AWS.Credentials(options) + * Creates a Credentials object with a given set of credential information + * as an options hash. + * @option options accessKeyId [String] the AWS access key ID + * @option options secretAccessKey [String] the AWS secret access key + * @option options sessionToken [String] the optional AWS session token + * @example Create a credentials object with AWS credentials + * var creds = new AWS.Credentials({ + * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' + * }); + */constructor:function Credentials(){// hide secretAccessKey from being displayed with util.inspect +AWS.util.hideProperties(this,['secretAccessKey']);this.expired=false;this.expireTime=null;this.refreshCallbacks=[];if(arguments.length===1&&_typeof(arguments[0])==='object'){var creds=arguments[0].credentials||arguments[0];this.accessKeyId=creds.accessKeyId;this.secretAccessKey=creds.secretAccessKey;this.sessionToken=creds.sessionToken;}else{this.accessKeyId=arguments[0];this.secretAccessKey=arguments[1];this.sessionToken=arguments[2];}},/** + * @return [Integer] the number of seconds before {expireTime} during which + * the credentials will be considered expired. + */expiryWindow:15,/** + * @return [Boolean] whether the credentials object should call {refresh} + * @note Subclasses should override this method to provide custom refresh + * logic. + */needsRefresh:function needsRefresh(){var currentTime=AWS.util.date.getDate().getTime();var adjustedTime=new Date(currentTime+this.expiryWindow*1000);if(this.expireTime&&adjustedTime>this.expireTime){return true;}else{return this.expired||!this.accessKeyId||!this.secretAccessKey;}},/** + * Gets the existing credentials, refreshing them if they are not yet loaded + * or have expired. Users should call this method before using {refresh}, + * as this will not attempt to reload credentials when they are already + * loaded into the object. * * @callback callback function(err) - * Called when the STS service responds (or fails). When - * this callback is called with no error, it means that the credentials - * information has been loaded into the object (as the `accessKeyId`, - * `secretAccessKey`, and `sessionToken` properties). + * When this callback is called with no error, it means either credentials + * do not need to be refreshed or refreshed credentials information has + * been loaded into the object (as the `accessKeyId`, `secretAccessKey`, + * and `sessionToken` properties). + * @param err [Error] if an error occurred, this value will be filled + */get:function get(callback){var self=this;if(this.needsRefresh()){this.refresh(function(err){if(!err)self.expired=false;// reset expired flag +if(callback)callback(err);});}else if(callback){callback();}},/** + * @!method getPromise() + * Returns a 'thenable' promise. + * Gets the existing credentials, refreshing them if they are not yet loaded + * or have expired. Users should call this method before using {refresh}, + * as this will not attempt to reload credentials when they are already + * loaded into the object. + * + * Two callbacks can be provided to the `then` method on the returned promise. + * The first callback will be called if the promise is fulfilled, and the second + * callback will be called if the promise is rejected. + * @callback fulfilledCallback function() + * Called if the promise is fulfilled. When this callback is called, it + * means either credentials do not need to be refreshed or refreshed + * credentials information has been loaded into the object (as the + * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). + * @callback rejectedCallback function(err) + * Called if the promise is rejected. + * @param err [Error] if an error occurred, this value will be filled + * @return [Promise] A promise that represents the state of the `get` call. + * @example Calling the `getPromise` method. + * var promise = credProvider.getPromise(); + * promise.then(function() { ... }, function(err) { ... }); + */ /** + * @!method refreshPromise() + * Returns a 'thenable' promise. + * Refreshes the credentials. Users should call {get} before attempting + * to forcibly refresh credentials. + * + * Two callbacks can be provided to the `then` method on the returned promise. + * The first callback will be called if the promise is fulfilled, and the second + * callback will be called if the promise is rejected. + * @callback fulfilledCallback function() + * Called if the promise is fulfilled. When this callback is called, it + * means refreshed credentials information has been loaded into the object + * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). + * @callback rejectedCallback function(err) + * Called if the promise is rejected. + * @param err [Error] if an error occurred, this value will be filled + * @return [Promise] A promise that represents the state of the `refresh` call. + * @example Calling the `refreshPromise` method. + * var promise = credProvider.refreshPromise(); + * promise.then(function() { ... }, function(err) { ... }); + */ /** + * Refreshes the credentials. Users should call {get} before attempting + * to forcibly refresh credentials. + * + * @callback callback function(err) + * When this callback is called with no error, it means refreshed + * credentials information has been loaded into the object (as the + * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled + * @note Subclasses should override this class to reset the + * {accessKeyId}, {secretAccessKey} and optional {sessionToken} + * on the credentials object and then call the callback with + * any error information. * @see get - */ - refresh: function refresh(callback) { - this.coalesceRefresh(callback || AWS.util.fn.callback); - }, - - /** + */refresh:function refresh(callback){this.expired=false;callback();},/** * @api private - */ - load: function load(callback) { - var self = this; - self.createClients(); - self.service.assumeRoleWithWebIdentity(function (err, data) { - self.data = null; - if (!err) { - self.data = data; - self.service.credentialsFrom(data, self); - } - callback(err); - }); - }, - - /** + * @param callback + */coalesceRefresh:function coalesceRefresh(callback,sync){var self=this;if(self.refreshCallbacks.push(callback)===1){self.load(function onLoad(err){AWS.util.arrayEach(self.refreshCallbacks,function(callback){if(sync){callback(err);}else{// callback could throw, so defer to ensure all callbacks are notified +AWS.util.defer(function(){callback(err);});}});self.refreshCallbacks.length=0;});}},/** * @api private - */ - createClients: function() { - if (!this.service) { - var stsConfig = AWS.util.merge({}, this._clientConfig); - stsConfig.params = this.params; - this.service = new STS(stsConfig); - } - } - -}); - -},{"../../clients/sts":8,"../core":18}],26:[function(require,module,exports){ -(function (process){(function (){ -var AWS = require('./core'); -var util = require('./util'); -var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED']; - -/** - * Generate key (except resources and operation part) to index the endpoints in the cache - * If input shape has endpointdiscoveryid trait then use - * accessKey + operation + resources + region + service as cache key - * If input shape doesn't have endpointdiscoveryid trait then use - * accessKey + region + service as cache key - * @return [map] object with keys to index endpoints. + * @param callback + */load:function load(callback){callback();}});/** * @api private - */ -function getCacheKey(request) { - var service = request.service; - var api = service.api || {}; - var operations = api.operations; - var identifiers = {}; - if (service.config.region) { - identifiers.region = service.config.region; - } - if (api.serviceId) { - identifiers.serviceId = api.serviceId; - } - if (service.config.credentials.accessKeyId) { - identifiers.accessKeyId = service.config.credentials.accessKeyId; - } - return identifiers; -} - -/** - * Recursive helper for marshallCustomIdentifiers(). - * Looks for required string input members that have 'endpointdiscoveryid' trait. - * @api private - */ -function marshallCustomIdentifiersHelper(result, params, shape) { - if (!shape || params === undefined || params === null) return; - if (shape.type === 'structure' && shape.required && shape.required.length > 0) { - util.arrayEach(shape.required, function(name) { - var memberShape = shape.members[name]; - if (memberShape.endpointDiscoveryId === true) { - var locationName = memberShape.isLocationName ? memberShape.name : name; - result[locationName] = String(params[name]); - } else { - marshallCustomIdentifiersHelper(result, params[name], memberShape); - } - }); - } -} - -/** - * Get custom identifiers for cache key. - * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait. - * @param [object] request object - * @param [object] input shape of the given operation's api - * @api private - */ -function marshallCustomIdentifiers(request, shape) { - var identifiers = {}; - marshallCustomIdentifiersHelper(identifiers, request.params, shape); - return identifiers; -} - -/** - * Call endpoint discovery operation when it's optional. - * When endpoint is available in cache then use the cached endpoints. If endpoints - * are unavailable then use regional endpoints and call endpoint discovery operation - * asynchronously. This is turned off by default. - * @param [object] request object - * @api private - */ -function optionalDiscoverEndpoint(request) { - var service = request.service; - var api = service.api; - var operationModel = api.operations ? api.operations[request.operation] : undefined; - var inputShape = operationModel ? operationModel.input : undefined; - - var identifiers = marshallCustomIdentifiers(request, inputShape); - var cacheKey = getCacheKey(request); - if (Object.keys(identifiers).length > 0) { - cacheKey = util.update(cacheKey, identifiers); - if (operationModel) cacheKey.operation = operationModel.name; - } - var endpoints = AWS.endpointCache.get(cacheKey); - if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') { - //endpoint operation is being made but response not yet received - //or endpoint operation just failed in 1 minute - return; - } else if (endpoints && endpoints.length > 0) { - //found endpoint record from cache - request.httpRequest.updateEndpoint(endpoints[0].Address); - } else { - //endpoint record not in cache or outdated. make discovery operation - var endpointRequest = service.makeRequest(api.endpointOperation, { - Operation: operationModel.name, - Identifiers: identifiers, - }); - addApiVersionHeader(endpointRequest); - endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); - endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK); - //put in a placeholder for endpoints already requested, prevent - //too much in-flight calls - AWS.endpointCache.put(cacheKey, [{ - Address: '', - CachePeriodInMinutes: 1 - }]); - endpointRequest.send(function(err, data) { - if (data && data.Endpoints) { - AWS.endpointCache.put(cacheKey, data.Endpoints); - } else if (err) { - AWS.endpointCache.put(cacheKey, [{ - Address: '', - CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute - }]); - } - }); - } -} - -var requestQueue = {}; - -/** - * Call endpoint discovery operation when it's required. - * When endpoint is available in cache then use cached ones. If endpoints are - * unavailable then SDK should call endpoint operation then use returned new - * endpoint for the api call. SDK will automatically attempt to do endpoint - * discovery. This is turned off by default - * @param [object] request object - * @api private - */ -function requiredDiscoverEndpoint(request, done) { - var service = request.service; - var api = service.api; - var operationModel = api.operations ? api.operations[request.operation] : undefined; - var inputShape = operationModel ? operationModel.input : undefined; - - var identifiers = marshallCustomIdentifiers(request, inputShape); - var cacheKey = getCacheKey(request); - if (Object.keys(identifiers).length > 0) { - cacheKey = util.update(cacheKey, identifiers); - if (operationModel) cacheKey.operation = operationModel.name; - } - var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey); - var endpoints = AWS.endpointCache.get(cacheKeyStr); //endpoint cache also accepts string keys - if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') { - //endpoint operation is being made but response not yet received - //push request object to a pending queue - if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = []; - requestQueue[cacheKeyStr].push({request: request, callback: done}); - return; - } else if (endpoints && endpoints.length > 0) { - request.httpRequest.updateEndpoint(endpoints[0].Address); - done(); - } else { - var endpointRequest = service.makeRequest(api.endpointOperation, { - Operation: operationModel.name, - Identifiers: identifiers, - }); - endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); - addApiVersionHeader(endpointRequest); - - //put in a placeholder for endpoints already requested, prevent - //too much in-flight calls - AWS.endpointCache.put(cacheKeyStr, [{ - Address: '', - CachePeriodInMinutes: 60 //long-live cache - }]); - endpointRequest.send(function(err, data) { - if (err) { - var errorParams = { - code: 'EndpointDiscoveryException', - message: 'Request cannot be fulfilled without specifying an endpoint', - retryable: false - }; - request.response.error = util.error(err, errorParams); - AWS.endpointCache.remove(cacheKey); - - //fail all the pending requests in batch - if (requestQueue[cacheKeyStr]) { - var pendingRequests = requestQueue[cacheKeyStr]; - util.arrayEach(pendingRequests, function(requestContext) { - requestContext.request.response.error = util.error(err, errorParams); - requestContext.callback(); - }); - delete requestQueue[cacheKeyStr]; - } - } else if (data) { - AWS.endpointCache.put(cacheKeyStr, data.Endpoints); - request.httpRequest.updateEndpoint(data.Endpoints[0].Address); - - //update the endpoint for all the pending requests in batch - if (requestQueue[cacheKeyStr]) { - var pendingRequests = requestQueue[cacheKeyStr]; - util.arrayEach(pendingRequests, function(requestContext) { - requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address); - requestContext.callback(); - }); - delete requestQueue[cacheKeyStr]; - } - } - done(); - }); - } -} - -/** - * add api version header to endpoint operation - * @api private - */ -function addApiVersionHeader(endpointRequest) { - var api = endpointRequest.service.api; - var apiVersion = api.apiVersion; - if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) { - endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion; - } -} - -/** - * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid - * endpoint from cache. - * @api private - */ -function invalidateCachedEndpoints(response) { - var error = response.error; - var httpResponse = response.httpResponse; - if (error && - (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421) - ) { - var request = response.request; - var operations = request.service.api.operations || {}; - var inputShape = operations[request.operation] ? operations[request.operation].input : undefined; - var identifiers = marshallCustomIdentifiers(request, inputShape); - var cacheKey = getCacheKey(request); - if (Object.keys(identifiers).length > 0) { - cacheKey = util.update(cacheKey, identifiers); - if (operations[request.operation]) cacheKey.operation = operations[request.operation].name; - } - AWS.endpointCache.remove(cacheKey); - } -} - -/** - * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime. - * @param [object] client Service client object. - * @api private - */ -function hasCustomEndpoint(client) { - //if set endpoint is set for specific client, enable endpoint discovery will raise an error. - if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) { - throw util.error(new Error(), { - code: 'ConfigurationException', - message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.' - }); - }; - var svcConfig = AWS.config[client.serviceIdentifier] || {}; - return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint)); -} - -/** - * @api private - */ -function isFalsy(value) { - return ['false', '0'].indexOf(value) >= 0; -} - -/** - * If endpoint discovery should perform for this request when endpoint discovery is optional. - * SDK performs config resolution in order like below: - * 1. If turned on client configuration(default to off) then turn on endpoint discovery. - * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery. - * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then - * turn on endpoint discovery. - * @param [object] request request object. - * @api private - */ -function isEndpointDiscoveryApplicable(request) { - var service = request.service || {}; - if (service.config.endpointDiscoveryEnabled === true) return true; - - //shared ini file is only available in Node - //not to check env in browser - if (util.isBrowser()) return false; - - for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) { - var env = endpointDiscoveryEnabledEnvs[i]; - if (Object.prototype.hasOwnProperty.call(process.env, env)) { - if (process.env[env] === '' || process.env[env] === undefined) { - throw util.error(new Error(), { - code: 'ConfigurationException', - message: 'environmental variable ' + env + ' cannot be set to nothing' - }); - } - if (!isFalsy(process.env[env])) return true; - } - } - - var configFile = {}; - try { - configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({ - isConfig: true, - filename: process.env[AWS.util.sharedConfigFileEnv] - }) : {}; - } catch (e) {} - var sharedFileConfig = configFile[ - process.env.AWS_PROFILE || AWS.util.defaultProfile - ] || {}; - if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) { - if (sharedFileConfig.endpoint_discovery_enabled === undefined) { - throw util.error(new Error(), { - code: 'ConfigurationException', - message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing' - }); - } - if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true; - } - return false; -} - -/** - * attach endpoint discovery logic to request object - * @param [object] request - * @api private - */ -function discoverEndpoint(request, done) { - var service = request.service || {}; - if (hasCustomEndpoint(service) || request.isPresigned()) return done(); - - if (!isEndpointDiscoveryApplicable(request)) return done(); - - request.httpRequest.appendToUserAgent('endpoint-discovery'); - - var operations = service.api.operations || {}; - var operationModel = operations[request.operation]; - var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL'; - switch (isEndpointDiscoveryRequired) { - case 'OPTIONAL': - optionalDiscoverEndpoint(request); - request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); - done(); - break; - case 'REQUIRED': - request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); - requiredDiscoverEndpoint(request, done); - break; - case 'NULL': - default: - done(); - break; - } -} - -module.exports = { - discoverEndpoint: discoverEndpoint, - requiredDiscoverEndpoint: requiredDiscoverEndpoint, - optionalDiscoverEndpoint: optionalDiscoverEndpoint, - marshallCustomIdentifiers: marshallCustomIdentifiers, - getCacheKey: getCacheKey, - invalidateCachedEndpoint: invalidateCachedEndpoints, -}; - -}).call(this)}).call(this,require('_process')) -},{"./core":18,"./util":71,"_process":86}],27:[function(require,module,exports){ -var eventMessageChunker = require('../event-stream/event-message-chunker').eventMessageChunker; -var parseEvent = require('./parse-event').parseEvent; - -function createEventStream(body, parser, model) { - var eventMessages = eventMessageChunker(body); - - var events = []; - - for (var i = 0; i < eventMessages.length; i++) { - events.push(parseEvent(parser, eventMessages[i], model)); - } - - return events; -} - -/** - * @api private - */ -module.exports = { - createEventStream: createEventStream -}; - -},{"../event-stream/event-message-chunker":28,"./parse-event":30}],28:[function(require,module,exports){ -/** - * Takes in a buffer of event messages and splits them into individual messages. - * @param {Buffer} buffer - * @api private - */ -function eventMessageChunker(buffer) { - /** @type Buffer[] */ - var messages = []; - var offset = 0; - - while (offset < buffer.length) { - var totalLength = buffer.readInt32BE(offset); - - // create new buffer for individual message (shares memory with original) - var message = buffer.slice(offset, totalLength + offset); - // increment offset to it starts at the next message - offset += totalLength; - - messages.push(message); - } - - return messages; -} - -/** + */AWS.Credentials.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.getPromise=AWS.util.promisifyMethod('get',PromiseDependency);this.prototype.refreshPromise=AWS.util.promisifyMethod('refresh',PromiseDependency);};/** * @api private - */ -module.exports = { - eventMessageChunker: eventMessageChunker -}; - -},{}],29:[function(require,module,exports){ -var util = require('../core').util; -var toBuffer = util.buffer.toBuffer; - -/** - * A lossless representation of a signed, 64-bit integer. Instances of this - * class may be used in arithmetic expressions as if they were numeric - * primitives, but the binary representation will be preserved unchanged as the - * `bytes` property of the object. The bytes should be encoded as big-endian, - * two's complement integers. - * @param {Buffer} bytes + */AWS.Credentials.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.getPromise;delete this.prototype.refreshPromise;};AWS.util.addPromises(AWS.Credentials);},{"./core":18}],20:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** + * Represents temporary credentials retrieved from {AWS.STS}. Without any + * extra parameters, credentials will be fetched from the + * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the + * {AWS.STS.assumeRole} operation will be used to fetch credentials for the + * role instead. * - * @api private - */ -function Int64(bytes) { - if (bytes.length !== 8) { - throw new Error('Int64 buffers must be exactly 8 bytes'); - } - if (!util.Buffer.isBuffer(bytes)) bytes = toBuffer(bytes); - - this.bytes = bytes; -} - -/** - * @param {number} number - * @returns {Int64} + * AWS.ChainableTemporaryCredentials differs from AWS.TemporaryCredentials in + * the way masterCredentials and refreshes are handled. + * AWS.ChainableTemporaryCredentials refreshes expired credentials using the + * masterCredentials passed by the user to support chaining of STS credentials. + * However, AWS.TemporaryCredentials recursively collapses the masterCredentials + * during instantiation, precluding the ability to refresh credentials which + * require intermediate, temporary credentials. * - * @api private - */ -Int64.fromNumber = function(number) { - if (number > 9223372036854775807 || number < -9223372036854775808) { - throw new Error( - number + ' is too large (or, if negative, too small) to represent as an Int64' - ); - } - - var bytes = new Uint8Array(8); - for ( - var i = 7, remaining = Math.abs(Math.round(number)); - i > -1 && remaining > 0; - i--, remaining /= 256 - ) { - bytes[i] = remaining; - } - - if (number < 0) { - negate(bytes); - } - - return new Int64(bytes); -}; - -/** - * @returns {number} + * For example, if the application should use RoleA, which must be assumed from + * RoleB, and the environment provides credentials which can assume RoleB, then + * AWS.ChainableTemporaryCredentials must be used to support refreshing the + * temporary credentials for RoleA: * - * @api private - */ -Int64.prototype.valueOf = function() { - var bytes = this.bytes.slice(0); - var negative = bytes[0] & 128; - if (negative) { - negate(bytes); - } - - return parseInt(bytes.toString('hex'), 16) * (negative ? -1 : 1); -}; - -Int64.prototype.toString = function() { - return String(this.valueOf()); -}; - -/** - * @param {Buffer} bytes + * ```javascript + * var roleACreds = new AWS.ChainableTemporaryCredentials({ + * params: {RoleArn: 'RoleA'}, + * masterCredentials: new AWS.ChainableTemporaryCredentials({ + * params: {RoleArn: 'RoleB'}, + * masterCredentials: new AWS.EnvironmentCredentials('AWS') + * }) + * }); + * ``` * - * @api private - */ -function negate(bytes) { - for (var i = 0; i < 8; i++) { - bytes[i] ^= 0xFF; - } - for (var i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) { - break; - } - } -} - -/** - * @api private - */ -module.exports = { - Int64: Int64 -}; - -},{"../core":18}],30:[function(require,module,exports){ -var parseMessage = require('./parse-message').parseMessage; - -/** + * If AWS.TemporaryCredentials had been used in the previous example, + * `roleACreds` would fail to refresh because `roleACreds` would + * use the environment credentials for the AssumeRole request. * - * @param {*} parser - * @param {Buffer} message - * @param {*} shape - * @api private - */ -function parseEvent(parser, message, shape) { - var parsedMessage = parseMessage(message); - - // check if message is an event or error - var messageType = parsedMessage.headers[':message-type']; - if (messageType) { - if (messageType.value === 'error') { - throw parseError(parsedMessage); - } else if (messageType.value !== 'event') { - // not sure how to parse non-events/non-errors, ignore for now - return; - } - } - - // determine event type - var eventType = parsedMessage.headers[':event-type']; - // check that the event type is modeled - var eventModel = shape.members[eventType.value]; - if (!eventModel) { - return; - } - - var result = {}; - // check if an event payload exists - var eventPayloadMemberName = eventModel.eventPayloadMemberName; - if (eventPayloadMemberName) { - var payloadShape = eventModel.members[eventPayloadMemberName]; - // if the shape is binary, return the byte array - if (payloadShape.type === 'binary') { - result[eventPayloadMemberName] = parsedMessage.body; - } else { - result[eventPayloadMemberName] = parser.parse(parsedMessage.body.toString(), payloadShape); - } - } - - // read event headers - var eventHeaderNames = eventModel.eventHeaderMemberNames; - for (var i = 0; i < eventHeaderNames.length; i++) { - var name = eventHeaderNames[i]; - if (parsedMessage.headers[name]) { - // parse the header! - result[name] = eventModel.members[name].toType(parsedMessage.headers[name].value); - } - } - - var output = {}; - output[eventType.value] = result; - return output; -} - -function parseError(message) { - var errorCode = message.headers[':error-code']; - var errorMessage = message.headers[':error-message']; - var error = new Error(errorMessage.value || errorMessage); - error.code = error.name = errorCode.value || errorCode; - return error; -} - -/** - * @api private - */ -module.exports = { - parseEvent: parseEvent -}; - -},{"./parse-message":31}],31:[function(require,module,exports){ -var Int64 = require('./int64').Int64; - -var splitMessage = require('./split-message').splitMessage; - -var BOOLEAN_TAG = 'boolean'; -var BYTE_TAG = 'byte'; -var SHORT_TAG = 'short'; -var INT_TAG = 'integer'; -var LONG_TAG = 'long'; -var BINARY_TAG = 'binary'; -var STRING_TAG = 'string'; -var TIMESTAMP_TAG = 'timestamp'; -var UUID_TAG = 'uuid'; - -/** - * @api private + * Another difference is that AWS.ChainableTemporaryCredentials creates the STS + * service instance during instantiation while AWS.TemporaryCredentials creates + * the STS service instance during the first refresh. Creating the service + * instance during instantiation effectively captures the master credentials + * from the global config, so that subsequent changes to the global config do + * not affect the master credentials used to refresh the temporary credentials. * - * @param {Buffer} headers - */ -function parseHeaders(headers) { - var out = {}; - var position = 0; - while (position < headers.length) { - var nameLength = headers.readUInt8(position++); - var name = headers.slice(position, position + nameLength).toString(); - position += nameLength; - switch (headers.readUInt8(position++)) { - case 0 /* boolTrue */: - out[name] = { - type: BOOLEAN_TAG, - value: true - }; - break; - case 1 /* boolFalse */: - out[name] = { - type: BOOLEAN_TAG, - value: false - }; - break; - case 2 /* byte */: - out[name] = { - type: BYTE_TAG, - value: headers.readInt8(position++) - }; - break; - case 3 /* short */: - out[name] = { - type: SHORT_TAG, - value: headers.readInt16BE(position) - }; - position += 2; - break; - case 4 /* integer */: - out[name] = { - type: INT_TAG, - value: headers.readInt32BE(position) - }; - position += 4; - break; - case 5 /* long */: - out[name] = { - type: LONG_TAG, - value: new Int64(headers.slice(position, position + 8)) - }; - position += 8; - break; - case 6 /* byteArray */: - var binaryLength = headers.readUInt16BE(position); - position += 2; - out[name] = { - type: BINARY_TAG, - value: headers.slice(position, position + binaryLength) - }; - position += binaryLength; - break; - case 7 /* string */: - var stringLength = headers.readUInt16BE(position); - position += 2; - out[name] = { - type: STRING_TAG, - value: headers.slice( - position, - position + stringLength - ).toString() - }; - position += stringLength; - break; - case 8 /* timestamp */: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date( - new Int64(headers.slice(position, position + 8)) - .valueOf() - ) - }; - position += 8; - break; - case 9 /* uuid */: - var uuidChars = headers.slice(position, position + 16) - .toString('hex'); - position += 16; - out[name] = { - type: UUID_TAG, - value: uuidChars.substr(0, 8) + '-' + - uuidChars.substr(8, 4) + '-' + - uuidChars.substr(12, 4) + '-' + - uuidChars.substr(16, 4) + '-' + - uuidChars.substr(20) - }; - break; - default: - throw new Error('Unrecognized header type tag'); - } - } - return out; -} - -function parseMessage(message) { - var parsed = splitMessage(message); - return { headers: parseHeaders(parsed.headers), body: parsed.body }; -} - -/** - * @api private - */ -module.exports = { - parseMessage: parseMessage -}; - -},{"./int64":29,"./split-message":32}],32:[function(require,module,exports){ -var util = require('../core').util; -var toBuffer = util.buffer.toBuffer; - -// All prelude components are unsigned, 32-bit integers -var PRELUDE_MEMBER_LENGTH = 4; -// The prelude consists of two components -var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; -// Checksums are always CRC32 hashes. -var CHECKSUM_LENGTH = 4; -// Messages must include a full prelude, a prelude checksum, and a message checksum -var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; - -/** - * @api private - * - * @param {Buffer} message - */ -function splitMessage(message) { - if (!util.Buffer.isBuffer(message)) message = toBuffer(message); - - if (message.length < MINIMUM_MESSAGE_LENGTH) { - throw new Error('Provided message too short to accommodate event stream message overhead'); - } - - if (message.length !== message.readUInt32BE(0)) { - throw new Error('Reported message length does not match received message length'); - } - - var expectedPreludeChecksum = message.readUInt32BE(PRELUDE_LENGTH); - - if ( - expectedPreludeChecksum !== util.crypto.crc32( - message.slice(0, PRELUDE_LENGTH) - ) - ) { - throw new Error( - 'The prelude checksum specified in the message (' + - expectedPreludeChecksum + - ') does not match the calculated CRC32 checksum.' - ); - } - - var expectedMessageChecksum = message.readUInt32BE(message.length - CHECKSUM_LENGTH); - - if ( - expectedMessageChecksum !== util.crypto.crc32( - message.slice(0, message.length - CHECKSUM_LENGTH) - ) - ) { - throw new Error( - 'The message checksum did not match the expected value of ' + - expectedMessageChecksum - ); - } - - var headersStart = PRELUDE_LENGTH + CHECKSUM_LENGTH; - var headersEnd = headersStart + message.readUInt32BE(PRELUDE_MEMBER_LENGTH); - - return { - headers: message.slice(headersStart, headersEnd), - body: message.slice(headersEnd, message.length - CHECKSUM_LENGTH), - }; -} - -/** - * @api private - */ -module.exports = { - splitMessage: splitMessage -}; - -},{"../core":18}],33:[function(require,module,exports){ -var AWS = require('./core'); -var SequentialExecutor = require('./sequential_executor'); -var DISCOVER_ENDPOINT = require('./discover_endpoint').discoverEndpoint; -/** - * The namespace used to register global event listeners for request building - * and sending. - */ -AWS.EventListeners = { - /** - * @!attribute VALIDATE_CREDENTIALS - * A request listener that validates whether the request is being - * sent with credentials. - * Handles the {AWS.Request~validate 'validate' Request event} - * @example Sending a request without validating credentials - * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS; - * request.removeListener('validate', listener); - * @readonly - * @return [Function] - * @!attribute VALIDATE_REGION - * A request listener that validates whether the region is set - * for a request. - * Handles the {AWS.Request~validate 'validate' Request event} - * @example Sending a request without validating region configuration - * var listener = AWS.EventListeners.Core.VALIDATE_REGION; - * request.removeListener('validate', listener); - * @readonly - * @return [Function] - * @!attribute VALIDATE_PARAMETERS - * A request listener that validates input parameters in a request. - * Handles the {AWS.Request~validate 'validate' Request event} - * @example Sending a request without validating parameters - * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS; - * request.removeListener('validate', listener); - * @example Disable parameter validation globally - * AWS.EventListeners.Core.removeListener('validate', - * AWS.EventListeners.Core.VALIDATE_REGION); - * @readonly - * @return [Function] - * @!attribute SEND - * A request listener that initiates the HTTP connection for a - * request being sent. Handles the {AWS.Request~send 'send' Request event} - * @example Replacing the HTTP handler - * var listener = AWS.EventListeners.Core.SEND; - * request.removeListener('send', listener); - * request.on('send', function(response) { - * customHandler.send(response); - * }); - * @return [Function] - * @readonly - * @!attribute HTTP_DATA - * A request listener that reads data from the HTTP connection in order - * to build the response data. - * Handles the {AWS.Request~httpData 'httpData' Request event}. - * Remove this handler if you are overriding the 'httpData' event and - * do not want extra data processing and buffering overhead. - * @example Disabling default data processing - * var listener = AWS.EventListeners.Core.HTTP_DATA; - * request.removeListener('httpData', listener); - * @return [Function] - * @readonly - */ - Core: {} /* doc hack */ -}; - -/** - * @api private - */ -function getOperationAuthtype(req) { - if (!req.service.api.operations) { - return ''; - } - var operation = req.service.api.operations[req.operation]; - return operation ? operation.authtype : ''; -} - -AWS.EventListeners = { - Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) { - addAsync('VALIDATE_CREDENTIALS', 'validate', - function VALIDATE_CREDENTIALS(req, done) { - if (!req.service.api.signatureVersion && !req.service.config.signatureVersion) return done(); // none - req.service.config.getCredentials(function(err) { - if (err) { - req.response.error = AWS.util.error(err, - {code: 'CredentialsError', message: 'Missing credentials in config'}); - } - done(); - }); - }); - - add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) { - if (!req.service.config.region && !req.service.isGlobalEndpoint) { - req.response.error = AWS.util.error(new Error(), - {code: 'ConfigError', message: 'Missing region in config'}); - } - }); - - add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) { - if (!req.service.api.operations) { - return; - } - var operation = req.service.api.operations[req.operation]; - if (!operation) { - return; - } - var idempotentMembers = operation.idempotentMembers; - if (!idempotentMembers.length) { - return; - } - // creates a copy of params so user's param object isn't mutated - var params = AWS.util.copy(req.params); - for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) { - if (!params[idempotentMembers[i]]) { - // add the member - params[idempotentMembers[i]] = AWS.util.uuid.v4(); - } - } - req.params = params; - }); - - add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) { - if (!req.service.api.operations) { - return; - } - var rules = req.service.api.operations[req.operation].input; - var validation = req.service.config.paramValidation; - new AWS.ParamValidator(validation).validate(rules, req.params); - }); - - addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) { - req.haltHandlersOnError(); - if (!req.service.api.operations) { - return; - } - var operation = req.service.api.operations[req.operation]; - var authtype = operation ? operation.authtype : ''; - if (!req.service.api.signatureVersion && !authtype && !req.service.config.signatureVersion) return done(); // none - if (req.service.getSignerClass(req) === AWS.Signers.V4) { - var body = req.httpRequest.body || ''; - if (authtype.indexOf('unsigned-body') >= 0) { - req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD'; - return done(); - } - AWS.util.computeSha256(body, function(err, sha) { - if (err) { - done(err); - } - else { - req.httpRequest.headers['X-Amz-Content-Sha256'] = sha; - done(); - } - }); - } else { - done(); - } - }); - - add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) { - var authtype = getOperationAuthtype(req); - var payloadMember = AWS.util.getRequestPayloadShape(req); - if (req.httpRequest.headers['Content-Length'] === undefined) { - try { - var length = AWS.util.string.byteLength(req.httpRequest.body); - req.httpRequest.headers['Content-Length'] = length; - } catch (err) { - if (payloadMember && payloadMember.isStreaming) { - if (payloadMember.requiresLength) { - //streaming payload requires length(s3, glacier) - throw err; - } else if (authtype.indexOf('unsigned-body') >= 0) { - //unbounded streaming payload(lex, mediastore) - req.httpRequest.headers['Transfer-Encoding'] = 'chunked'; - return; - } else { - throw err; - } - } - throw err; - } - } - }); - - add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) { - req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; - }); - - add('RESTART', 'restart', function RESTART() { - var err = this.response.error; - if (!err || !err.retryable) return; - - this.httpRequest = new AWS.HttpRequest( - this.service.endpoint, - this.service.region - ); - - if (this.response.retryCount < this.service.config.maxRetries) { - this.response.retryCount++; - } else { - this.response.error = null; - } - }); - - var addToHead = true; - addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead); - - addAsync('SIGN', 'sign', function SIGN(req, done) { - var service = req.service; - var operations = req.service.api.operations || {}; - var operation = operations[req.operation]; - var authtype = operation ? operation.authtype : ''; - if (!service.api.signatureVersion && !authtype && !service.config.signatureVersion) return done(); // none - - service.config.getCredentials(function (err, credentials) { - if (err) { - req.response.error = err; - return done(); - } - - try { - var date = service.getSkewCorrectedDate(); - var SignerClass = service.getSignerClass(req); - var signer = new SignerClass(req.httpRequest, - service.api.signingName || service.api.endpointPrefix, - { - signatureCache: service.config.signatureCache, - operation: operation, - signatureVersion: service.api.signatureVersion - }); - signer.setServiceClientId(service._clientId); - - // clear old authorization headers - delete req.httpRequest.headers['Authorization']; - delete req.httpRequest.headers['Date']; - delete req.httpRequest.headers['X-Amz-Date']; - - // add new authorization - signer.addAuthorization(credentials, date); - req.signedAt = date; - } catch (e) { - req.response.error = e; - } - done(); - }); - }); - - add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) { - if (this.service.successfulResponse(resp, this)) { - resp.data = {}; - resp.error = null; - } else { - resp.data = null; - resp.error = AWS.util.error(new Error(), - {code: 'UnknownError', message: 'An unknown error occurred.'}); - } - }); - - addAsync('SEND', 'send', function SEND(resp, done) { - resp.httpResponse._abortCallback = done; - resp.error = null; - resp.data = null; - - function callback(httpResp) { - resp.httpResponse.stream = httpResp; - var stream = resp.request.httpRequest.stream; - var service = resp.request.service; - var api = service.api; - var operationName = resp.request.operation; - var operation = api.operations[operationName] || {}; - - httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) { - resp.request.emit( - 'httpHeaders', - [statusCode, headers, resp, statusMessage] - ); - - if (!resp.httpResponse.streaming) { - if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check - // if we detect event streams, we're going to have to - // return the stream immediately - if (operation.hasEventOutput && service.successfulResponse(resp)) { - // skip reading the IncomingStream - resp.request.emit('httpDone'); - done(); - return; - } - - httpResp.on('readable', function onReadable() { - var data = httpResp.read(); - if (data !== null) { - resp.request.emit('httpData', [data, resp]); - } - }); - } else { // legacy streams API - httpResp.on('data', function onData(data) { - resp.request.emit('httpData', [data, resp]); - }); - } - } - }); - - httpResp.on('end', function onEnd() { - if (!stream || !stream.didCallback) { - if (AWS.HttpClient.streamsApiVersion === 2 && (operation.hasEventOutput && service.successfulResponse(resp))) { - // don't concatenate response chunks when streaming event stream data when response is successful - return; - } - resp.request.emit('httpDone'); - done(); - } - }); - } - - function progress(httpResp) { - httpResp.on('sendProgress', function onSendProgress(value) { - resp.request.emit('httpUploadProgress', [value, resp]); - }); - - httpResp.on('receiveProgress', function onReceiveProgress(value) { - resp.request.emit('httpDownloadProgress', [value, resp]); - }); - } - - function error(err) { - if (err.code !== 'RequestAbortedError') { - var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError'; - err = AWS.util.error(err, { - code: errCode, - region: resp.request.httpRequest.region, - hostname: resp.request.httpRequest.endpoint.hostname, - retryable: true - }); - } - resp.error = err; - resp.request.emit('httpError', [resp.error, resp], function() { - done(); - }); - } - - function executeSend() { - var http = AWS.HttpClient.getInstance(); - var httpOptions = resp.request.service.config.httpOptions || {}; - try { - var stream = http.handleRequest(resp.request.httpRequest, httpOptions, - callback, error); - progress(stream); - } catch (err) { - error(err); - } - } - var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000; - if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign - this.emit('sign', [this], function(err) { - if (err) done(err); - else executeSend(); - }); - } else { - executeSend(); - } - }); - - add('HTTP_HEADERS', 'httpHeaders', - function HTTP_HEADERS(statusCode, headers, resp, statusMessage) { - resp.httpResponse.statusCode = statusCode; - resp.httpResponse.statusMessage = statusMessage; - resp.httpResponse.headers = headers; - resp.httpResponse.body = AWS.util.buffer.toBuffer(''); - resp.httpResponse.buffers = []; - resp.httpResponse.numBytes = 0; - var dateHeader = headers.date || headers.Date; - var service = resp.request.service; - if (dateHeader) { - var serverTime = Date.parse(dateHeader); - if (service.config.correctClockSkew - && service.isClockSkewed(serverTime)) { - service.applyClockOffset(serverTime); - } - } - }); - - add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) { - if (chunk) { - if (AWS.util.isNode()) { - resp.httpResponse.numBytes += chunk.length; - - var total = resp.httpResponse.headers['content-length']; - var progress = { loaded: resp.httpResponse.numBytes, total: total }; - resp.request.emit('httpDownloadProgress', [progress, resp]); - } - - resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk)); - } - }); - - add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) { - // convert buffers array into single buffer - if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) { - var body = AWS.util.buffer.concat(resp.httpResponse.buffers); - resp.httpResponse.body = body; - } - delete resp.httpResponse.numBytes; - delete resp.httpResponse.buffers; - }); - - add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) { - if (resp.httpResponse.statusCode) { - resp.error.statusCode = resp.httpResponse.statusCode; - if (resp.error.retryable === undefined) { - resp.error.retryable = this.service.retryableError(resp.error, this); - } - } - }); - - add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) { - if (!resp.error) return; - switch (resp.error.code) { - case 'RequestExpired': // EC2 only - case 'ExpiredTokenException': - case 'ExpiredToken': - resp.error.retryable = true; - resp.request.service.config.credentials.expired = true; - } - }); - - add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) { - var err = resp.error; - if (!err) return; - if (typeof err.code === 'string' && typeof err.message === 'string') { - if (err.code.match(/Signature/) && err.message.match(/expired/)) { - resp.error.retryable = true; - } - } - }); - - add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) { - if (!resp.error) return; - if (this.service.clockSkewError(resp.error) - && this.service.config.correctClockSkew) { - resp.error.retryable = true; - } - }); - - add('REDIRECT', 'retry', function REDIRECT(resp) { - if (resp.error && resp.error.statusCode >= 300 && - resp.error.statusCode < 400 && resp.httpResponse.headers['location']) { - this.httpRequest.endpoint = - new AWS.Endpoint(resp.httpResponse.headers['location']); - this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host; - resp.error.redirect = true; - resp.error.retryable = true; - } - }); - - add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) { - if (resp.error) { - if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { - resp.error.retryDelay = 0; - } else if (resp.retryCount < resp.maxRetries) { - resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0; - } - } - }); - - addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) { - var delay, willRetry = false; - - if (resp.error) { - delay = resp.error.retryDelay || 0; - if (resp.error.retryable && resp.retryCount < resp.maxRetries) { - resp.retryCount++; - willRetry = true; - } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { - resp.redirectCount++; - willRetry = true; - } - } - - if (willRetry) { - resp.error = null; - setTimeout(done, delay); - } else { - done(); - } - }); - }), - - CorePost: new SequentialExecutor().addNamedListeners(function(add) { - add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId); - add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId); - - add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) { - if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') { - var message = 'Inaccessible host: `' + err.hostname + - '\'. This service may not be available in the `' + err.region + - '\' region.'; - this.response.error = AWS.util.error(new Error(message), { - code: 'UnknownEndpoint', - region: err.region, - hostname: err.hostname, - retryable: true, - originalError: err - }); - } - }); - }), - - Logger: new SequentialExecutor().addNamedListeners(function(add) { - add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) { - var req = resp.request; - var logger = req.service.config.logger; - if (!logger) return; - function filterSensitiveLog(inputShape, shape) { - if (!shape) { - return shape; - } - switch (inputShape.type) { - case 'structure': - var struct = {}; - AWS.util.each(shape, function(subShapeName, subShape) { - if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) { - struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape); - } else { - struct[subShapeName] = subShape; - } - }); - return struct; - case 'list': - var list = []; - AWS.util.arrayEach(shape, function(subShape, index) { - list.push(filterSensitiveLog(inputShape.member, subShape)); - }); - return list; - case 'map': - var map = {}; - AWS.util.each(shape, function(key, value) { - map[key] = filterSensitiveLog(inputShape.value, value); - }); - return map; - default: - if (inputShape.isSensitive) { - return '***SensitiveInformation***'; - } else { - return shape; - } - } - } - - function buildMessage() { - var time = resp.request.service.getSkewCorrectedDate().getTime(); - var delta = (time - req.startTime.getTime()) / 1000; - var ansi = logger.isTTY ? true : false; - var status = resp.httpResponse.statusCode; - var censoredParams = req.params; - if ( - req.service.api.operations && - req.service.api.operations[req.operation] && - req.service.api.operations[req.operation].input - ) { - var inputShape = req.service.api.operations[req.operation].input; - censoredParams = filterSensitiveLog(inputShape, req.params); - } - var params = require('util').inspect(censoredParams, true, null); - var message = ''; - if (ansi) message += '\x1B[33m'; - message += '[AWS ' + req.service.serviceIdentifier + ' ' + status; - message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]'; - if (ansi) message += '\x1B[0;1m'; - message += ' ' + AWS.util.string.lowerFirst(req.operation); - message += '(' + params + ')'; - if (ansi) message += '\x1B[0m'; - return message; - } - - var line = buildMessage(); - if (typeof logger.log === 'function') { - logger.log(line); - } else if (typeof logger.write === 'function') { - logger.write(line + '\n'); - } - }); - }), - - Json: new SequentialExecutor().addNamedListeners(function(add) { - var svc = require('./protocol/json'); - add('BUILD', 'build', svc.buildRequest); - add('EXTRACT_DATA', 'extractData', svc.extractData); - add('EXTRACT_ERROR', 'extractError', svc.extractError); - }), - - Rest: new SequentialExecutor().addNamedListeners(function(add) { - var svc = require('./protocol/rest'); - add('BUILD', 'build', svc.buildRequest); - add('EXTRACT_DATA', 'extractData', svc.extractData); - add('EXTRACT_ERROR', 'extractError', svc.extractError); - }), - - RestJson: new SequentialExecutor().addNamedListeners(function(add) { - var svc = require('./protocol/rest_json'); - add('BUILD', 'build', svc.buildRequest); - add('EXTRACT_DATA', 'extractData', svc.extractData); - add('EXTRACT_ERROR', 'extractError', svc.extractError); - }), - - RestXml: new SequentialExecutor().addNamedListeners(function(add) { - var svc = require('./protocol/rest_xml'); - add('BUILD', 'build', svc.buildRequest); - add('EXTRACT_DATA', 'extractData', svc.extractData); - add('EXTRACT_ERROR', 'extractError', svc.extractError); - }), - - Query: new SequentialExecutor().addNamedListeners(function(add) { - var svc = require('./protocol/query'); - add('BUILD', 'build', svc.buildRequest); - add('EXTRACT_DATA', 'extractData', svc.extractData); - add('EXTRACT_ERROR', 'extractError', svc.extractError); - }) -}; - -},{"./core":18,"./discover_endpoint":26,"./protocol/json":46,"./protocol/query":47,"./protocol/rest":48,"./protocol/rest_json":49,"./protocol/rest_xml":50,"./sequential_executor":58,"util":97}],34:[function(require,module,exports){ -var AWS = require('./core'); -var inherit = AWS.util.inherit; - -/** - * The endpoint that a service will talk to, for example, - * `'https://ec2.ap-southeast-1.amazonaws.com'`. If - * you need to override an endpoint for a service, you can - * set the endpoint on a service by passing the endpoint - * object with the `endpoint` option key: + * This allows an instance of AWS.ChainableTemporaryCredentials to be assigned + * to AWS.config.credentials: * * ```javascript - * var ep = new AWS.Endpoint('awsproxy.example.com'); - * var s3 = new AWS.S3({endpoint: ep}); - * s3.service.endpoint.hostname == 'awsproxy.example.com' + * var envCreds = new AWS.EnvironmentCredentials('AWS'); + * AWS.config.credentials = envCreds; + * // masterCredentials will be envCreds + * AWS.config.credentials = new AWS.ChainableTemporaryCredentials({ + * params: {RoleArn: '...'} + * }); * ``` * - * Note that if you do not specify a protocol, the protocol will - * be selected based on your current {AWS.config} configuration. + * Similarly, to use the CredentialProviderChain's default providers as the + * master credentials, simply create a new instance of + * AWS.ChainableTemporaryCredentials: * - * @!attribute protocol - * @return [String] the protocol (http or https) of the endpoint - * URL - * @!attribute hostname - * @return [String] the host portion of the endpoint, e.g., - * example.com - * @!attribute host - * @return [String] the host portion of the endpoint including - * the port, e.g., example.com:80 - * @!attribute port - * @return [Integer] the port of the endpoint - * @!attribute href - * @return [String] the full URL of the endpoint - */ -AWS.Endpoint = inherit({ - - /** - * @overload Endpoint(endpoint) - * Constructs a new endpoint given an endpoint URL. If the - * URL omits a protocol (http or https), the default protocol - * set in the global {AWS.config} will be used. - * @param endpoint [String] the URL to construct an endpoint from - */ - constructor: function Endpoint(endpoint, config) { - AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']); - - if (typeof endpoint === 'undefined' || endpoint === null) { - throw new Error('Invalid endpoint: ' + endpoint); - } else if (typeof endpoint !== 'string') { - return AWS.util.copy(endpoint); - } - - if (!endpoint.match(/^http/)) { - var useSSL = config && config.sslEnabled !== undefined ? - config.sslEnabled : AWS.config.sslEnabled; - endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint; - } - - AWS.util.update(this, AWS.util.urlParse(endpoint)); - - // Ensure the port property is set as an integer - if (this.port) { - this.port = parseInt(this.port, 10); - } else { - this.port = this.protocol === 'https:' ? 443 : 80; - } - } - -}); - -/** - * The low level HTTP request object, encapsulating all HTTP header - * and body data sent by a service request. + * ```javascript + * AWS.config.credentials = new ChainableTemporaryCredentials({ + * params: {RoleArn: '...'} + * }); + * ``` * - * @!attribute method - * @return [String] the HTTP method of the request - * @!attribute path - * @return [String] the path portion of the URI, e.g., - * "/list/?start=5&num=10" - * @!attribute headers - * @return [map] - * a map of header keys and their respective values - * @!attribute body - * @return [String] the request body payload - * @!attribute endpoint - * @return [AWS.Endpoint] the endpoint for the request - * @!attribute region - * @api private - * @return [String] the region, for signing purposes only. - */ -AWS.HttpRequest = inherit({ - - /** - * @api private - */ - constructor: function HttpRequest(endpoint, region) { - endpoint = new AWS.Endpoint(endpoint); - this.method = 'POST'; - this.path = endpoint.path || '/'; - this.headers = {}; - this.body = ''; - this.endpoint = endpoint; - this.region = region; - this._userAgent = ''; - this.setUserAgent(); - }, - - /** - * @api private - */ - setUserAgent: function setUserAgent() { - this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent(); - }, - - getUserAgentHeaderName: function getUserAgentHeaderName() { - var prefix = AWS.util.isBrowser() ? 'X-Amz-' : ''; - return prefix + 'User-Agent'; - }, - - /** - * @api private - */ - appendToUserAgent: function appendToUserAgent(agentPartial) { - if (typeof agentPartial === 'string' && agentPartial) { - this._userAgent += ' ' + agentPartial; - } - this.headers[this.getUserAgentHeaderName()] = this._userAgent; - }, - - /** + * @!attribute service + * @return [AWS.STS] the STS service instance used to + * get and refresh temporary credentials from AWS STS. + * @note (see constructor) + */AWS.ChainableTemporaryCredentials=AWS.util.inherit(AWS.Credentials,{/** + * Creates a new temporary credentials object. + * + * @param options [map] a set of options + * @option options params [map] ({}) a map of options that are passed to the + * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. + * If a `RoleArn` parameter is passed in, credentials will be based on the + * IAM role. If a `SerialNumber` parameter is passed in, {tokenCodeFn} must + * also be passed in or an error will be thrown. + * @option options masterCredentials [AWS.Credentials] the master credentials + * used to get and refresh temporary credentials from AWS STS. By default, + * AWS.config.credentials or AWS.config.credentialProvider will be used. + * @option options tokenCodeFn [Function] (null) Function to provide + * `TokenCode`, if `SerialNumber` is provided for profile in {params}. Function + * is called with value of `SerialNumber` and `callback`, and should provide + * the `TokenCode` or an error to the callback in the format + * `callback(err, token)`. + * @example Creating a new credentials object for generic temporary credentials + * AWS.config.credentials = new AWS.ChainableTemporaryCredentials(); + * @example Creating a new credentials object for an IAM role + * AWS.config.credentials = new AWS.ChainableTemporaryCredentials({ + * params: { + * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials' + * } + * }); + * @see AWS.STS.assumeRole + * @see AWS.STS.getSessionToken + */constructor:function ChainableTemporaryCredentials(options){AWS.Credentials.call(this);options=options||{};this.errorCode='ChainableTemporaryCredentialsProviderFailure';this.expired=true;this.tokenCodeFn=null;var params=AWS.util.copy(options.params)||{};if(params.RoleArn){params.RoleSessionName=params.RoleSessionName||'temporary-credentials';}if(params.SerialNumber){if(!options.tokenCodeFn||typeof options.tokenCodeFn!=='function'){throw new AWS.util.error(new Error('tokenCodeFn must be a function when params.SerialNumber is given'),{code:this.errorCode});}else{this.tokenCodeFn=options.tokenCodeFn;}}var config=AWS.util.merge({params:params,credentials:options.masterCredentials||AWS.config.credentials},options.stsConfig||{});this.service=new STS(config);},/** + * Refreshes credentials using {AWS.STS.assumeRole} or + * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed + * to the credentials {constructor}. + * + * @callback callback function(err) + * Called when the STS service responds (or fails). When + * this callback is called with no error, it means that the credentials + * information has been loaded into the object (as the `accessKeyId`, + * `secretAccessKey`, and `sessionToken` properties). + * @param err [Error] if an error occurred, this value will be filled + * @see AWS.Credentials.get + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private - */ - getUserAgent: function getUserAgent() { - return this._userAgent; - }, - - /** - * @return [String] the part of the {path} excluding the - * query string - */ - pathname: function pathname() { - return this.path.split('?', 1)[0]; - }, - - /** - * @return [String] the query string portion of the {path} - */ - search: function search() { - var query = this.path.split('?', 2)[1]; - if (query) { - query = AWS.util.queryStringParse(query); - return AWS.util.queryParamsToString(query); - } - return ''; - }, - - /** + * @param callback + */load:function load(callback){var self=this;var operation=self.service.config.params.RoleArn?'assumeRole':'getSessionToken';this.getTokenCode(function(err,tokenCode){var params={};if(err){callback(err);return;}if(tokenCode){params.TokenCode=tokenCode;}self.service[operation](params,function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});});},/** * @api private - * update httpRequest endpoint with endpoint string - */ - updateEndpoint: function updateEndpoint(endpointStr) { - var newEndpoint = new AWS.Endpoint(endpointStr); - this.endpoint = newEndpoint; - this.path = newEndpoint.path || '/'; - } -}); - -/** - * The low level HTTP response object, encapsulating all HTTP header - * and body data returned from the request. + */getTokenCode:function getTokenCode(callback){var self=this;if(this.tokenCodeFn){this.tokenCodeFn(this.service.config.params.SerialNumber,function(err,token){if(err){var message=err;if(err instanceof Error){message=err.message;}callback(AWS.util.error(new Error('Error fetching MFA token: '+message),{code:self.errorCode}));return;}callback(null,token);});}else{callback(null);}}});},{"../../clients/sts":8,"../core":18}],21:[function(require,module,exports){var AWS=require('../core');var CognitoIdentity=require('../../clients/cognitoidentity');var STS=require('../../clients/sts');/** + * Represents credentials retrieved from STS Web Identity Federation using + * the Amazon Cognito Identity service. * - * @!attribute statusCode - * @return [Integer] the HTTP status code of the response (e.g., 200, 404) - * @!attribute headers - * @return [map] - * a map of response header keys and their respective values - * @!attribute body - * @return [String] the response body payload - * @!attribute [r] streaming - * @return [Boolean] whether this response is being streamed at a low-level. - * Defaults to `false` (buffered reads). Do not modify this manually, use - * {createUnbufferedStream} to convert the stream to unbuffered mode - * instead. - */ -AWS.HttpResponse = inherit({ - - /** + * By default this provider gets credentials using the + * {AWS.CognitoIdentity.getCredentialsForIdentity} service operation, which + * requires either an `IdentityId` or an `IdentityPoolId` (Amazon Cognito + * Identity Pool ID), which is used to call {AWS.CognitoIdentity.getId} to + * obtain an `IdentityId`. If the identity or identity pool is not configured in + * the Amazon Cognito Console to use IAM roles with the appropriate permissions, + * then additionally a `RoleArn` is required containing the ARN of the IAM trust + * policy for the Amazon Cognito role that the user will log into. If a `RoleArn` + * is provided, then this provider gets credentials using the + * {AWS.STS.assumeRoleWithWebIdentity} service operation, after first getting an + * Open ID token from {AWS.CognitoIdentity.getOpenIdToken}. + * + * In addition, if this credential provider is used to provide authenticated + * login, the `Logins` map may be set to the tokens provided by the respective + * identity providers. See {constructor} for an example on creating a credentials + * object with proper property values. + * + * ## Refreshing Credentials from Identity Service + * + * In addition to AWS credentials expiring after a given amount of time, the + * login token from the identity provider will also expire. Once this token + * expires, it will not be usable to refresh AWS credentials, and another + * token will be needed. The SDK does not manage refreshing of the token value, + * but this can be done through a "refresh token" supported by most identity + * providers. Consult the documentation for the identity provider for refreshing + * tokens. Once the refreshed token is acquired, you should make sure to update + * this new token in the credentials object's {params} property. The following + * code will update the WebIdentityToken, assuming you have retrieved an updated + * token from the identity provider: + * + * ```javascript + * AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken; + * ``` + * + * Future calls to `credentials.refresh()` will now use the new token. + * + * @!attribute params + * @return [map] the map of params passed to + * {AWS.CognitoIdentity.getId}, + * {AWS.CognitoIdentity.getOpenIdToken}, and + * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the + * `params.WebIdentityToken` property. + * @!attribute data + * @return [map] the raw data response from the call to + * {AWS.CognitoIdentity.getCredentialsForIdentity}, or + * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get + * access to other properties from the response. + * @!attribute identityId + * @return [String] the Cognito ID returned by the last call to + * {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual + * final resolved identity ID from Amazon Cognito. + */AWS.CognitoIdentityCredentials=AWS.util.inherit(AWS.Credentials,{/** * @api private - */ - constructor: function HttpResponse() { - this.statusCode = undefined; - this.headers = {}; - this.body = undefined; - this.streaming = false; - this.stream = null; - }, - - /** - * Disables buffering on the HTTP response and returns the stream for reading. - * @return [Stream, XMLHttpRequest, null] the underlying stream object. - * Use this object to directly read data off of the stream. - * @note This object is only available after the {AWS.Request~httpHeaders} - * event has fired. This method must be called prior to - * {AWS.Request~httpData}. - * @example Taking control of a stream - * request.on('httpHeaders', function(statusCode, headers) { - * if (statusCode < 300) { - * if (headers.etag === 'xyz') { - * // pipe the stream, disabling buffering - * var stream = this.response.httpResponse.createUnbufferedStream(); - * stream.pipe(process.stdout); - * } else { // abort this request and set a better error message - * this.abort(); - * this.response.error = new Error('Invalid ETag'); - * } - * } - * }).send(console.log); - */ - createUnbufferedStream: function createUnbufferedStream() { - this.streaming = true; - return this.stream; - } -}); - - -AWS.HttpClient = inherit({}); - -/** - * @api private - */ -AWS.HttpClient.getInstance = function getInstance() { - if (this.singleton === undefined) { - this.singleton = new this(); - } - return this.singleton; -}; - -},{"./core":18}],35:[function(require,module,exports){ -var AWS = require('../core'); -var EventEmitter = require('events').EventEmitter; -require('../http'); - -/** - * @api private - */ -AWS.XHRClient = AWS.util.inherit({ - handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) { - var self = this; - var endpoint = httpRequest.endpoint; - var emitter = new EventEmitter(); - var href = endpoint.protocol + '//' + endpoint.hostname; - if (endpoint.port !== 80 && endpoint.port !== 443) { - href += ':' + endpoint.port; - } - href += httpRequest.path; - - var xhr = new XMLHttpRequest(), headersEmitted = false; - httpRequest.stream = xhr; - - xhr.addEventListener('readystatechange', function() { - try { - if (xhr.status === 0) return; // 0 code is invalid - } catch (e) { return; } - - if (this.readyState >= this.HEADERS_RECEIVED && !headersEmitted) { - emitter.statusCode = xhr.status; - emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders()); - emitter.emit( - 'headers', - emitter.statusCode, - emitter.headers, - xhr.statusText - ); - headersEmitted = true; - } - if (this.readyState === this.DONE) { - self.finishRequest(xhr, emitter); - } - }, false); - xhr.upload.addEventListener('progress', function (evt) { - emitter.emit('sendProgress', evt); - }); - xhr.addEventListener('progress', function (evt) { - emitter.emit('receiveProgress', evt); - }, false); - xhr.addEventListener('timeout', function () { - errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'})); - }, false); - xhr.addEventListener('error', function () { - errCallback(AWS.util.error(new Error('Network Failure'), { - code: 'NetworkingError' - })); - }, false); - xhr.addEventListener('abort', function () { - errCallback(AWS.util.error(new Error('Request aborted'), { - code: 'RequestAbortedError' - })); - }, false); - - callback(emitter); - xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false); - AWS.util.each(httpRequest.headers, function (key, value) { - if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') { - xhr.setRequestHeader(key, value); - } - }); - - if (httpOptions.timeout && httpOptions.xhrAsync !== false) { - xhr.timeout = httpOptions.timeout; - } - - if (httpOptions.xhrWithCredentials) { - xhr.withCredentials = true; - } - try { xhr.responseType = 'arraybuffer'; } catch (e) {} - - try { - if (httpRequest.body) { - xhr.send(httpRequest.body); - } else { - xhr.send(); - } - } catch (err) { - if (httpRequest.body && typeof httpRequest.body.buffer === 'object') { - xhr.send(httpRequest.body.buffer); // send ArrayBuffer directly - } else { - throw err; - } - } - - return emitter; - }, - - parseHeaders: function parseHeaders(rawHeaders) { - var headers = {}; - AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) { - var key = line.split(':', 1)[0]; - var value = line.substring(key.length + 2); - if (key.length > 0) headers[key.toLowerCase()] = value; - }); - return headers; - }, - - finishRequest: function finishRequest(xhr, emitter) { - var buffer; - if (xhr.responseType === 'arraybuffer' && xhr.response) { - var ab = xhr.response; - buffer = new AWS.util.Buffer(ab.byteLength); - var view = new Uint8Array(ab); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = view[i]; - } - } - - try { - if (!buffer && typeof xhr.responseText === 'string') { - buffer = new AWS.util.Buffer(xhr.responseText); - } - } catch (e) {} - - if (buffer) emitter.emit('data', buffer); - emitter.emit('end'); - } -}); - -/** - * @api private - */ -AWS.HttpClient.prototype = AWS.XHRClient.prototype; - -/** + */localStorageKey:{id:'aws.cognito.identity-id.',providers:'aws.cognito.identity-providers.'},/** + * Creates a new credentials object. + * @example Creating a new credentials object + * AWS.config.credentials = new AWS.CognitoIdentityCredentials({ + * + * // either IdentityPoolId or IdentityId is required + * // See the IdentityPoolId param for AWS.CognitoIdentity.getID (linked below) + * // See the IdentityId param for AWS.CognitoIdentity.getCredentialsForIdentity + * // or AWS.CognitoIdentity.getOpenIdToken (linked below) + * IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030', + * IdentityId: 'us-east-1:128d0a74-c82f-4553-916d-90053e4a8b0f' + * + * // optional, only necessary when the identity pool is not configured + * // to use IAM roles in the Amazon Cognito Console + * // See the RoleArn param for AWS.STS.assumeRoleWithWebIdentity (linked below) + * RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity', + * + * // optional tokens, used for authenticated login + * // See the Logins param for AWS.CognitoIdentity.getID (linked below) + * Logins: { + * 'graph.facebook.com': 'FBTOKEN', + * 'www.amazon.com': 'AMAZONTOKEN', + * 'accounts.google.com': 'GOOGLETOKEN', + * 'api.twitter.com': 'TWITTERTOKEN', + * 'www.digits.com': 'DIGITSTOKEN' + * }, + * + * // optional name, defaults to web-identity + * // See the RoleSessionName param for AWS.STS.assumeRoleWithWebIdentity (linked below) + * RoleSessionName: 'web', + * + * // optional, only necessary when application runs in a browser + * // and multiple users are signed in at once, used for caching + * LoginId: 'example@gmail.com' + * + * }, { + * // optionally provide configuration to apply to the underlying service clients + * // if configuration is not provided, then configuration will be pulled from AWS.config + * + * // region should match the region your identity pool is located in + * region: 'us-east-1', + * + * // specify timeout options + * httpOptions: { + * timeout: 100 + * } + * }); + * @see AWS.CognitoIdentity.getId + * @see AWS.CognitoIdentity.getCredentialsForIdentity + * @see AWS.STS.assumeRoleWithWebIdentity + * @see AWS.CognitoIdentity.getOpenIdToken + * @see AWS.Config + * @note If a region is not provided in the global AWS.config, or + * specified in the `clientConfig` to the CognitoIdentityCredentials + * constructor, you may encounter a 'Missing credentials in config' error + * when calling making a service call. + */constructor:function CognitoIdentityCredentials(params,clientConfig){AWS.Credentials.call(this);this.expired=true;this.params=params;this.data=null;this._identityId=null;this._clientConfig=AWS.util.copy(clientConfig||{});this.loadCachedId();var self=this;Object.defineProperty(this,'identityId',{get:function get(){self.loadCachedId();return self._identityId||self.params.IdentityId;},set:function set(identityId){self._identityId=identityId;}});},/** + * Refreshes credentials using {AWS.CognitoIdentity.getCredentialsForIdentity}, + * or {AWS.STS.assumeRoleWithWebIdentity}. + * + * @callback callback function(err) + * Called when the STS service responds (or fails). When + * this callback is called with no error, it means that the credentials + * information has been loaded into the object (as the `accessKeyId`, + * `secretAccessKey`, and `sessionToken` properties). + * @param err [Error] if an error occurred, this value will be filled + * @see AWS.Credentials.get + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** + * @api private + * @param callback + */load:function load(callback){var self=this;self.createClients();self.data=null;self._identityId=null;self.getId(function(err){if(!err){if(!self.params.RoleArn){self.getCredentialsForIdentity(callback);}else{self.getCredentialsFromSTS(callback);}}else{self.clearIdOnNotAuthorized(err);callback(err);}});},/** + * Clears the cached Cognito ID associated with the currently configured + * identity pool ID. Use this to manually invalidate your cache if + * the identity pool ID was deleted. + */clearCachedId:function clearCache(){this._identityId=null;delete this.params.IdentityId;var poolId=this.params.IdentityPoolId;var loginId=this.params.LoginId||'';delete this.storage[this.localStorageKey.id+poolId+loginId];delete this.storage[this.localStorageKey.providers+poolId+loginId];},/** + * @api private + */clearIdOnNotAuthorized:function clearIdOnNotAuthorized(err){var self=this;if(err.code=='NotAuthorizedException'){self.clearCachedId();}},/** + * Retrieves a Cognito ID, loading from cache if it was already retrieved + * on this device. + * + * @callback callback function(err, identityId) + * @param err [Error, null] an error object if the call failed or null if + * it succeeded. + * @param identityId [String, null] if successful, the callback will return + * the Cognito ID. + * @note If not loaded explicitly, the Cognito ID is loaded and stored in + * localStorage in the browser environment of a device. + * @api private + */getId:function getId(callback){var self=this;if(typeof self.params.IdentityId==='string'){return callback(null,self.params.IdentityId);}self.cognito.getId(function(err,data){if(!err&&data.IdentityId){self.params.IdentityId=data.IdentityId;callback(null,data.IdentityId);}else{callback(err);}});},/** + * @api private + */loadCredentials:function loadCredentials(data,credentials){if(!data||!credentials)return;credentials.expired=false;credentials.accessKeyId=data.Credentials.AccessKeyId;credentials.secretAccessKey=data.Credentials.SecretKey;credentials.sessionToken=data.Credentials.SessionToken;credentials.expireTime=data.Credentials.Expiration;},/** + * @api private + */getCredentialsForIdentity:function getCredentialsForIdentity(callback){var self=this;self.cognito.getCredentialsForIdentity(function(err,data){if(!err){self.cacheId(data);self.data=data;self.loadCredentials(self.data,self);}else{self.clearIdOnNotAuthorized(err);}callback(err);});},/** + * @api private + */getCredentialsFromSTS:function getCredentialsFromSTS(callback){var self=this;self.cognito.getOpenIdToken(function(err,data){if(!err){self.cacheId(data);self.params.WebIdentityToken=data.Token;self.webIdentityCredentials.refresh(function(webErr){if(!webErr){self.data=self.webIdentityCredentials.data;self.sts.credentialsFrom(self.data,self);}callback(webErr);});}else{self.clearIdOnNotAuthorized(err);callback(err);}});},/** + * @api private + */loadCachedId:function loadCachedId(){var self=this;// in the browser we source default IdentityId from localStorage +if(AWS.util.isBrowser()&&!self.params.IdentityId){var id=self.getStorage('id');if(id&&self.params.Logins){var actualProviders=Object.keys(self.params.Logins);var cachedProviders=(self.getStorage('providers')||'').split(',');// only load ID if at least one provider used this ID before +var intersect=cachedProviders.filter(function(n){return actualProviders.indexOf(n)!==-1;});if(intersect.length!==0){self.params.IdentityId=id;}}else if(id){self.params.IdentityId=id;}}},/** + * @api private + */createClients:function createClients(){var clientConfig=this._clientConfig;this.webIdentityCredentials=this.webIdentityCredentials||new AWS.WebIdentityCredentials(this.params,clientConfig);if(!this.cognito){var cognitoConfig=AWS.util.merge({},clientConfig);cognitoConfig.params=this.params;this.cognito=new CognitoIdentity(cognitoConfig);}this.sts=this.sts||new STS(clientConfig);},/** + * @api private + */cacheId:function cacheId(data){this._identityId=data.IdentityId;this.params.IdentityId=this._identityId;// cache this IdentityId in browser localStorage if possible +if(AWS.util.isBrowser()){this.setStorage('id',data.IdentityId);if(this.params.Logins){this.setStorage('providers',Object.keys(this.params.Logins).join(','));}}},/** + * @api private + */getStorage:function getStorage(key){return this.storage[this.localStorageKey[key]+this.params.IdentityPoolId+(this.params.LoginId||'')];},/** + * @api private + */setStorage:function setStorage(key,val){try{this.storage[this.localStorageKey[key]+this.params.IdentityPoolId+(this.params.LoginId||'')]=val;}catch(_){}},/** + * @api private + */storage:function(){try{var storage=AWS.util.isBrowser()&&window.localStorage!==null&&_typeof(window.localStorage)==='object'?window.localStorage:{};// Test set/remove which would throw an error in Safari's private browsing +storage['aws.test-storage']='foobar';delete storage['aws.test-storage'];return storage;}catch(_){return{};}}()});},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(require,module,exports){var AWS=require('../core');/** + * Creates a credential provider chain that searches for AWS credentials + * in a list of credential providers specified by the {providers} property. + * + * By default, the chain will use the {defaultProviders} to resolve credentials. + * These providers will look in the environment using the + * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes. + * + * ## Setting Providers + * + * Each provider in the {providers} list should be a function that returns + * a {AWS.Credentials} object, or a hardcoded credentials object. The function + * form allows for delayed execution of the credential construction. + * + * ## Resolving Credentials from a Chain + * + * Call {resolve} to return the first valid credential object that can be + * loaded by the provider chain. + * + * For example, to resolve a chain with a custom provider that checks a file + * on disk after the set of {defaultProviders}: + * + * ```javascript + * var diskProvider = new AWS.FileSystemCredentials('./creds.json'); + * var chain = new AWS.CredentialProviderChain(); + * chain.providers.push(diskProvider); + * chain.resolve(); + * ``` + * + * The above code will return the `diskProvider` object if the + * file contains credentials and the `defaultProviders` do not contain + * any credential settings. + * + * @!attribute providers + * @return [Array] + * a list of credentials objects or functions that return credentials + * objects. If the provider is a function, the function will be + * executed lazily when the provider needs to be checked for valid + * credentials. By default, this object will be set to the + * {defaultProviders}. + * @see defaultProviders + */AWS.CredentialProviderChain=AWS.util.inherit(AWS.Credentials,{/** + * Creates a new CredentialProviderChain with a default set of providers + * specified by {defaultProviders}. + */constructor:function CredentialProviderChain(providers){if(providers){this.providers=providers;}else{this.providers=AWS.CredentialProviderChain.defaultProviders.slice(0);}this.resolveCallbacks=[];},/** + * @!method resolvePromise() + * Returns a 'thenable' promise. + * Resolves the provider chain by searching for the first set of + * credentials in {providers}. + * + * Two callbacks can be provided to the `then` method on the returned promise. + * The first callback will be called if the promise is fulfilled, and the second + * callback will be called if the promise is rejected. + * @callback fulfilledCallback function(credentials) + * Called if the promise is fulfilled and the provider resolves the chain + * to a credentials object + * @param credentials [AWS.Credentials] the credentials object resolved + * by the provider chain. + * @callback rejectedCallback function(error) + * Called if the promise is rejected. + * @param err [Error] the error object returned if no credentials are found. + * @return [Promise] A promise that represents the state of the `resolve` method call. + * @example Calling the `resolvePromise` method. + * var promise = chain.resolvePromise(); + * promise.then(function(credentials) { ... }, function(err) { ... }); + */ /** + * Resolves the provider chain by searching for the first set of + * credentials in {providers}. + * + * @callback callback function(err, credentials) + * Called when the provider resolves the chain to a credentials object + * or null if no credentials can be found. + * + * @param err [Error] the error object returned if no credentials are + * found. + * @param credentials [AWS.Credentials] the credentials object resolved + * by the provider chain. + * @return [AWS.CredentialProviderChain] the provider, for chaining. + */resolve:function resolve(callback){var self=this;if(self.providers.length===0){callback(new Error('No providers'));return self;}if(self.resolveCallbacks.push(callback)===1){var resolveNext=function resolveNext(err,creds){if(!err&&creds||index===providers.length){AWS.util.arrayEach(self.resolveCallbacks,function(callback){callback(err,creds);});self.resolveCallbacks.length=0;return;}var provider=providers[index++];if(typeof provider==='function'){creds=provider.call();}else{creds=provider;}if(creds.get){creds.get(function(getErr){resolveNext(getErr,getErr?null:creds);});}else{resolveNext(null,creds);}};var index=0;var providers=self.providers.slice(0);resolveNext();}return self;}});/** + * The default set of providers used by a vanilla CredentialProviderChain. + * + * In the browser: + * + * ```javascript + * AWS.CredentialProviderChain.defaultProviders = [] + * ``` + * + * In Node.js: + * + * ```javascript + * AWS.CredentialProviderChain.defaultProviders = [ + * function () { return new AWS.EnvironmentCredentials('AWS'); }, + * function () { return new AWS.EnvironmentCredentials('AMAZON'); }, + * function () { return new AWS.SharedIniFileCredentials(); }, + * function () { return new AWS.ECSCredentials(); }, + * function () { return new AWS.ProcessCredentials(); }, + * function () { return new AWS.TokenFileWebIdentityCredentials(); }, + * function () { return new AWS.EC2MetadataCredentials() } + * ] + * ``` + */AWS.CredentialProviderChain.defaultProviders=[];/** * @api private - */ -AWS.HttpClient.streamsApiVersion = 1; - -},{"../core":18,"../http":34,"events":82}],36:[function(require,module,exports){ -var util = require('../util'); - -function JsonBuilder() { } - -JsonBuilder.prototype.build = function(value, shape) { - return JSON.stringify(translate(value, shape)); -}; - -function translate(value, shape) { - if (!shape || value === undefined || value === null) return undefined; - - switch (shape.type) { - case 'structure': return translateStructure(value, shape); - case 'map': return translateMap(value, shape); - case 'list': return translateList(value, shape); - default: return translateScalar(value, shape); - } -} - -function translateStructure(structure, shape) { - var struct = {}; - util.each(structure, function(name, value) { - var memberShape = shape.members[name]; - if (memberShape) { - if (memberShape.location !== 'body') return; - var locationName = memberShape.isLocationName ? memberShape.name : name; - var result = translate(value, memberShape); - if (result !== undefined) struct[locationName] = result; - } - }); - return struct; -} - -function translateList(list, shape) { - var out = []; - util.arrayEach(list, function(value) { - var result = translate(value, shape.member); - if (result !== undefined) out.push(result); - }); - return out; -} - -function translateMap(map, shape) { - var out = {}; - util.each(map, function(key, value) { - var result = translate(value, shape.value); - if (result !== undefined) out[key] = result; - }); - return out; -} - -function translateScalar(value, shape) { - return shape.toWireFormat(value); -} - -/** + */AWS.CredentialProviderChain.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.resolvePromise=AWS.util.promisifyMethod('resolve',PromiseDependency);};/** * @api private - */ -module.exports = JsonBuilder; - -},{"../util":71}],37:[function(require,module,exports){ -var util = require('../util'); - -function JsonParser() { } - -JsonParser.prototype.parse = function(value, shape) { - return translate(JSON.parse(value), shape); -}; - -function translate(value, shape) { - if (!shape || value === undefined) return undefined; - - switch (shape.type) { - case 'structure': return translateStructure(value, shape); - case 'map': return translateMap(value, shape); - case 'list': return translateList(value, shape); - default: return translateScalar(value, shape); - } -} - -function translateStructure(structure, shape) { - if (structure == null) return undefined; - - var struct = {}; - var shapeMembers = shape.members; - util.each(shapeMembers, function(name, memberShape) { - var locationName = memberShape.isLocationName ? memberShape.name : name; - if (Object.prototype.hasOwnProperty.call(structure, locationName)) { - var value = structure[locationName]; - var result = translate(value, memberShape); - if (result !== undefined) struct[name] = result; - } - }); - return struct; -} - -function translateList(list, shape) { - if (list == null) return undefined; - - var out = []; - util.arrayEach(list, function(value) { - var result = translate(value, shape.member); - if (result === undefined) out.push(null); - else out.push(result); - }); - return out; -} - -function translateMap(map, shape) { - if (map == null) return undefined; - - var out = {}; - util.each(map, function(key, value) { - var result = translate(value, shape.value); - if (result === undefined) out[key] = null; - else out[key] = result; - }); - return out; -} - -function translateScalar(value, shape) { - return shape.toType(value); -} - -/** + */AWS.CredentialProviderChain.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.resolvePromise;};AWS.util.addPromises(AWS.CredentialProviderChain);},{"../core":18}],23:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** + * Represents credentials retrieved from STS SAML support. + * + * By default this provider gets credentials using the + * {AWS.STS.assumeRoleWithSAML} service operation. This operation + * requires a `RoleArn` containing the ARN of the IAM trust policy for the + * application for which credentials will be given, as well as a `PrincipalArn` + * representing the ARN for the SAML identity provider. In addition, the + * `SAMLAssertion` must be set to the token provided by the identity + * provider. See {constructor} for an example on creating a credentials + * object with proper `RoleArn`, `PrincipalArn`, and `SAMLAssertion` values. + * + * ## Refreshing Credentials from Identity Service + * + * In addition to AWS credentials expiring after a given amount of time, the + * login token from the identity provider will also expire. Once this token + * expires, it will not be usable to refresh AWS credentials, and another + * token will be needed. The SDK does not manage refreshing of the token value, + * but this can be done through a "refresh token" supported by most identity + * providers. Consult the documentation for the identity provider for refreshing + * tokens. Once the refreshed token is acquired, you should make sure to update + * this new token in the credentials object's {params} property. The following + * code will update the SAMLAssertion, assuming you have retrieved an updated + * token from the identity provider: + * + * ```javascript + * AWS.config.credentials.params.SAMLAssertion = updatedToken; + * ``` + * + * Future calls to `credentials.refresh()` will now use the new token. + * + * @!attribute params + * @return [map] the map of params passed to + * {AWS.STS.assumeRoleWithSAML}. To update the token, set the + * `params.SAMLAssertion` property. + */AWS.SAMLCredentials=AWS.util.inherit(AWS.Credentials,{/** + * Creates a new credentials object. + * @param (see AWS.STS.assumeRoleWithSAML) + * @example Creating a new credentials object + * AWS.config.credentials = new AWS.SAMLCredentials({ + * RoleArn: 'arn:aws:iam::1234567890:role/SAMLRole', + * PrincipalArn: 'arn:aws:iam::1234567890:role/SAMLPrincipal', + * SAMLAssertion: 'base64-token', // base64-encoded token from IdP + * }); + * @see AWS.STS.assumeRoleWithSAML + */constructor:function SAMLCredentials(params){AWS.Credentials.call(this);this.expired=true;this.params=params;},/** + * Refreshes credentials using {AWS.STS.assumeRoleWithSAML} + * + * @callback callback function(err) + * Called when the STS service responds (or fails). When + * this callback is called with no error, it means that the credentials + * information has been loaded into the object (as the `accessKeyId`, + * `secretAccessKey`, and `sessionToken` properties). + * @param err [Error] if an error occurred, this value will be filled + * @see get + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** + * @api private + */load:function load(callback){var self=this;self.createClients();self.service.assumeRoleWithSAML(function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});},/** + * @api private + */createClients:function createClients(){this.service=this.service||new STS({params:this.params});}});},{"../../clients/sts":8,"../core":18}],24:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** + * Represents temporary credentials retrieved from {AWS.STS}. Without any + * extra parameters, credentials will be fetched from the + * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the + * {AWS.STS.assumeRole} operation will be used to fetch credentials for the + * role instead. + * + * @note AWS.TemporaryCredentials is deprecated, but remains available for + * backwards compatibility. {AWS.ChainableTemporaryCredentials} is the + * preferred class for temporary credentials. + * + * To setup temporary credentials, configure a set of master credentials + * using the standard credentials providers (environment, EC2 instance metadata, + * or from the filesystem), then set the global credentials to a new + * temporary credentials object: + * + * ```javascript + * // Note that environment credentials are loaded by default, + * // the following line is shown for clarity: + * AWS.config.credentials = new AWS.EnvironmentCredentials('AWS'); + * + * // Now set temporary credentials seeded from the master credentials + * AWS.config.credentials = new AWS.TemporaryCredentials(); + * + * // subsequent requests will now use temporary credentials from AWS STS. + * new AWS.S3().listBucket(function(err, data) { ... }); + * ``` + * + * @!attribute masterCredentials + * @return [AWS.Credentials] the master (non-temporary) credentials used to + * get and refresh temporary credentials from AWS STS. + * @note (see constructor) + */AWS.TemporaryCredentials=AWS.util.inherit(AWS.Credentials,{/** + * Creates a new temporary credentials object. + * + * @note In order to create temporary credentials, you first need to have + * "master" credentials configured in {AWS.Config.credentials}. These + * master credentials are necessary to retrieve the temporary credentials, + * as well as refresh the credentials when they expire. + * @param params [map] a map of options that are passed to the + * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. + * If a `RoleArn` parameter is passed in, credentials will be based on the + * IAM role. + * @param masterCredentials [AWS.Credentials] the master (non-temporary) credentials + * used to get and refresh temporary credentials from AWS STS. + * @example Creating a new credentials object for generic temporary credentials + * AWS.config.credentials = new AWS.TemporaryCredentials(); + * @example Creating a new credentials object for an IAM role + * AWS.config.credentials = new AWS.TemporaryCredentials({ + * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials', + * }); + * @see AWS.STS.assumeRole + * @see AWS.STS.getSessionToken + */constructor:function TemporaryCredentials(params,masterCredentials){AWS.Credentials.call(this);this.loadMasterCredentials(masterCredentials);this.expired=true;this.params=params||{};if(this.params.RoleArn){this.params.RoleSessionName=this.params.RoleSessionName||'temporary-credentials';}},/** + * Refreshes credentials using {AWS.STS.assumeRole} or + * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed + * to the credentials {constructor}. + * + * @callback callback function(err) + * Called when the STS service responds (or fails). When + * this callback is called with no error, it means that the credentials + * information has been loaded into the object (as the `accessKeyId`, + * `secretAccessKey`, and `sessionToken` properties). + * @param err [Error] if an error occurred, this value will be filled + * @see get + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** + * @api private + */load:function load(callback){var self=this;self.createClients();self.masterCredentials.get(function(){self.service.config.credentials=self.masterCredentials;var operation=self.params.RoleArn?self.service.assumeRole:self.service.getSessionToken;operation.call(self.service,function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});});},/** + * @api private + */loadMasterCredentials:function loadMasterCredentials(masterCredentials){this.masterCredentials=masterCredentials||AWS.config.credentials;while(this.masterCredentials.masterCredentials){this.masterCredentials=this.masterCredentials.masterCredentials;}if(typeof this.masterCredentials.get!=='function'){this.masterCredentials=new AWS.Credentials(this.masterCredentials);}},/** + * @api private + */createClients:function createClients(){this.service=this.service||new STS({params:this.params});}});},{"../../clients/sts":8,"../core":18}],25:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** + * Represents credentials retrieved from STS Web Identity Federation support. + * + * By default this provider gets credentials using the + * {AWS.STS.assumeRoleWithWebIdentity} service operation. This operation + * requires a `RoleArn` containing the ARN of the IAM trust policy for the + * application for which credentials will be given. In addition, the + * `WebIdentityToken` must be set to the token provided by the identity + * provider. See {constructor} for an example on creating a credentials + * object with proper `RoleArn` and `WebIdentityToken` values. + * + * ## Refreshing Credentials from Identity Service + * + * In addition to AWS credentials expiring after a given amount of time, the + * login token from the identity provider will also expire. Once this token + * expires, it will not be usable to refresh AWS credentials, and another + * token will be needed. The SDK does not manage refreshing of the token value, + * but this can be done through a "refresh token" supported by most identity + * providers. Consult the documentation for the identity provider for refreshing + * tokens. Once the refreshed token is acquired, you should make sure to update + * this new token in the credentials object's {params} property. The following + * code will update the WebIdentityToken, assuming you have retrieved an updated + * token from the identity provider: + * + * ```javascript + * AWS.config.credentials.params.WebIdentityToken = updatedToken; + * ``` + * + * Future calls to `credentials.refresh()` will now use the new token. + * + * @!attribute params + * @return [map] the map of params passed to + * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the + * `params.WebIdentityToken` property. + * @!attribute data + * @return [map] the raw data response from the call to + * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get + * access to other properties from the response. + */AWS.WebIdentityCredentials=AWS.util.inherit(AWS.Credentials,{/** + * Creates a new credentials object. + * @param (see AWS.STS.assumeRoleWithWebIdentity) + * @example Creating a new credentials object + * AWS.config.credentials = new AWS.WebIdentityCredentials({ + * RoleArn: 'arn:aws:iam::1234567890:role/WebIdentity', + * WebIdentityToken: 'ABCDEFGHIJKLMNOP', // token from identity service + * RoleSessionName: 'web' // optional name, defaults to web-identity + * }, { + * // optionally provide configuration to apply to the underlying AWS.STS service client + * // if configuration is not provided, then configuration will be pulled from AWS.config + * + * // specify timeout options + * httpOptions: { + * timeout: 100 + * } + * }); + * @see AWS.STS.assumeRoleWithWebIdentity + * @see AWS.Config + */constructor:function WebIdentityCredentials(params,clientConfig){AWS.Credentials.call(this);this.expired=true;this.params=params;this.params.RoleSessionName=this.params.RoleSessionName||'web-identity';this.data=null;this._clientConfig=AWS.util.copy(clientConfig||{});},/** + * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity} + * + * @callback callback function(err) + * Called when the STS service responds (or fails). When + * this callback is called with no error, it means that the credentials + * information has been loaded into the object (as the `accessKeyId`, + * `secretAccessKey`, and `sessionToken` properties). + * @param err [Error] if an error occurred, this value will be filled + * @see get + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** + * @api private + */load:function load(callback){var self=this;self.createClients();self.service.assumeRoleWithWebIdentity(function(err,data){self.data=null;if(!err){self.data=data;self.service.credentialsFrom(data,self);}callback(err);});},/** + * @api private + */createClients:function createClients(){if(!this.service){var stsConfig=AWS.util.merge({},this._clientConfig);stsConfig.params=this.params;this.service=new STS(stsConfig);}}});},{"../../clients/sts":8,"../core":18}],26:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');var util=require('./util');var endpointDiscoveryEnabledEnvs=['AWS_ENABLE_ENDPOINT_DISCOVERY','AWS_ENDPOINT_DISCOVERY_ENABLED'];/** + * Generate key (except resources and operation part) to index the endpoints in the cache + * If input shape has endpointdiscoveryid trait then use + * accessKey + operation + resources + region + service as cache key + * If input shape doesn't have endpointdiscoveryid trait then use + * accessKey + region + service as cache key + * @return [map] object with keys to index endpoints. * @api private - */ -module.exports = JsonParser; - -},{"../util":71}],38:[function(require,module,exports){ -var Collection = require('./collection'); -var Operation = require('./operation'); -var Shape = require('./shape'); -var Paginator = require('./paginator'); -var ResourceWaiter = require('./resource_waiter'); - -var util = require('../util'); -var property = util.property; -var memoizedProperty = util.memoizedProperty; - -function Api(api, options) { - var self = this; - api = api || {}; - options = options || {}; - options.api = this; - - api.metadata = api.metadata || {}; - - property(this, 'isApi', true, false); - property(this, 'apiVersion', api.metadata.apiVersion); - property(this, 'endpointPrefix', api.metadata.endpointPrefix); - property(this, 'signingName', api.metadata.signingName); - property(this, 'globalEndpoint', api.metadata.globalEndpoint); - property(this, 'signatureVersion', api.metadata.signatureVersion); - property(this, 'jsonVersion', api.metadata.jsonVersion); - property(this, 'targetPrefix', api.metadata.targetPrefix); - property(this, 'protocol', api.metadata.protocol); - property(this, 'timestampFormat', api.metadata.timestampFormat); - property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace); - property(this, 'abbreviation', api.metadata.serviceAbbreviation); - property(this, 'fullName', api.metadata.serviceFullName); - property(this, 'serviceId', api.metadata.serviceId); - - memoizedProperty(this, 'className', function() { - var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName; - if (!name) return null; - - name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, ''); - if (name === 'ElasticLoadBalancing') name = 'ELB'; - return name; - }); - - function addEndpointOperation(name, operation) { - if (operation.endpointoperation === true) { - property(self, 'endpointOperation', util.string.lowerFirst(name)); - } - } - - property(this, 'operations', new Collection(api.operations, options, function(name, operation) { - return new Operation(name, operation, options); - }, util.string.lowerFirst, addEndpointOperation)); - - property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) { - return Shape.create(shape, options); - })); - - property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) { - return new Paginator(name, paginator, options); - })); - - property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) { - return new ResourceWaiter(name, waiter, options); - }, util.string.lowerFirst)); - - if (options.documentation) { - property(this, 'documentation', api.documentation); - property(this, 'documentationUrl', api.documentationUrl); - } -} - -/** + */function getCacheKey(request){var service=request.service;var api=service.api||{};var operations=api.operations;var identifiers={};if(service.config.region){identifiers.region=service.config.region;}if(api.serviceId){identifiers.serviceId=api.serviceId;}if(service.config.credentials.accessKeyId){identifiers.accessKeyId=service.config.credentials.accessKeyId;}return identifiers;}/** + * Recursive helper for marshallCustomIdentifiers(). + * Looks for required string input members that have 'endpointdiscoveryid' trait. * @api private - */ -module.exports = Api; - -},{"../util":71,"./collection":39,"./operation":40,"./paginator":41,"./resource_waiter":42,"./shape":43}],39:[function(require,module,exports){ -var memoizedProperty = require('../util').memoizedProperty; - -function memoize(name, value, factory, nameTr) { - memoizedProperty(this, nameTr(name), function() { - return factory(name, value); - }); -} - -function Collection(iterable, options, factory, nameTr, callback) { - nameTr = nameTr || String; - var self = this; - - for (var id in iterable) { - if (Object.prototype.hasOwnProperty.call(iterable, id)) { - memoize.call(self, id, iterable[id], factory, nameTr); - if (callback) callback(id, iterable[id]); - } - } -} - -/** + */function marshallCustomIdentifiersHelper(result,params,shape){if(!shape||params===undefined||params===null)return;if(shape.type==='structure'&&shape.required&&shape.required.length>0){util.arrayEach(shape.required,function(name){var memberShape=shape.members[name];if(memberShape.endpointDiscoveryId===true){var locationName=memberShape.isLocationName?memberShape.name:name;result[locationName]=String(params[name]);}else{marshallCustomIdentifiersHelper(result,params[name],memberShape);}});}}/** + * Get custom identifiers for cache key. + * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait. + * @param [object] request object + * @param [object] input shape of the given operation's api * @api private - */ -module.exports = Collection; - -},{"../util":71}],40:[function(require,module,exports){ -var Shape = require('./shape'); - -var util = require('../util'); -var property = util.property; -var memoizedProperty = util.memoizedProperty; - -function Operation(name, operation, options) { - var self = this; - options = options || {}; - - property(this, 'name', operation.name || name); - property(this, 'api', options.api, false); - - operation.http = operation.http || {}; - property(this, 'endpoint', operation.endpoint); - property(this, 'httpMethod', operation.http.method || 'POST'); - property(this, 'httpPath', operation.http.requestUri || '/'); - property(this, 'authtype', operation.authtype || ''); - property( - this, - 'endpointDiscoveryRequired', - operation.endpointdiscovery ? - (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') : - 'NULL' - ); - - memoizedProperty(this, 'input', function() { - if (!operation.input) { - return new Shape.create({type: 'structure'}, options); - } - return Shape.create(operation.input, options); - }); - - memoizedProperty(this, 'output', function() { - if (!operation.output) { - return new Shape.create({type: 'structure'}, options); - } - return Shape.create(operation.output, options); - }); - - memoizedProperty(this, 'errors', function() { - var list = []; - if (!operation.errors) return null; - - for (var i = 0; i < operation.errors.length; i++) { - list.push(Shape.create(operation.errors[i], options)); - } - - return list; - }); - - memoizedProperty(this, 'paginator', function() { - return options.api.paginators[name]; - }); - - if (options.documentation) { - property(this, 'documentation', operation.documentation); - property(this, 'documentationUrl', operation.documentationUrl); - } - - // idempotentMembers only tracks top-level input shapes - memoizedProperty(this, 'idempotentMembers', function() { - var idempotentMembers = []; - var input = self.input; - var members = input.members; - if (!input.members) { - return idempotentMembers; - } - for (var name in members) { - if (!members.hasOwnProperty(name)) { - continue; - } - if (members[name].isIdempotent === true) { - idempotentMembers.push(name); - } - } - return idempotentMembers; - }); - - memoizedProperty(this, 'hasEventOutput', function() { - var output = self.output; - return hasEventStream(output); - }); -} - -function hasEventStream(topLevelShape) { - var members = topLevelShape.members; - var payload = topLevelShape.payload; - - if (!topLevelShape.members) { - return false; - } - - if (payload) { - var payloadMember = members[payload]; - return payloadMember.isEventStream; - } - - // check if any member is an event stream - for (var name in members) { - if (!members.hasOwnProperty(name)) { - if (members[name].isEventStream === true) { - return true; - } - } - } - return false; -} - -/** + */function marshallCustomIdentifiers(request,shape){var identifiers={};marshallCustomIdentifiersHelper(identifiers,request.params,shape);return identifiers;}/** + * Call endpoint discovery operation when it's optional. + * When endpoint is available in cache then use the cached endpoints. If endpoints + * are unavailable then use regional endpoints and call endpoint discovery operation + * asynchronously. This is turned off by default. + * @param [object] request object * @api private - */ -module.exports = Operation; - -},{"../util":71,"./shape":43}],41:[function(require,module,exports){ -var property = require('../util').property; - -function Paginator(name, paginator) { - property(this, 'inputToken', paginator.input_token); - property(this, 'limitKey', paginator.limit_key); - property(this, 'moreResults', paginator.more_results); - property(this, 'outputToken', paginator.output_token); - property(this, 'resultKey', paginator.result_key); -} - -/** + */function optionalDiscoverEndpoint(request){var service=request.service;var api=service.api;var operationModel=api.operations?api.operations[request.operation]:undefined;var inputShape=operationModel?operationModel.input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operationModel)cacheKey.operation=operationModel.name;}var endpoints=AWS.endpointCache.get(cacheKey);if(endpoints&&endpoints.length===1&&endpoints[0].Address===''){//endpoint operation is being made but response not yet received +//or endpoint operation just failed in 1 minute +return;}else if(endpoints&&endpoints.length>0){//found endpoint record from cache +request.httpRequest.updateEndpoint(endpoints[0].Address);}else{//endpoint record not in cache or outdated. make discovery operation +var endpointRequest=service.makeRequest(api.endpointOperation,{Operation:operationModel.name,Identifiers:identifiers});addApiVersionHeader(endpointRequest);endpointRequest.removeListener('validate',AWS.EventListeners.Core.VALIDATE_PARAMETERS);endpointRequest.removeListener('retry',AWS.EventListeners.Core.RETRY_CHECK);//put in a placeholder for endpoints already requested, prevent +//too much in-flight calls +AWS.endpointCache.put(cacheKey,[{Address:'',CachePeriodInMinutes:1}]);endpointRequest.send(function(err,data){if(data&&data.Endpoints){AWS.endpointCache.put(cacheKey,data.Endpoints);}else if(err){AWS.endpointCache.put(cacheKey,[{Address:'',CachePeriodInMinutes:1//not to make more endpoint operation in next 1 minute +}]);}});}}var requestQueue={};/** + * Call endpoint discovery operation when it's required. + * When endpoint is available in cache then use cached ones. If endpoints are + * unavailable then SDK should call endpoint operation then use returned new + * endpoint for the api call. SDK will automatically attempt to do endpoint + * discovery. This is turned off by default + * @param [object] request object * @api private - */ -module.exports = Paginator; - -},{"../util":71}],42:[function(require,module,exports){ -var util = require('../util'); -var property = util.property; - -function ResourceWaiter(name, waiter, options) { - options = options || {}; - property(this, 'name', name); - property(this, 'api', options.api, false); - - if (waiter.operation) { - property(this, 'operation', util.string.lowerFirst(waiter.operation)); - } - - var self = this; - var keys = [ - 'type', - 'description', - 'delay', - 'maxAttempts', - 'acceptors' - ]; - - keys.forEach(function(key) { - var value = waiter[key]; - if (value) { - property(self, key, value); - } - }); -} - -/** + */function requiredDiscoverEndpoint(request,done){var service=request.service;var api=service.api;var operationModel=api.operations?api.operations[request.operation]:undefined;var inputShape=operationModel?operationModel.input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operationModel)cacheKey.operation=operationModel.name;}var cacheKeyStr=AWS.EndpointCache.getKeyString(cacheKey);var endpoints=AWS.endpointCache.get(cacheKeyStr);//endpoint cache also accepts string keys +if(endpoints&&endpoints.length===1&&endpoints[0].Address===''){//endpoint operation is being made but response not yet received +//push request object to a pending queue +if(!requestQueue[cacheKeyStr])requestQueue[cacheKeyStr]=[];requestQueue[cacheKeyStr].push({request:request,callback:done});return;}else if(endpoints&&endpoints.length>0){request.httpRequest.updateEndpoint(endpoints[0].Address);done();}else{var endpointRequest=service.makeRequest(api.endpointOperation,{Operation:operationModel.name,Identifiers:identifiers});endpointRequest.removeListener('validate',AWS.EventListeners.Core.VALIDATE_PARAMETERS);addApiVersionHeader(endpointRequest);//put in a placeholder for endpoints already requested, prevent +//too much in-flight calls +AWS.endpointCache.put(cacheKeyStr,[{Address:'',CachePeriodInMinutes:60//long-live cache +}]);endpointRequest.send(function(err,data){if(err){var errorParams={code:'EndpointDiscoveryException',message:'Request cannot be fulfilled without specifying an endpoint',retryable:false};request.response.error=util.error(err,errorParams);AWS.endpointCache.remove(cacheKey);//fail all the pending requests in batch +if(requestQueue[cacheKeyStr]){var pendingRequests=requestQueue[cacheKeyStr];util.arrayEach(pendingRequests,function(requestContext){requestContext.request.response.error=util.error(err,errorParams);requestContext.callback();});delete requestQueue[cacheKeyStr];}}else if(data){AWS.endpointCache.put(cacheKeyStr,data.Endpoints);request.httpRequest.updateEndpoint(data.Endpoints[0].Address);//update the endpoint for all the pending requests in batch +if(requestQueue[cacheKeyStr]){var pendingRequests=requestQueue[cacheKeyStr];util.arrayEach(pendingRequests,function(requestContext){requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);requestContext.callback();});delete requestQueue[cacheKeyStr];}}done();});}}/** + * add api version header to endpoint operation * @api private - */ -module.exports = ResourceWaiter; - -},{"../util":71}],43:[function(require,module,exports){ -var Collection = require('./collection'); - -var util = require('../util'); - -function property(obj, name, value) { - if (value !== null && value !== undefined) { - util.property.apply(this, arguments); - } -} - -function memoizedProperty(obj, name) { - if (!obj.constructor.prototype[name]) { - util.memoizedProperty.apply(this, arguments); - } -} - -function Shape(shape, options, memberName) { - options = options || {}; - - property(this, 'shape', shape.shape); - property(this, 'api', options.api, false); - property(this, 'type', shape.type); - property(this, 'enum', shape.enum); - property(this, 'min', shape.min); - property(this, 'max', shape.max); - property(this, 'pattern', shape.pattern); - property(this, 'location', shape.location || this.location || 'body'); - property(this, 'name', this.name || shape.xmlName || shape.queryName || - shape.locationName || memberName); - property(this, 'isStreaming', shape.streaming || this.isStreaming || false); - property(this, 'requiresLength', shape.requiresLength, false); - property(this, 'isComposite', shape.isComposite || false); - property(this, 'isShape', true, false); - property(this, 'isQueryName', Boolean(shape.queryName), false); - property(this, 'isLocationName', Boolean(shape.locationName), false); - property(this, 'isIdempotent', shape.idempotencyToken === true); - property(this, 'isJsonValue', shape.jsonvalue === true); - property(this, 'isSensitive', shape.sensitive === true || shape.prototype && shape.prototype.sensitive === true); - property(this, 'isEventStream', Boolean(shape.eventstream), false); - property(this, 'isEvent', Boolean(shape.event), false); - property(this, 'isEventPayload', Boolean(shape.eventpayload), false); - property(this, 'isEventHeader', Boolean(shape.eventheader), false); - property(this, 'isTimestampFormatSet', Boolean(shape.timestampFormat) || shape.prototype && shape.prototype.isTimestampFormatSet === true, false); - property(this, 'endpointDiscoveryId', Boolean(shape.endpointdiscoveryid), false); - property(this, 'hostLabel', Boolean(shape.hostLabel), false); - - if (options.documentation) { - property(this, 'documentation', shape.documentation); - property(this, 'documentationUrl', shape.documentationUrl); - } - - if (shape.xmlAttribute) { - property(this, 'isXmlAttribute', shape.xmlAttribute || false); - } - - // type conversion and parsing - property(this, 'defaultValue', null); - this.toWireFormat = function(value) { - if (value === null || value === undefined) return ''; - return value; - }; - this.toType = function(value) { return value; }; -} - -/** + */function addApiVersionHeader(endpointRequest){var api=endpointRequest.service.api;var apiVersion=api.apiVersion;if(apiVersion&&!endpointRequest.httpRequest.headers['x-amz-api-version']){endpointRequest.httpRequest.headers['x-amz-api-version']=apiVersion;}}/** + * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid + * endpoint from cache. * @api private - */ -Shape.normalizedTypes = { - character: 'string', - double: 'float', - long: 'integer', - short: 'integer', - biginteger: 'integer', - bigdecimal: 'float', - blob: 'binary' -}; - -/** + */function invalidateCachedEndpoints(response){var error=response.error;var httpResponse=response.httpResponse;if(error&&(error.code==='InvalidEndpointException'||httpResponse.statusCode===421)){var request=response.request;var operations=request.service.api.operations||{};var inputShape=operations[request.operation]?operations[request.operation].input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operations[request.operation])cacheKey.operation=operations[request.operation].name;}AWS.endpointCache.remove(cacheKey);}}/** + * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime. + * @param [object] client Service client object. * @api private - */ -Shape.types = { - 'structure': StructureShape, - 'list': ListShape, - 'map': MapShape, - 'boolean': BooleanShape, - 'timestamp': TimestampShape, - 'float': FloatShape, - 'integer': IntegerShape, - 'string': StringShape, - 'base64': Base64Shape, - 'binary': BinaryShape -}; - -Shape.resolve = function resolve(shape, options) { - if (shape.shape) { - var refShape = options.api.shapes[shape.shape]; - if (!refShape) { - throw new Error('Cannot find shape reference: ' + shape.shape); - } - - return refShape; - } else { - return null; - } -}; - -Shape.create = function create(shape, options, memberName) { - if (shape.isShape) return shape; - - var refShape = Shape.resolve(shape, options); - if (refShape) { - var filteredKeys = Object.keys(shape); - if (!options.documentation) { - filteredKeys = filteredKeys.filter(function(name) { - return !name.match(/documentation/); - }); - } - - // create an inline shape with extra members - var InlineShape = function() { - refShape.constructor.call(this, shape, options, memberName); - }; - InlineShape.prototype = refShape; - return new InlineShape(); - } else { - // set type if not set - if (!shape.type) { - if (shape.members) shape.type = 'structure'; - else if (shape.member) shape.type = 'list'; - else if (shape.key) shape.type = 'map'; - else shape.type = 'string'; - } - - // normalize types - var origType = shape.type; - if (Shape.normalizedTypes[shape.type]) { - shape.type = Shape.normalizedTypes[shape.type]; - } - - if (Shape.types[shape.type]) { - return new Shape.types[shape.type](shape, options, memberName); - } else { - throw new Error('Unrecognized shape type: ' + origType); - } - } -}; - -function CompositeShape(shape) { - Shape.apply(this, arguments); - property(this, 'isComposite', true); - - if (shape.flattened) { - property(this, 'flattened', shape.flattened || false); - } -} - -function StructureShape(shape, options) { - var self = this; - var requiredMap = null, firstInit = !this.isShape; - - CompositeShape.apply(this, arguments); - - if (firstInit) { - property(this, 'defaultValue', function() { return {}; }); - property(this, 'members', {}); - property(this, 'memberNames', []); - property(this, 'required', []); - property(this, 'isRequired', function() { return false; }); - } - - if (shape.members) { - property(this, 'members', new Collection(shape.members, options, function(name, member) { - return Shape.create(member, options, name); - })); - memoizedProperty(this, 'memberNames', function() { - return shape.xmlOrder || Object.keys(shape.members); - }); - - if (shape.event) { - memoizedProperty(this, 'eventPayloadMemberName', function() { - var members = self.members; - var memberNames = self.memberNames; - // iterate over members to find ones that are event payloads - for (var i = 0, iLen = memberNames.length; i < iLen; i++) { - if (members[memberNames[i]].isEventPayload) { - return memberNames[i]; - } - } - }); - - memoizedProperty(this, 'eventHeaderMemberNames', function() { - var members = self.members; - var memberNames = self.memberNames; - var eventHeaderMemberNames = []; - // iterate over members to find ones that are event headers - for (var i = 0, iLen = memberNames.length; i < iLen; i++) { - if (members[memberNames[i]].isEventHeader) { - eventHeaderMemberNames.push(memberNames[i]); - } - } - return eventHeaderMemberNames; - }); - } - } - - if (shape.required) { - property(this, 'required', shape.required); - property(this, 'isRequired', function(name) { - if (!requiredMap) { - requiredMap = {}; - for (var i = 0; i < shape.required.length; i++) { - requiredMap[shape.required[i]] = true; - } - } - - return requiredMap[name]; - }, false, true); - } - - property(this, 'resultWrapper', shape.resultWrapper || null); - - if (shape.payload) { - property(this, 'payload', shape.payload); - } - - if (typeof shape.xmlNamespace === 'string') { - property(this, 'xmlNamespaceUri', shape.xmlNamespace); - } else if (typeof shape.xmlNamespace === 'object') { - property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix); - property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri); - } -} - -function ListShape(shape, options) { - var self = this, firstInit = !this.isShape; - CompositeShape.apply(this, arguments); - - if (firstInit) { - property(this, 'defaultValue', function() { return []; }); - } - - if (shape.member) { - memoizedProperty(this, 'member', function() { - return Shape.create(shape.member, options); - }); - } - - if (this.flattened) { - var oldName = this.name; - memoizedProperty(this, 'name', function() { - return self.member.name || oldName; - }); - } -} - -function MapShape(shape, options) { - var firstInit = !this.isShape; - CompositeShape.apply(this, arguments); - - if (firstInit) { - property(this, 'defaultValue', function() { return {}; }); - property(this, 'key', Shape.create({type: 'string'}, options)); - property(this, 'value', Shape.create({type: 'string'}, options)); - } - - if (shape.key) { - memoizedProperty(this, 'key', function() { - return Shape.create(shape.key, options); - }); - } - if (shape.value) { - memoizedProperty(this, 'value', function() { - return Shape.create(shape.value, options); - }); - } -} - -function TimestampShape(shape) { - var self = this; - Shape.apply(this, arguments); - - if (shape.timestampFormat) { - property(this, 'timestampFormat', shape.timestampFormat); - } else if (self.isTimestampFormatSet && this.timestampFormat) { - property(this, 'timestampFormat', this.timestampFormat); - } else if (this.location === 'header') { - property(this, 'timestampFormat', 'rfc822'); - } else if (this.location === 'querystring') { - property(this, 'timestampFormat', 'iso8601'); - } else if (this.api) { - switch (this.api.protocol) { - case 'json': - case 'rest-json': - property(this, 'timestampFormat', 'unixTimestamp'); - break; - case 'rest-xml': - case 'query': - case 'ec2': - property(this, 'timestampFormat', 'iso8601'); - break; - } - } - - this.toType = function(value) { - if (value === null || value === undefined) return null; - if (typeof value.toUTCString === 'function') return value; - return typeof value === 'string' || typeof value === 'number' ? - util.date.parseTimestamp(value) : null; - }; - - this.toWireFormat = function(value) { - return util.date.format(value, self.timestampFormat); - }; -} - -function StringShape() { - Shape.apply(this, arguments); - - var nullLessProtocols = ['rest-xml', 'query', 'ec2']; - this.toType = function(value) { - value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ? - value || '' : value; - if (this.isJsonValue) { - return JSON.parse(value); - } - - return value && typeof value.toString === 'function' ? - value.toString() : value; - }; - - this.toWireFormat = function(value) { - return this.isJsonValue ? JSON.stringify(value) : value; - }; -} - -function FloatShape() { - Shape.apply(this, arguments); - - this.toType = function(value) { - if (value === null || value === undefined) return null; - return parseFloat(value); - }; - this.toWireFormat = this.toType; -} - -function IntegerShape() { - Shape.apply(this, arguments); - - this.toType = function(value) { - if (value === null || value === undefined) return null; - return parseInt(value, 10); - }; - this.toWireFormat = this.toType; -} - -function BinaryShape() { - Shape.apply(this, arguments); - this.toType = function(value) { - var buf = util.base64.decode(value); - if (this.isSensitive && util.isNode() && typeof util.Buffer.alloc === 'function') { - /* Node.js can create a Buffer that is not isolated. - * i.e. buf.byteLength !== buf.buffer.byteLength - * This means that the sensitive data is accessible to anyone with access to buf.buffer. - * If this is the node shared Buffer, then other code within this process _could_ find this secret. - * Copy sensitive data to an isolated Buffer and zero the sensitive data. - * While this is safe to do here, copying this code somewhere else may produce unexpected results. - */ - var secureBuf = util.Buffer.alloc(buf.length, buf); - buf.fill(0); - buf = secureBuf; - } - return buf; - }; - this.toWireFormat = util.base64.encode; -} - -function Base64Shape() { - BinaryShape.apply(this, arguments); -} - -function BooleanShape() { - Shape.apply(this, arguments); - - this.toType = function(value) { - if (typeof value === 'boolean') return value; - if (value === null || value === undefined) return null; - return value === 'true'; - }; -} - -/** + */function hasCustomEndpoint(client){//if set endpoint is set for specific client, enable endpoint discovery will raise an error. +if(client._originalConfig&&client._originalConfig.endpoint&&client._originalConfig.endpointDiscoveryEnabled===true){throw util.error(new Error(),{code:'ConfigurationException',message:'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'});};var svcConfig=AWS.config[client.serviceIdentifier]||{};return Boolean(AWS.config.endpoint||svcConfig.endpoint||client._originalConfig&&client._originalConfig.endpoint);}/** * @api private - */ -Shape.shapes = { - StructureShape: StructureShape, - ListShape: ListShape, - MapShape: MapShape, - StringShape: StringShape, - BooleanShape: BooleanShape, - Base64Shape: Base64Shape -}; - -/** + */function isFalsy(value){return['false','0'].indexOf(value)>=0;}/** + * If endpoint discovery should perform for this request when endpoint discovery is optional. + * SDK performs config resolution in order like below: + * 1. If turned on client configuration(default to off) then turn on endpoint discovery. + * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery. + * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then + * turn on endpoint discovery. + * @param [object] request request object. * @api private - */ -module.exports = Shape; - -},{"../util":71,"./collection":39}],44:[function(require,module,exports){ -var AWS = require('./core'); - -/** + */function isEndpointDiscoveryApplicable(request){var service=request.service||{};if(service.config.endpointDiscoveryEnabled===true)return true;//shared ini file is only available in Node +//not to check env in browser +if(util.isBrowser())return false;for(var i=0;i 1) { - var msg = this.errors.join('\n* '); - msg = 'There were ' + this.errors.length + - ' validation errors:\n* ' + msg; - throw AWS.util.error(new Error(msg), - {code: 'MultipleValidationErrors', errors: this.errors}); - } else if (this.errors.length === 1) { - throw this.errors[0]; - } else { - return true; - } - }, - - fail: function fail(code, message) { - this.errors.push(AWS.util.error(new Error(message), {code: code})); - }, - - validateStructure: function validateStructure(shape, params, context) { - this.validateType(params, context, ['object'], 'structure'); - - var paramName; - for (var i = 0; shape.required && i < shape.required.length; i++) { - paramName = shape.required[i]; - var value = params[paramName]; - if (value === undefined || value === null) { - this.fail('MissingRequiredParameter', - 'Missing required key \'' + paramName + '\' in ' + context); - } - } - - // validate hash members - for (paramName in params) { - if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue; - - var paramValue = params[paramName], - memberShape = shape.members[paramName]; - - if (memberShape !== undefined) { - var memberContext = [context, paramName].join('.'); - this.validateMember(memberShape, paramValue, memberContext); - } else { - this.fail('UnexpectedParameter', - 'Unexpected key \'' + paramName + '\' found in ' + context); - } - } - - return true; - }, - - validateMember: function validateMember(shape, param, context) { - switch (shape.type) { - case 'structure': - return this.validateStructure(shape, param, context); - case 'list': - return this.validateList(shape, param, context); - case 'map': - return this.validateMap(shape, param, context); - default: - return this.validateScalar(shape, param, context); - } - }, - - validateList: function validateList(shape, params, context) { - if (this.validateType(params, context, [Array])) { - this.validateRange(shape, params.length, context, 'list member count'); - // validate array members - for (var i = 0; i < params.length; i++) { - this.validateMember(shape.member, params[i], context + '[' + i + ']'); - } - } - }, - - validateMap: function validateMap(shape, params, context) { - if (this.validateType(params, context, ['object'], 'map')) { - // Build up a count of map members to validate range traits. - var mapCount = 0; - for (var param in params) { - if (!Object.prototype.hasOwnProperty.call(params, param)) continue; - // Validate any map key trait constraints - this.validateMember(shape.key, param, - context + '[key=\'' + param + '\']'); - this.validateMember(shape.value, params[param], - context + '[\'' + param + '\']'); - mapCount++; - } - this.validateRange(shape, mapCount, context, 'map member count'); - } - }, - - validateScalar: function validateScalar(shape, value, context) { - switch (shape.type) { - case null: - case undefined: - case 'string': - return this.validateString(shape, value, context); - case 'base64': - case 'binary': - return this.validatePayload(value, context); - case 'integer': - case 'float': - return this.validateNumber(shape, value, context); - case 'boolean': - return this.validateType(value, context, ['boolean']); - case 'timestamp': - return this.validateType(value, context, [Date, - /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'], - 'Date object, ISO-8601 string, or a UNIX timestamp'); - default: - return this.fail('UnkownType', 'Unhandled type ' + - shape.type + ' for ' + context); - } - }, - - validateString: function validateString(shape, value, context) { - var validTypes = ['string']; - if (shape.isJsonValue) { - validTypes = validTypes.concat(['number', 'object', 'boolean']); - } - if (value !== null && this.validateType(value, context, validTypes)) { - this.validateEnum(shape, value, context); - this.validateRange(shape, value.length, context, 'string length'); - this.validatePattern(shape, value, context); - this.validateUri(shape, value, context); - } - }, - - validateUri: function validateUri(shape, value, context) { - if (shape['location'] === 'uri') { - if (value.length === 0) { - this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,' - + ' but found "' + value +'" for ' + context); - } - } - }, - - validatePattern: function validatePattern(shape, value, context) { - if (this.validation['pattern'] && shape['pattern'] !== undefined) { - if (!(new RegExp(shape['pattern'])).test(value)) { - this.fail('PatternMatchError', 'Provided value "' + value + '" ' - + 'does not match regex pattern /' + shape['pattern'] + '/ for ' - + context); - } - } - }, - - validateRange: function validateRange(shape, value, context, descriptor) { - if (this.validation['min']) { - if (shape['min'] !== undefined && value < shape['min']) { - this.fail('MinRangeError', 'Expected ' + descriptor + ' >= ' - + shape['min'] + ', but found ' + value + ' for ' + context); - } - } - if (this.validation['max']) { - if (shape['max'] !== undefined && value > shape['max']) { - this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= ' - + shape['max'] + ', but found ' + value + ' for ' + context); - } - } - }, - - validateEnum: function validateRange(shape, value, context) { - if (this.validation['enum'] && shape['enum'] !== undefined) { - // Fail if the string value is not present in the enum list - if (shape['enum'].indexOf(value) === -1) { - this.fail('EnumError', 'Found string value of ' + value + ', but ' - + 'expected ' + shape['enum'].join('|') + ' for ' + context); - } - } - }, - - validateType: function validateType(value, context, acceptedTypes, type) { - // We will not log an error for null or undefined, but we will return - // false so that callers know that the expected type was not strictly met. - if (value === null || value === undefined) return false; - - var foundInvalidType = false; - for (var i = 0; i < acceptedTypes.length; i++) { - if (typeof acceptedTypes[i] === 'string') { - if (typeof value === acceptedTypes[i]) return true; - } else if (acceptedTypes[i] instanceof RegExp) { - if ((value || '').toString().match(acceptedTypes[i])) return true; - } else { - if (value instanceof acceptedTypes[i]) return true; - if (AWS.util.isType(value, acceptedTypes[i])) return true; - if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice(); - acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]); - } - foundInvalidType = true; - } - - var acceptedType = type; - if (!acceptedType) { - acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1'); - } - - var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : ''; - this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' + - vowel + ' ' + acceptedType); - return false; - }, - - validateNumber: function validateNumber(shape, value, context) { - if (value === null || value === undefined) return; - if (typeof value === 'string') { - var castedValue = parseFloat(value); - if (castedValue.toString() === value) value = castedValue; - } - if (this.validateType(value, context, ['number'])) { - this.validateRange(shape, value, context, 'numeric value'); - } - }, - - validatePayload: function validatePayload(value, context) { - if (value === null || value === undefined) return; - if (typeof value === 'string') return; - if (value && typeof value.byteLength === 'number') return; // typed arrays - if (AWS.util.isNode()) { // special check for buffer/stream in Node.js - var Stream = AWS.util.stream.Stream; - if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return; - } else { - if (typeof Blob !== void 0 && value instanceof Blob) return; - } - - var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView']; - if (value) { - for (var i = 0; i < types.length; i++) { - if (AWS.util.isType(value, types[i])) return; - if (AWS.util.typeName(value.constructor) === types[i]) return; - } - } - - this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' + - 'string, Buffer, Stream, Blob, or typed array object'); - } -}); - -},{"./core":18}],45:[function(require,module,exports){ -var util = require('../util'); -var AWS = require('../core'); - -/** - * Prepend prefix defined by API model to endpoint that's already - * constructed. This feature does not apply to operations using - * endpoint discovery and can be disabled. + */function discoverEndpoint(request,done){var service=request.service||{};if(hasCustomEndpoint(service)||request.isPresigned())return done();if(!isEndpointDiscoveryApplicable(request))return done();request.httpRequest.appendToUserAgent('endpoint-discovery');var operations=service.api.operations||{};var operationModel=operations[request.operation];var isEndpointDiscoveryRequired=operationModel?operationModel.endpointDiscoveryRequired:'NULL';switch(isEndpointDiscoveryRequired){case'OPTIONAL':optionalDiscoverEndpoint(request);request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS','extractError',invalidateCachedEndpoints);done();break;case'REQUIRED':request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS','extractError',invalidateCachedEndpoints);requiredDiscoverEndpoint(request,done);break;case'NULL':default:done();break;}}module.exports={discoverEndpoint:discoverEndpoint,requiredDiscoverEndpoint:requiredDiscoverEndpoint,optionalDiscoverEndpoint:optionalDiscoverEndpoint,marshallCustomIdentifiers:marshallCustomIdentifiers,getCacheKey:getCacheKey,invalidateCachedEndpoint:invalidateCachedEndpoints};}).call(this);}).call(this,require('_process'));},{"./core":18,"./util":71,"_process":86}],27:[function(require,module,exports){var eventMessageChunker=require('../event-stream/event-message-chunker').eventMessageChunker;var parseEvent=require('./parse-event').parseEvent;function createEventStream(body,parser,model){var eventMessages=eventMessageChunker(body);var events=[];for(var i=0;i 63) { - throw util.error(new Error(), { - code: 'ValidationError', - message: 'Hostname label length should be between 1 to 63 characters, inclusive.' - }); - } - if (!hostPattern.test(label)) { - throw AWS.util.error(new Error(), - {code: 'ValidationError', message: label + ' is not hostname compatible.'}); - } - }); -} - -module.exports = { - populateHostPrefix: populateHostPrefix -}; - -},{"../core":18,"../util":71}],46:[function(require,module,exports){ -var util = require('../util'); -var JsonBuilder = require('../json/builder'); -var JsonParser = require('../json/parser'); -var populateHostPrefix = require('./helpers').populateHostPrefix; - -function buildRequest(req) { - var httpRequest = req.httpRequest; - var api = req.service.api; - var target = api.targetPrefix + '.' + api.operations[req.operation].name; - var version = api.jsonVersion || '1.0'; - var input = api.operations[req.operation].input; - var builder = new JsonBuilder(); - - if (version === 1) version = '1.0'; - httpRequest.body = builder.build(req.params || {}, input); - httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version; - httpRequest.headers['X-Amz-Target'] = target; - - populateHostPrefix(req); -} - -function extractError(resp) { - var error = {}; - var httpResponse = resp.httpResponse; - - error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError'; - if (typeof error.code === 'string') { - error.code = error.code.split(':')[0]; - } - - if (httpResponse.body.length > 0) { - try { - var e = JSON.parse(httpResponse.body.toString()); - if (e.__type || e.code) { - error.code = (e.__type || e.code).split('#').pop(); - } - if (error.code === 'RequestEntityTooLarge') { - error.message = 'Request body must be less than 1 MB'; - } else { - error.message = (e.message || e.Message || null); - } - } catch (e) { - error.statusCode = httpResponse.statusCode; - error.message = httpResponse.statusMessage; - } - } else { - error.statusCode = httpResponse.statusCode; - error.message = httpResponse.statusCode.toString(); - } - - resp.error = util.error(new Error(), error); -} - -function extractData(resp) { - var body = resp.httpResponse.body.toString() || '{}'; - if (resp.request.service.config.convertResponseTypes === false) { - resp.data = JSON.parse(body); - } else { - var operation = resp.request.service.api.operations[resp.request.operation]; - var shape = operation.output || {}; - var parser = new JsonParser(); - resp.data = parser.parse(body, shape); - } -} - -/** + */Int64.fromNumber=function(number){if(number>9223372036854775807||number<-9223372036854775808){throw new Error(number+' is too large (or, if negative, too small) to represent as an Int64');}var bytes=new Uint8Array(8);for(var i=7,remaining=Math.abs(Math.round(number));i>-1&&remaining>0;i--,remaining/=256){bytes[i]=remaining;}if(number<0){negate(bytes);}return new Int64(bytes);};/** + * @returns {number} + * * @api private - */ -module.exports = { - buildRequest: buildRequest, - extractError: extractError, - extractData: extractData -}; - -},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(require,module,exports){ -var AWS = require('../core'); -var util = require('../util'); -var QueryParamSerializer = require('../query/query_param_serializer'); -var Shape = require('../model/shape'); -var populateHostPrefix = require('./helpers').populateHostPrefix; - -function buildRequest(req) { - var operation = req.service.api.operations[req.operation]; - var httpRequest = req.httpRequest; - httpRequest.headers['Content-Type'] = - 'application/x-www-form-urlencoded; charset=utf-8'; - httpRequest.params = { - Version: req.service.api.apiVersion, - Action: operation.name - }; - - // convert the request parameters into a list of query params, - // e.g. Deeply.NestedParam.0.Name=value - var builder = new QueryParamSerializer(); - builder.serialize(req.params, operation.input, function(name, value) { - httpRequest.params[name] = value; - }); - httpRequest.body = util.queryParamsToString(httpRequest.params); - - populateHostPrefix(req); -} - -function extractError(resp) { - var data, body = resp.httpResponse.body.toString(); - if (body.match('= 0 ? '&' : '?'); - var parts = []; - util.arrayEach(Object.keys(queryString).sort(), function(key) { - if (!Array.isArray(queryString[key])) { - queryString[key] = [queryString[key]]; - } - for (var i = 0; i < queryString[key].length; i++) { - parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]); - } - }); - uri += parts.join('&'); - } - - return uri; -} - -function populateURI(req) { - var operation = req.service.api.operations[req.operation]; - var input = operation.input; - - var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params); - req.httpRequest.path = uri; -} - -function populateHeaders(req) { - var operation = req.service.api.operations[req.operation]; - util.each(operation.input.members, function (name, member) { - var value = req.params[name]; - if (value === null || value === undefined) return; - - if (member.location === 'headers' && member.type === 'map') { - util.each(value, function(key, memberValue) { - req.httpRequest.headers[member.name + key] = memberValue; - }); - } else if (member.location === 'header') { - value = member.toWireFormat(value).toString(); - if (member.isJsonValue) { - value = util.base64.encode(value); - } - req.httpRequest.headers[member.name] = value; - } - }); -} - -function buildRequest(req) { - populateMethod(req); - populateURI(req); - populateHeaders(req); - populateHostPrefix(req); -} - -function extractError() { -} - -function extractData(resp) { - var req = resp.request; - var data = {}; - var r = resp.httpResponse; - var operation = req.service.api.operations[req.operation]; - var output = operation.output; - - // normalize headers names to lower-cased keys for matching - var headers = {}; - util.each(r.headers, function (k, v) { - headers[k.toLowerCase()] = v; - }); - - util.each(output.members, function(name, member) { - var header = (member.name || name).toLowerCase(); - if (member.location === 'headers' && member.type === 'map') { - data[name] = {}; - var location = member.isLocationName ? member.name : ''; - var pattern = new RegExp('^' + location + '(.+)', 'i'); - util.each(r.headers, function (k, v) { - var result = k.match(pattern); - if (result !== null) { - data[name][result[1]] = v; - } - }); - } else if (member.location === 'header') { - if (headers[header] !== undefined) { - var value = member.isJsonValue ? - util.base64.decode(headers[header]) : - headers[header]; - data[name] = member.toType(value); - } - } else if (member.location === 'statusCode') { - data[name] = parseInt(r.statusCode, 10); - } - }); - - resp.data = data; -} - -/** + */function negate(bytes){for(var i=0;i<8;i++){bytes[i]^=0xFF;}for(var i=7;i>-1;i--){bytes[i]++;if(bytes[i]!==0){break;}}}/** * @api private - */ -module.exports = { - buildRequest: buildRequest, - extractError: extractError, - extractData: extractData, - generateURI: generateURI -}; - -},{"../util":71,"./helpers":45}],49:[function(require,module,exports){ -var util = require('../util'); -var Rest = require('./rest'); -var Json = require('./json'); -var JsonBuilder = require('../json/builder'); -var JsonParser = require('../json/parser'); - -function populateBody(req) { - var builder = new JsonBuilder(); - var input = req.service.api.operations[req.operation].input; - - if (input.payload) { - var params = {}; - var payloadShape = input.members[input.payload]; - params = req.params[input.payload]; - if (params === undefined) return; - - if (payloadShape.type === 'structure') { - req.httpRequest.body = builder.build(params, payloadShape); - applyContentTypeHeader(req); - } else { // non-JSON payload - req.httpRequest.body = params; - if (payloadShape.type === 'binary' || payloadShape.isStreaming) { - applyContentTypeHeader(req, true); - } - } - } else { - var body = builder.build(req.params, input); - if (body !== '{}' || req.httpRequest.method !== 'GET') { //don't send empty body for GET method - req.httpRequest.body = body; - } - applyContentTypeHeader(req); - } -} - -function applyContentTypeHeader(req, isBinary) { - var operation = req.service.api.operations[req.operation]; - var input = operation.input; - - if (!req.httpRequest.headers['Content-Type']) { - var type = isBinary ? 'binary/octet-stream' : 'application/json'; - req.httpRequest.headers['Content-Type'] = type; - } -} - -function buildRequest(req) { - Rest.buildRequest(req); - - // never send body payload on HEAD/DELETE - if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { - populateBody(req); - } -} - -function extractError(resp) { - Json.extractError(resp); -} - -function extractData(resp) { - Rest.extractData(resp); - - var req = resp.request; - var operation = req.service.api.operations[req.operation]; - var rules = req.service.api.operations[req.operation].output || {}; - var parser; - var hasEventOutput = operation.hasEventOutput; - - if (rules.payload) { - var payloadMember = rules.members[rules.payload]; - var body = resp.httpResponse.body; - if (payloadMember.isEventStream) { - parser = new JsonParser(); - resp.data[payload] = util.createEventStream( - AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : body, - parser, - payloadMember - ); - } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') { - var parser = new JsonParser(); - resp.data[rules.payload] = parser.parse(body, payloadMember); - } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) { - resp.data[rules.payload] = body; - } else { - resp.data[rules.payload] = payloadMember.toType(body); - } - } else { - var data = resp.data; - Json.extractData(resp); - resp.data = util.merge(data, resp.data); - } -} - -/** + */module.exports={Int64:Int64};},{"../core":18}],30:[function(require,module,exports){var parseMessage=require('./parse-message').parseMessage;/** + * + * @param {*} parser + * @param {Buffer} message + * @param {*} shape * @api private - */ -module.exports = { - buildRequest: buildRequest, - extractError: extractError, - extractData: extractData -}; - -},{"../json/builder":36,"../json/parser":37,"../util":71,"./json":46,"./rest":48}],50:[function(require,module,exports){ -var AWS = require('../core'); -var util = require('../util'); -var Rest = require('./rest'); - -function populateBody(req) { - var input = req.service.api.operations[req.operation].input; - var builder = new AWS.XML.Builder(); - var params = req.params; - - var payload = input.payload; - if (payload) { - var payloadMember = input.members[payload]; - params = params[payload]; - if (params === undefined) return; - - if (payloadMember.type === 'structure') { - var rootElement = payloadMember.name; - req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true); - } else { // non-xml payload - req.httpRequest.body = params; - } - } else { - req.httpRequest.body = builder.toXML(params, input, input.name || - input.shape || util.string.upperFirst(req.operation) + 'Request'); - } -} - -function buildRequest(req) { - Rest.buildRequest(req); - - // never send body payload on GET/HEAD - if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) { - populateBody(req); - } -} - -function extractError(resp) { - Rest.extractError(resp); - - var data; - try { - data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString()); - } catch (e) { - data = { - Code: resp.httpResponse.statusCode, - Message: resp.httpResponse.statusMessage - }; - } - - if (data.Errors) data = data.Errors; - if (data.Error) data = data.Error; - if (data.Code) { - resp.error = util.error(new Error(), { - code: data.Code, - message: data.Message - }); - } else { - resp.error = util.error(new Error(), { - code: resp.httpResponse.statusCode, - message: null - }); - } -} - -function extractData(resp) { - Rest.extractData(resp); - - var parser; - var req = resp.request; - var body = resp.httpResponse.body; - var operation = req.service.api.operations[req.operation]; - var output = operation.output; - - var hasEventOutput = operation.hasEventOutput; - - var payload = output.payload; - if (payload) { - var payloadMember = output.members[payload]; - if (payloadMember.isEventStream) { - parser = new AWS.XML.Parser(); - resp.data[payload] = util.createEventStream( - AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : resp.httpResponse.body, - parser, - payloadMember - ); - } else if (payloadMember.type === 'structure') { - parser = new AWS.XML.Parser(); - resp.data[payload] = parser.parse(body.toString(), payloadMember); - } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) { - resp.data[payload] = body; - } else { - resp.data[payload] = payloadMember.toType(body); - } - } else if (body.length > 0) { - parser = new AWS.XML.Parser(); - var data = parser.parse(body.toString(), output); - util.update(resp.data, data); - } -} - -/** + */function parseEvent(parser,message,shape){var parsedMessage=parseMessage(message);// check if message is an event or error +var messageType=parsedMessage.headers[':message-type'];if(messageType){if(messageType.value==='error'){throw parseError(parsedMessage);}else if(messageType.value!=='event'){// not sure how to parse non-events/non-errors, ignore for now +return;}}// determine event type +var eventType=parsedMessage.headers[':event-type'];// check that the event type is modeled +var eventModel=shape.members[eventType.value];if(!eventModel){return;}var result={};// check if an event payload exists +var eventPayloadMemberName=eventModel.eventPayloadMemberName;if(eventPayloadMemberName){var payloadShape=eventModel.members[eventPayloadMemberName];// if the shape is binary, return the byte array +if(payloadShape.type==='binary'){result[eventPayloadMemberName]=parsedMessage.body;}else{result[eventPayloadMemberName]=parser.parse(parsedMessage.body.toString(),payloadShape);}}// read event headers +var eventHeaderNames=eventModel.eventHeaderMemberNames;for(var i=0;i=0){req.httpRequest.headers['X-Amz-Content-Sha256']='UNSIGNED-PAYLOAD';return done();}AWS.util.computeSha256(body,function(err,sha){if(err){done(err);}else{req.httpRequest.headers['X-Amz-Content-Sha256']=sha;done();}});}else{done();}});add('SET_CONTENT_LENGTH','afterBuild',function SET_CONTENT_LENGTH(req){var authtype=getOperationAuthtype(req);var payloadMember=AWS.util.getRequestPayloadShape(req);if(req.httpRequest.headers['Content-Length']===undefined){try{var length=AWS.util.string.byteLength(req.httpRequest.body);req.httpRequest.headers['Content-Length']=length;}catch(err){if(payloadMember&&payloadMember.isStreaming){if(payloadMember.requiresLength){//streaming payload requires length(s3, glacier) +throw err;}else if(authtype.indexOf('unsigned-body')>=0){//unbounded streaming payload(lex, mediastore) +req.httpRequest.headers['Transfer-Encoding']='chunked';return;}else{throw err;}}throw err;}}});add('SET_HTTP_HOST','afterBuild',function SET_HTTP_HOST(req){req.httpRequest.headers['Host']=req.httpRequest.endpoint.host;});add('RESTART','restart',function RESTART(){var err=this.response.error;if(!err||!err.retryable)return;this.httpRequest=new AWS.HttpRequest(this.service.endpoint,this.service.region);if(this.response.retryCount=60*10){// if we signed 10min ago, re-sign +this.emit('sign',[this],function(err){if(err)done(err);else executeSend();});}else{executeSend();}});add('HTTP_HEADERS','httpHeaders',function HTTP_HEADERS(statusCode,headers,resp,statusMessage){resp.httpResponse.statusCode=statusCode;resp.httpResponse.statusMessage=statusMessage;resp.httpResponse.headers=headers;resp.httpResponse.body=AWS.util.buffer.toBuffer('');resp.httpResponse.buffers=[];resp.httpResponse.numBytes=0;var dateHeader=headers.date||headers.Date;var service=resp.request.service;if(dateHeader){var serverTime=Date.parse(dateHeader);if(service.config.correctClockSkew&&service.isClockSkewed(serverTime)){service.applyClockOffset(serverTime);}}});add('HTTP_DATA','httpData',function HTTP_DATA(chunk,resp){if(chunk){if(AWS.util.isNode()){resp.httpResponse.numBytes+=chunk.length;var total=resp.httpResponse.headers['content-length'];var progress={loaded:resp.httpResponse.numBytes,total:total};resp.request.emit('httpDownloadProgress',[progress,resp]);}resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk));}});add('HTTP_DONE','httpDone',function HTTP_DONE(resp){// convert buffers array into single buffer +if(resp.httpResponse.buffers&&resp.httpResponse.buffers.length>0){var body=AWS.util.buffer.concat(resp.httpResponse.buffers);resp.httpResponse.body=body;}delete resp.httpResponse.numBytes;delete resp.httpResponse.buffers;});add('FINALIZE_ERROR','retry',function FINALIZE_ERROR(resp){if(resp.httpResponse.statusCode){resp.error.statusCode=resp.httpResponse.statusCode;if(resp.error.retryable===undefined){resp.error.retryable=this.service.retryableError(resp.error,this);}}});add('INVALIDATE_CREDENTIALS','retry',function INVALIDATE_CREDENTIALS(resp){if(!resp.error)return;switch(resp.error.code){case'RequestExpired':// EC2 only +case'ExpiredTokenException':case'ExpiredToken':resp.error.retryable=true;resp.request.service.config.credentials.expired=true;}});add('EXPIRED_SIGNATURE','retry',function EXPIRED_SIGNATURE(resp){var err=resp.error;if(!err)return;if(typeof err.code==='string'&&typeof err.message==='string'){if(err.code.match(/Signature/)&&err.message.match(/expired/)){resp.error.retryable=true;}}});add('CLOCK_SKEWED','retry',function CLOCK_SKEWED(resp){if(!resp.error)return;if(this.service.clockSkewError(resp.error)&&this.service.config.correctClockSkew){resp.error.retryable=true;}});add('REDIRECT','retry',function REDIRECT(resp){if(resp.error&&resp.error.statusCode>=300&&resp.error.statusCode<400&&resp.httpResponse.headers['location']){this.httpRequest.endpoint=new AWS.Endpoint(resp.httpResponse.headers['location']);this.httpRequest.headers['Host']=this.httpRequest.endpoint.host;resp.error.redirect=true;resp.error.retryable=true;}});add('RETRY_CHECK','retry',function RETRY_CHECK(resp){if(resp.error){if(resp.error.redirect&&resp.redirectCount] + * a map of header keys and their respective values + * @!attribute body + * @return [String] the request body payload + * @!attribute endpoint + * @return [AWS.Endpoint] the endpoint for the request + * @!attribute region + * @api private + * @return [String] the region, for signing purposes only. + */AWS.HttpRequest=inherit({/** + * @api private + */constructor:function HttpRequest(endpoint,region){endpoint=new AWS.Endpoint(endpoint);this.method='POST';this.path=endpoint.path||'/';this.headers={};this.body='';this.endpoint=endpoint;this.region=region;this._userAgent='';this.setUserAgent();},/** + * @api private + */setUserAgent:function setUserAgent(){this._userAgent=this.headers[this.getUserAgentHeaderName()]=AWS.util.userAgent();},getUserAgentHeaderName:function getUserAgentHeaderName(){var prefix=AWS.util.isBrowser()?'X-Amz-':'';return prefix+'User-Agent';},/** + * @api private + */appendToUserAgent:function appendToUserAgent(agentPartial){if(typeof agentPartial==='string'&&agentPartial){this._userAgent+=' '+agentPartial;}this.headers[this.getUserAgentHeaderName()]=this._userAgent;},/** + * @api private + */getUserAgent:function getUserAgent(){return this._userAgent;},/** + * @return [String] the part of the {path} excluding the + * query string + */pathname:function pathname(){return this.path.split('?',1)[0];},/** + * @return [String] the query string portion of the {path} + */search:function search(){var query=this.path.split('?',2)[1];if(query){query=AWS.util.queryStringParse(query);return AWS.util.queryParamsToString(query);}return'';},/** + * @api private + * update httpRequest endpoint with endpoint string + */updateEndpoint:function updateEndpoint(endpointStr){var newEndpoint=new AWS.Endpoint(endpointStr);this.endpoint=newEndpoint;this.path=newEndpoint.path||'/';}});/** + * The low level HTTP response object, encapsulating all HTTP header + * and body data returned from the request. + * + * @!attribute statusCode + * @return [Integer] the HTTP status code of the response (e.g., 200, 404) + * @!attribute headers + * @return [map] + * a map of response header keys and their respective values + * @!attribute body + * @return [String] the response body payload + * @!attribute [r] streaming + * @return [Boolean] whether this response is being streamed at a low-level. + * Defaults to `false` (buffered reads). Do not modify this manually, use + * {createUnbufferedStream} to convert the stream to unbuffered mode + * instead. + */AWS.HttpResponse=inherit({/** + * @api private + */constructor:function HttpResponse(){this.statusCode=undefined;this.headers={};this.body=undefined;this.streaming=false;this.stream=null;},/** + * Disables buffering on the HTTP response and returns the stream for reading. + * @return [Stream, XMLHttpRequest, null] the underlying stream object. + * Use this object to directly read data off of the stream. + * @note This object is only available after the {AWS.Request~httpHeaders} + * event has fired. This method must be called prior to + * {AWS.Request~httpData}. + * @example Taking control of a stream + * request.on('httpHeaders', function(statusCode, headers) { + * if (statusCode < 300) { + * if (headers.etag === 'xyz') { + * // pipe the stream, disabling buffering + * var stream = this.response.httpResponse.createUnbufferedStream(); + * stream.pipe(process.stdout); + * } else { // abort this request and set a better error message + * this.abort(); + * this.response.error = new Error('Invalid ETag'); + * } + * } + * }).send(console.log); + */createUnbufferedStream:function createUnbufferedStream(){this.streaming=true;return this.stream;}});AWS.HttpClient=inherit({});/** + * @api private + */AWS.HttpClient.getInstance=function getInstance(){if(this.singleton===undefined){this.singleton=new this();}return this.singleton;};},{"./core":18}],35:[function(require,module,exports){var AWS=require('../core');var EventEmitter=require('events').EventEmitter;require('../http');/** + * @api private + */AWS.XHRClient=AWS.util.inherit({handleRequest:function handleRequest(httpRequest,httpOptions,callback,errCallback){var self=this;var endpoint=httpRequest.endpoint;var emitter=new EventEmitter();var href=endpoint.protocol+'//'+endpoint.hostname;if(endpoint.port!==80&&endpoint.port!==443){href+=':'+endpoint.port;}href+=httpRequest.path;var xhr=new XMLHttpRequest(),headersEmitted=false;httpRequest.stream=xhr;xhr.addEventListener('readystatechange',function(){try{if(xhr.status===0)return;// 0 code is invalid +}catch(e){return;}if(this.readyState>=this.HEADERS_RECEIVED&&!headersEmitted){emitter.statusCode=xhr.status;emitter.headers=self.parseHeaders(xhr.getAllResponseHeaders());emitter.emit('headers',emitter.statusCode,emitter.headers,xhr.statusText);headersEmitted=true;}if(this.readyState===this.DONE){self.finishRequest(xhr,emitter);}},false);xhr.upload.addEventListener('progress',function(evt){emitter.emit('sendProgress',evt);});xhr.addEventListener('progress',function(evt){emitter.emit('receiveProgress',evt);},false);xhr.addEventListener('timeout',function(){errCallback(AWS.util.error(new Error('Timeout'),{code:'TimeoutError'}));},false);xhr.addEventListener('error',function(){errCallback(AWS.util.error(new Error('Network Failure'),{code:'NetworkingError'}));},false);xhr.addEventListener('abort',function(){errCallback(AWS.util.error(new Error('Request aborted'),{code:'RequestAbortedError'}));},false);callback(emitter);xhr.open(httpRequest.method,href,httpOptions.xhrAsync!==false);AWS.util.each(httpRequest.headers,function(key,value){if(key!=='Content-Length'&&key!=='User-Agent'&&key!=='Host'){xhr.setRequestHeader(key,value);}});if(httpOptions.timeout&&httpOptions.xhrAsync!==false){xhr.timeout=httpOptions.timeout;}if(httpOptions.xhrWithCredentials){xhr.withCredentials=true;}try{xhr.responseType='arraybuffer';}catch(e){}try{if(httpRequest.body){xhr.send(httpRequest.body);}else{xhr.send();}}catch(err){if(httpRequest.body&&_typeof(httpRequest.body.buffer)==='object'){xhr.send(httpRequest.body.buffer);// send ArrayBuffer directly +}else{throw err;}}return emitter;},parseHeaders:function parseHeaders(rawHeaders){var headers={};AWS.util.arrayEach(rawHeaders.split(/\r?\n/),function(line){var key=line.split(':',1)[0];var value=line.substring(key.length+2);if(key.length>0)headers[key.toLowerCase()]=value;});return headers;},finishRequest:function finishRequest(xhr,emitter){var buffer;if(xhr.responseType==='arraybuffer'&&xhr.response){var ab=xhr.response;buffer=new AWS.util.Buffer(ab.byteLength);var view=new Uint8Array(ab);for(var i=0;i-1?value||'':value;if(this.isJsonValue){return JSON.parse(value);}return value&&typeof value.toString==='function'?value.toString():value;};this.toWireFormat=function(value){return this.isJsonValue?JSON.stringify(value):value;};}function FloatShape(){Shape.apply(this,arguments);this.toType=function(value){if(value===null||value===undefined)return null;return parseFloat(value);};this.toWireFormat=this.toType;}function IntegerShape(){Shape.apply(this,arguments);this.toType=function(value){if(value===null||value===undefined)return null;return parseInt(value,10);};this.toWireFormat=this.toType;}function BinaryShape(){Shape.apply(this,arguments);this.toType=function(value){var buf=util.base64.decode(value);if(this.isSensitive&&util.isNode()&&typeof util.Buffer.alloc==='function'){/* Node.js can create a Buffer that is not isolated. + * i.e. buf.byteLength !== buf.buffer.byteLength + * This means that the sensitive data is accessible to anyone with access to buf.buffer. + * If this is the node shared Buffer, then other code within this process _could_ find this secret. + * Copy sensitive data to an isolated Buffer and zero the sensitive data. + * While this is safe to do here, copying this code somewhere else may produce unexpected results. + */var secureBuf=util.Buffer.alloc(buf.length,buf);buf.fill(0);buf=secureBuf;}return buf;};this.toWireFormat=util.base64.encode;}function Base64Shape(){BinaryShape.apply(this,arguments);}function BooleanShape(){Shape.apply(this,arguments);this.toType=function(value){if(typeof value==='boolean')return value;if(value===null||value===undefined)return null;return value==='true';};}/** + * @api private + */Shape.shapes={StructureShape:StructureShape,ListShape:ListShape,MapShape:MapShape,StringShape:StringShape,BooleanShape:BooleanShape,Base64Shape:Base64Shape};/** + * @api private + */module.exports=Shape;},{"../util":71,"./collection":39}],44:[function(require,module,exports){var AWS=require('./core');/** + * @api private + */AWS.ParamValidator=AWS.util.inherit({/** + * Create a new validator object. + * + * @param validation [Boolean|map] whether input parameters should be + * validated against the operation description before sending the + * request. Pass a map to enable any of the following specific + * validation features: + * + * * **min** [Boolean] — Validates that a value meets the min + * constraint. This is enabled by default when paramValidation is set + * to `true`. + * * **max** [Boolean] — Validates that a value meets the max + * constraint. + * * **pattern** [Boolean] — Validates that a string value matches a + * regular expression. + * * **enum** [Boolean] — Validates that a string value matches one + * of the allowable enum values. + */constructor:function ParamValidator(validation){if(validation===true||validation===undefined){validation={'min':true};}this.validation=validation;},validate:function validate(shape,params,context){this.errors=[];this.validateMember(shape,params||{},context||'params');if(this.errors.length>1){var msg=this.errors.join('\n* ');msg='There were '+this.errors.length+' validation errors:\n* '+msg;throw AWS.util.error(new Error(msg),{code:'MultipleValidationErrors',errors:this.errors});}else if(this.errors.length===1){throw this.errors[0];}else{return true;}},fail:function fail(code,message){this.errors.push(AWS.util.error(new Error(message),{code:code}));},validateStructure:function validateStructure(shape,params,context){this.validateType(params,context,['object'],'structure');var paramName;for(var i=0;shape.required&&i= 1,'+' but found "'+value+'" for '+context);}}},validatePattern:function validatePattern(shape,value,context){if(this.validation['pattern']&&shape['pattern']!==undefined){if(!new RegExp(shape['pattern']).test(value)){this.fail('PatternMatchError','Provided value "'+value+'" '+'does not match regex pattern /'+shape['pattern']+'/ for '+context);}}},validateRange:function validateRange(shape,value,context,descriptor){if(this.validation['min']){if(shape['min']!==undefined&&value= '+shape['min']+', but found '+value+' for '+context);}}if(this.validation['max']){if(shape['max']!==undefined&&value>shape['max']){this.fail('MaxRangeError','Expected '+descriptor+' <= '+shape['max']+', but found '+value+' for '+context);}}},validateEnum:function validateRange(shape,value,context){if(this.validation['enum']&&shape['enum']!==undefined){// Fail if the string value is not present in the enum list +if(shape['enum'].indexOf(value)===-1){this.fail('EnumError','Found string value of '+value+', but '+'expected '+shape['enum'].join('|')+' for '+context);}}},validateType:function validateType(value,context,acceptedTypes,type){// We will not log an error for null or undefined, but we will return +// false so that callers know that the expected type was not strictly met. +if(value===null||value===undefined)return false;var foundInvalidType=false;for(var i=0;i63){throw util.error(new Error(),{code:'ValidationError',message:'Hostname label length should be between 1 to 63 characters, inclusive.'});}if(!hostPattern.test(label)){throw AWS.util.error(new Error(),{code:'ValidationError',message:label+' is not hostname compatible.'});}});}module.exports={populateHostPrefix:populateHostPrefix};},{"../core":18,"../util":71}],46:[function(require,module,exports){var util=require('../util');var JsonBuilder=require('../json/builder');var JsonParser=require('../json/parser');var populateHostPrefix=require('./helpers').populateHostPrefix;function buildRequest(req){var httpRequest=req.httpRequest;var api=req.service.api;var target=api.targetPrefix+'.'+api.operations[req.operation].name;var version=api.jsonVersion||'1.0';var input=api.operations[req.operation].input;var builder=new JsonBuilder();if(version===1)version='1.0';httpRequest.body=builder.build(req.params||{},input);httpRequest.headers['Content-Type']='application/x-amz-json-'+version;httpRequest.headers['X-Amz-Target']=target;populateHostPrefix(req);}function extractError(resp){var error={};var httpResponse=resp.httpResponse;error.code=httpResponse.headers['x-amzn-errortype']||'UnknownError';if(typeof error.code==='string'){error.code=error.code.split(':')[0];}if(httpResponse.body.length>0){try{var e=JSON.parse(httpResponse.body.toString());if(e.__type||e.code){error.code=(e.__type||e.code).split('#').pop();}if(error.code==='RequestEntityTooLarge'){error.message='Request body must be less than 1 MB';}else{error.message=e.message||e.Message||null;}}catch(e){error.statusCode=httpResponse.statusCode;error.message=httpResponse.statusMessage;}}else{error.statusCode=httpResponse.statusCode;error.message=httpResponse.statusCode.toString();}resp.error=util.error(new Error(),error);}function extractData(resp){var body=resp.httpResponse.body.toString()||'{}';if(resp.request.service.config.convertResponseTypes===false){resp.data=JSON.parse(body);}else{var operation=resp.request.service.api.operations[resp.request.operation];var shape=operation.output||{};var parser=new JsonParser();resp.data=parser.parse(body,shape);}}/** + * @api private + */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(require,module,exports){var AWS=require('../core');var util=require('../util');var QueryParamSerializer=require('../query/query_param_serializer');var Shape=require('../model/shape');var populateHostPrefix=require('./helpers').populateHostPrefix;function buildRequest(req){var operation=req.service.api.operations[req.operation];var httpRequest=req.httpRequest;httpRequest.headers['Content-Type']='application/x-www-form-urlencoded; charset=utf-8';httpRequest.params={Version:req.service.api.apiVersion,Action:operation.name};// convert the request parameters into a list of query params, +// e.g. Deeply.NestedParam.0.Name=value +var builder=new QueryParamSerializer();builder.serialize(req.params,operation.input,function(name,value){httpRequest.params[name]=value;});httpRequest.body=util.queryParamsToString(httpRequest.params);populateHostPrefix(req);}function extractError(resp){var data,body=resp.httpResponse.body.toString();if(body.match('=0?'&':'?';var parts=[];util.arrayEach(Object.keys(queryString).sort(),function(key){if(!Array.isArray(queryString[key])){queryString[key]=[queryString[key]];}for(var i=0;i0){parser=new AWS.XML.Parser();var data=parser.parse(body.toString(),output);util.update(resp.data,data);}}/** + * @api private + */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../core":18,"../util":71,"./rest":48}],51:[function(require,module,exports){var util=require('../util');function QueryParamSerializer(){}QueryParamSerializer.prototype.serialize=function(params,shape,fn){serializeStructure('',params,shape,fn);};function ucfirst(shape){if(shape.isQueryName||shape.api.protocol!=='ec2'){return shape.name;}else{return shape.name[0].toUpperCase()+shape.name.substr(1);}}function serializeStructure(prefix,struct,rules,fn){util.each(rules.members,function(name,member){var value=struct[name];if(value===null||value===undefined)return;var memberName=ucfirst(member);memberName=prefix?prefix+'.'+memberName:memberName;serializeMember(memberName,value,member,fn);});}function serializeMap(name,map,rules,fn){var i=1;util.each(map,function(key,value){var prefix=rules.flattened?'.':'.entry.';var position=prefix+i++ +'.';var keyName=position+(rules.key.name||'key');var valueName=position+(rules.value.name||'value');serializeMember(name+keyName,key,rules.key,fn);serializeMember(name+valueName,value,rules.value,fn);});}function serializeList(name,list,rules,fn){var memberRules=rules.member||{};if(list.length===0){fn.call(this,name,null);return;}util.arrayEach(list,function(v,n){var suffix='.'+(n+1);if(rules.api.protocol==='ec2'){// Do nothing for EC2 +suffix=suffix+'';// make linter happy +}else if(rules.flattened){if(memberRules.name){var parts=name.split('.');parts.pop();parts.push(ucfirst(memberRules));name=parts.join('.');}}else{suffix='.'+(memberRules.name?memberRules.name:'member')+suffix;}serializeMember(name+suffix,v,memberRules,fn);});}function serializeMember(name,value,rules,fn){if(value===null||value===undefined)return;if(rules.type==='structure'){serializeStructure(name,value,rules,fn);}else if(rules.type==='list'){serializeList(name,value,rules,fn);}else if(rules.type==='map'){serializeMap(name,value,rules,fn);}else{fn(name,rules.toWireFormat(value).toString());}}/** + * @api private + */module.exports=QueryParamSerializer;},{"../util":71}],52:[function(require,module,exports){module.exports={//provide realtime clock for performance measurement +now:function now(){if(typeof performance!=='undefined'&&typeof performance.now==='function'){return performance.now();}return Date.now();}};},{}],53:[function(require,module,exports){var util=require('./util');var regionConfig=require('./region_config_data.json');function generateRegionPrefix(region){if(!region)return null;var parts=region.split('-');if(parts.length<3)return null;return parts.slice(0,parts.length-2).join('-')+'-*';}function derivedKeys(service){var region=service.config.region;var regionPrefix=generateRegionPrefix(region);var endpointPrefix=service.api.endpointPrefix;return[[region,endpointPrefix],[regionPrefix,endpointPrefix],[region,'*'],[regionPrefix,'*'],['*',endpointPrefix],['*','*']].map(function(item){return item[0]&&item[1]?item.join('/'):null;});}function applyConfig(service,config){util.each(config,function(key,value){if(key==='globalEndpoint')return;if(service.config[key]===undefined||service.config[key]===null){service.config[key]=value;}});}function configureEndpoint(service){var keys=derivedKeys(service);for(var i=0;i= 0) { - shouldCheckContentLength = true; - var receivedLen = 0; - } - - var checkContentLengthAndEmit = function checkContentLengthAndEmit() { - if (shouldCheckContentLength && receivedLen !== expectedLen) { - stream.emit('error', AWS.util.error( - new Error('Stream content length mismatch. Received ' + - receivedLen + ' of ' + expectedLen + ' bytes.'), - { code: 'StreamContentLengthMismatch' } - )); - } else if (AWS.HttpClient.streamsApiVersion === 2) { - stream.end(); - } else { - stream.emit('end'); - } - }; - - var httpStream = resp.httpResponse.createUnbufferedStream(); - - if (AWS.HttpClient.streamsApiVersion === 2) { - if (shouldCheckContentLength) { - var lengthAccumulator = new streams.PassThrough(); - lengthAccumulator._write = function(chunk) { - if (chunk && chunk.length) { - receivedLen += chunk.length; - } - return streams.PassThrough.prototype._write.apply(this, arguments); - }; - - lengthAccumulator.on('end', checkContentLengthAndEmit); - stream.on('error', function(err) { - shouldCheckContentLength = false; - httpStream.unpipe(lengthAccumulator); - lengthAccumulator.emit('end'); - lengthAccumulator.end(); - }); - httpStream.pipe(lengthAccumulator).pipe(stream, { end: false }); - } else { - httpStream.pipe(stream); - } - } else { - - if (shouldCheckContentLength) { - httpStream.on('data', function(arg) { - if (arg && arg.length) { - receivedLen += arg.length; - } - }); - } - - httpStream.on('data', function(arg) { - stream.emit('data', arg); - }); - httpStream.on('end', checkContentLengthAndEmit); - } - - httpStream.on('error', function(err) { - shouldCheckContentLength = false; - stream.emit('error', err); - }); - } - }); - - return stream; - }, - - /** + */createReadStream:function createReadStream(){var streams=AWS.util.stream;var req=this;var stream=null;if(AWS.HttpClient.streamsApiVersion===2){stream=new streams.PassThrough();process.nextTick(function(){req.send();});}else{stream=new streams.Stream();stream.readable=true;stream.sent=false;stream.on('newListener',function(event){if(!stream.sent&&event==='data'){stream.sent=true;process.nextTick(function(){req.send();});}});}this.on('error',function(err){stream.emit('error',err);});this.on('httpHeaders',function streamHeaders(statusCode,headers,resp){if(statusCode<300){req.removeListener('httpData',AWS.EventListeners.Core.HTTP_DATA);req.removeListener('httpError',AWS.EventListeners.Core.HTTP_ERROR);req.on('httpError',function streamHttpError(error){resp.error=error;resp.error.retryable=false;});var shouldCheckContentLength=false;var expectedLen;if(req.httpRequest.method!=='HEAD'){expectedLen=parseInt(headers['content-length'],10);}if(expectedLen!==undefined&&!isNaN(expectedLen)&&expectedLen>=0){shouldCheckContentLength=true;var receivedLen=0;}var checkContentLengthAndEmit=function checkContentLengthAndEmit(){if(shouldCheckContentLength&&receivedLen!==expectedLen){stream.emit('error',AWS.util.error(new Error('Stream content length mismatch. Received '+receivedLen+' of '+expectedLen+' bytes.'),{code:'StreamContentLengthMismatch'}));}else if(AWS.HttpClient.streamsApiVersion===2){stream.end();}else{stream.emit('end');}};var httpStream=resp.httpResponse.createUnbufferedStream();if(AWS.HttpClient.streamsApiVersion===2){if(shouldCheckContentLength){var lengthAccumulator=new streams.PassThrough();lengthAccumulator._write=function(chunk){if(chunk&&chunk.length){receivedLen+=chunk.length;}return streams.PassThrough.prototype._write.apply(this,arguments);};lengthAccumulator.on('end',checkContentLengthAndEmit);stream.on('error',function(err){shouldCheckContentLength=false;httpStream.unpipe(lengthAccumulator);lengthAccumulator.emit('end');lengthAccumulator.end();});httpStream.pipe(lengthAccumulator).pipe(stream,{end:false});}else{httpStream.pipe(stream);}}else{if(shouldCheckContentLength){httpStream.on('data',function(arg){if(arg&&arg.length){receivedLen+=arg.length;}});}httpStream.on('data',function(arg){stream.emit('data',arg);});httpStream.on('end',checkContentLengthAndEmit);}httpStream.on('error',function(err){shouldCheckContentLength=false;stream.emit('error',err);});}});return stream;},/** * @param [Array,Response] args This should be the response object, * or an array of args to send to the event. * @api private - */ - emitEvent: function emit(eventName, args, done) { - if (typeof args === 'function') { done = args; args = null; } - if (!done) done = function() { }; - if (!args) args = this.eventParameters(eventName, this.response); - - var origEmit = AWS.SequentialExecutor.prototype.emit; - origEmit.call(this, eventName, args, function (err) { - if (err) this.response.error = err; - done.call(this, err); - }); - }, - - /** + */emitEvent:function emit(eventName,args,done){if(typeof args==='function'){done=args;args=null;}if(!done)done=function done(){};if(!args)args=this.eventParameters(eventName,this.response);var origEmit=AWS.SequentialExecutor.prototype.emit;origEmit.call(this,eventName,args,function(err){if(err)this.response.error=err;done.call(this,err);});},/** * @api private - */ - eventParameters: function eventParameters(eventName) { - switch (eventName) { - 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]; - } - }, - - /** + */eventParameters:function eventParameters(eventName){switch(eventName){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];}},/** * @api private - */ - presign: function presign(expires, callback) { - if (!callback && typeof expires === 'function') { - callback = expires; - expires = null; - } - return new AWS.Signers.Presign().sign(this.toGet(), expires, callback); - }, - - /** + */presign:function presign(expires,callback){if(!callback&&typeof expires==='function'){callback=expires;expires=null;}return new AWS.Signers.Presign().sign(this.toGet(),expires,callback);},/** * @api private - */ - isPresigned: function isPresigned() { - return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires'); - }, - - /** + */isPresigned:function isPresigned(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,'presigned-expires');},/** * @api private - */ - toUnauthenticated: function toUnauthenticated() { - this._unAuthenticated = true; - this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS); - this.removeListener('sign', AWS.EventListeners.Core.SIGN); - return this; - }, - - /** + */toUnauthenticated:function toUnauthenticated(){this._unAuthenticated=true;this.removeListener('validate',AWS.EventListeners.Core.VALIDATE_CREDENTIALS);this.removeListener('sign',AWS.EventListeners.Core.SIGN);return this;},/** * @api private - */ - toGet: function toGet() { - if (this.service.api.protocol === 'query' || - this.service.api.protocol === 'ec2') { - this.removeListener('build', this.buildAsGet); - this.addListener('build', this.buildAsGet); - } - return this; - }, - - /** + */toGet:function toGet(){if(this.service.api.protocol==='query'||this.service.api.protocol==='ec2'){this.removeListener('build',this.buildAsGet);this.addListener('build',this.buildAsGet);}return this;},/** * @api private - */ - buildAsGet: function buildAsGet(request) { - request.httpRequest.method = 'GET'; - request.httpRequest.path = request.service.endpoint.path + - '?' + request.httpRequest.body; - request.httpRequest.body = ''; - - // don't need these headers on a GET request - delete request.httpRequest.headers['Content-Length']; - delete request.httpRequest.headers['Content-Type']; - }, - - /** + */buildAsGet:function buildAsGet(request){request.httpRequest.method='GET';request.httpRequest.path=request.service.endpoint.path+'?'+request.httpRequest.body;request.httpRequest.body='';// don't need these headers on a GET request +delete request.httpRequest.headers['Content-Length'];delete request.httpRequest.headers['Content-Type'];},/** * @api private - */ - haltHandlersOnError: function haltHandlersOnError() { - this._haltHandlersOnError = true; - } -}); - -/** + */haltHandlersOnError:function haltHandlersOnError(){this._haltHandlersOnError=true;}});/** * @api private - */ -AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) { - this.prototype.promise = function promise() { - var self = this; - // append to user agent - this.httpRequest.appendToUserAgent('promise'); - return new PromiseDependency(function(resolve, reject) { - self.on('complete', function(resp) { - if (resp.error) { - reject(resp.error); - } else { - // define $response property so that it is not enumberable - // this prevents circular reference errors when stringifying the JSON object - resolve(Object.defineProperty( - resp.data || {}, - '$response', - {value: resp} - )); - } - }); - self.runTo(); - }); - }; -}; - -/** + */AWS.Request.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.promise=function promise(){var self=this;// append to user agent +this.httpRequest.appendToUserAgent('promise');return new PromiseDependency(function(resolve,reject){self.on('complete',function(resp){if(resp.error){reject(resp.error);}else{// define $response property so that it is not enumberable +// this prevents circular reference errors when stringifying the JSON object +resolve(Object.defineProperty(resp.data||{},'$response',{value:resp}));}});self.runTo();});};};/** * @api private - */ -AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() { - delete this.prototype.promise; -}; - -AWS.util.addPromises(AWS.Request); - -AWS.util.mixin(AWS.Request, AWS.SequentialExecutor); - -}).call(this)}).call(this,require('_process')) -},{"./core":18,"./state_machine":70,"_process":86,"jmespath":85}],56:[function(require,module,exports){ -/** + */AWS.Request.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.promise;};AWS.util.addPromises(AWS.Request);AWS.util.mixin(AWS.Request,AWS.SequentialExecutor);}).call(this);}).call(this,require('_process'));},{"./core":18,"./state_machine":70,"_process":86,"jmespath":85}],56:[function(require,module,exports){/** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You @@ -10323,45 +4138,11 @@ AWS.util.mixin(AWS.Request, AWS.SequentialExecutor); * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. - */ - -var AWS = require('./core'); -var inherit = AWS.util.inherit; -var jmespath = require('jmespath'); - -/** + */var AWS=require('./core');var inherit=AWS.util.inherit;var jmespath=require('jmespath');/** * @api private - */ -function CHECK_ACCEPTORS(resp) { - var waiter = resp.request._waiter; - var acceptors = waiter.config.acceptors; - var acceptorMatched = false; - var state = 'retry'; - - acceptors.forEach(function(acceptor) { - if (!acceptorMatched) { - var matcher = waiter.matchers[acceptor.matcher]; - if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) { - acceptorMatched = true; - state = acceptor.state; - } - } - }); - - if (!acceptorMatched && resp.error) state = 'failure'; - - if (state === 'success') { - waiter.setSuccess(resp); - } else { - waiter.setError(resp, state === 'retry'); - } -} - -/** + */function CHECK_ACCEPTORS(resp){var waiter=resp.request._waiter;var acceptors=waiter.config.acceptors;var acceptorMatched=false;var state='retry';acceptors.forEach(function(acceptor){if(!acceptorMatched){var matcher=waiter.matchers[acceptor.matcher];if(matcher&&matcher(resp,acceptor.expected,acceptor.argument)){acceptorMatched=true;state=acceptor.state;}}});if(!acceptorMatched&&resp.error)state='failure';if(state==='success'){waiter.setSuccess(resp);}else{waiter.setError(resp,state==='retry');}}/** * @api private - */ -AWS.ResourceWaiter = inherit({ - /** + */AWS.ResourceWaiter=inherit({/** * Waits for a given state on a service object * @param service [Service] the service object to wait on * @param state [String] the state (defined in waiter configuration) to wait @@ -10369,158 +4150,14 @@ AWS.ResourceWaiter = inherit({ * @example Create a waiter for running EC2 instances * var ec2 = new AWS.EC2; * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning'); - */ - constructor: function constructor(service, state) { - this.service = service; - this.state = state; - this.loadWaiterConfig(this.state); - }, - - service: null, - - state: null, - - config: null, - - matchers: { - path: function(resp, expected, argument) { - try { - var result = jmespath.search(resp.data, argument); - } catch (err) { - return false; - } - - return jmespath.strictDeepEqual(result,expected); - }, - - pathAll: function(resp, expected, argument) { - try { - var results = jmespath.search(resp.data, argument); - } catch (err) { - return false; - } - - if (!Array.isArray(results)) results = [results]; - var numResults = results.length; - if (!numResults) return false; - for (var ind = 0 ; ind < numResults; ind++) { - if (!jmespath.strictDeepEqual(results[ind], expected)) { - return false; - } - } - return true; - }, - - pathAny: function(resp, expected, argument) { - try { - var results = jmespath.search(resp.data, argument); - } catch (err) { - return false; - } - - if (!Array.isArray(results)) results = [results]; - var numResults = results.length; - for (var ind = 0 ; ind < numResults; ind++) { - if (jmespath.strictDeepEqual(results[ind], expected)) { - return true; - } - } - return false; - }, - - status: function(resp, expected) { - var statusCode = resp.httpResponse.statusCode; - return (typeof statusCode === 'number') && (statusCode === expected); - }, - - error: function(resp, expected) { - if (typeof expected === 'string' && resp.error) { - return expected === resp.error.code; - } - // if expected is not string, can be boolean indicating presence of error - return expected === !!resp.error; - } - }, - - listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) { - add('RETRY_CHECK', 'retry', function(resp) { - var waiter = resp.request._waiter; - if (resp.error && resp.error.code === 'ResourceNotReady') { - resp.error.retryDelay = (waiter.config.delay || 0) * 1000; - } - }); - - add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS); - - add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS); - }), - - /** + */constructor:function constructor(service,state){this.service=service;this.state=state;this.loadWaiterConfig(this.state);},service:null,state:null,config:null,matchers:{path:function path(resp,expected,argument){try{var result=jmespath.search(resp.data,argument);}catch(err){return false;}return jmespath.strictDeepEqual(result,expected);},pathAll:function pathAll(resp,expected,argument){try{var results=jmespath.search(resp.data,argument);}catch(err){return false;}if(!Array.isArray(results))results=[results];var numResults=results.length;if(!numResults)return false;for(var ind=0;ind -1) { - listeners.splice(position, 1); - } - } - return this; - }, - - removeAllListeners: function removeAllListeners(eventName) { - if (eventName) { - delete this._events[eventName]; - } else { - this._events = {}; - } - return this; - }, - - /** + */listeners:function listeners(eventName){return this._events[eventName]?this._events[eventName].slice(0):[];},on:function on(eventName,listener,toHead){if(this._events[eventName]){toHead?this._events[eventName].unshift(listener):this._events[eventName].push(listener);}else{this._events[eventName]=[listener];}return this;},onAsync:function onAsync(eventName,listener,toHead){listener._isAsync=true;return this.on(eventName,listener,toHead);},removeListener:function removeListener(eventName,listener){var listeners=this._events[eventName];if(listeners){var length=listeners.length;var position=-1;for(var i=0;i-1){listeners.splice(position,1);}}return this;},removeAllListeners:function removeAllListeners(eventName){if(eventName){delete this._events[eventName];}else{this._events={};}return this;},/** * @api private - */ - emit: function emit(eventName, eventArgs, doneCallback) { - if (!doneCallback) doneCallback = function() { }; - var listeners = this.listeners(eventName); - var count = listeners.length; - this.callListeners(listeners, eventArgs, doneCallback); - return count > 0; - }, - - /** + */emit:function emit(eventName,eventArgs,doneCallback){if(!doneCallback)doneCallback=function doneCallback(){};var listeners=this.listeners(eventName);var count=listeners.length;this.callListeners(listeners,eventArgs,doneCallback);return count>0;},/** * @api private - */ - callListeners: function callListeners(listeners, args, doneCallback, prevError) { - var self = this; - var error = prevError || null; - - function callNextListener(err) { - if (err) { - error = AWS.util.error(error || new Error(), err); - if (self._haltHandlersOnError) { - return doneCallback.call(self, error); - } - } - self.callListeners(listeners, args, doneCallback, error); - } - - while (listeners.length > 0) { - var listener = listeners.shift(); - if (listener._isAsync) { // asynchronous listener - listener.apply(self, args.concat([callNextListener])); - return; // stop here, callNextListener will continue - } else { // synchronous listener - try { - listener.apply(self, args); - } catch (err) { - error = AWS.util.error(error || new Error(), err); - } - if (error && self._haltHandlersOnError) { - doneCallback.call(self, error); - return; - } - } - } - doneCallback.call(self, error); - }, - - /** + */callListeners:function callListeners(listeners,args,doneCallback,prevError){var self=this;var error=prevError||null;function callNextListener(err){if(err){error=AWS.util.error(error||new Error(),err);if(self._haltHandlersOnError){return doneCallback.call(self,error);}}self.callListeners(listeners,args,doneCallback,error);}while(listeners.length>0){var listener=listeners.shift();if(listener._isAsync){// asynchronous listener +listener.apply(self,args.concat([callNextListener]));return;// stop here, callNextListener will continue +}else{// synchronous listener +try{listener.apply(self,args);}catch(err){error=AWS.util.error(error||new Error(),err);}if(error&&self._haltHandlersOnError){doneCallback.call(self,error);return;}}}doneCallback.call(self,error);},/** * Adds or copies a set of listeners from another list of * listeners or SequentialExecutor object. * @@ -10860,24 +4316,8 @@ AWS.SequentialExecutor = AWS.util.inherit({ * emitter2.addListeners(emitter1); * emitter2.emit('event1'); // emitter2 has event1 * emitter2.emit('event2'); // emitter2 has event2 - */ - addListeners: function addListeners(listeners) { - var self = this; - - // extract listeners if parameter is an SequentialExecutor object - if (listeners._events) listeners = listeners._events; - - AWS.util.each(listeners, function(event, callbacks) { - if (typeof callbacks === 'function') callbacks = [callbacks]; - AWS.util.arrayEach(callbacks, function(callback) { - self.on(event, callback); - }); - }); - - return self; - }, - - /** + */addListeners:function addListeners(listeners){var self=this;// extract listeners if parameter is an SequentialExecutor object +if(listeners._events)listeners=listeners._events;AWS.util.each(listeners,function(event,callbacks){if(typeof callbacks==='function')callbacks=[callbacks];AWS.util.arrayEach(callbacks,function(callback){self.on(event,callback);});});return self;},/** * Registers an event with {on} and saves the callback handle function * as a property on the emitter object using a given `name`. * @@ -10892,22 +4332,9 @@ AWS.SequentialExecutor = AWS.util.inherit({ * * // the following prints: true * console.log(emitter.DATA_CALLBACK == listener); - */ - addNamedListener: function addNamedListener(name, eventName, callback, toHead) { - this[name] = callback; - this.addListener(eventName, callback, toHead); - return this; - }, - - /** + */addNamedListener:function addNamedListener(name,eventName,callback,toHead){this[name]=callback;this.addListener(eventName,callback,toHead);return this;},/** * @api private - */ - addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) { - callback._isAsync = true; - return this.addNamedListener(name, eventName, callback, toHead); - }, - - /** + */addNamedAsyncListener:function addNamedAsyncListener(name,eventName,callback,toHead){callback._isAsync=true;return this.addNamedListener(name,eventName,callback,toHead);},/** * Helper method to add a set of named listeners using * {addNamedListener}. The callback contains a parameter * with a handle to the `addNamedListener` method. @@ -10929,42 +4356,12 @@ AWS.SequentialExecutor = AWS.util.inherit({ * emitter.DATA_CALLBACK; * emitter.OTHER; * emitter.LAST; - */ - addNamedListeners: function addNamedListeners(callback) { - var self = this; - callback( - function() { - self.addNamedListener.apply(self, arguments); - }, - function() { - self.addNamedAsyncListener.apply(self, arguments); - } - ); - return this; - } -}); - -/** + */addNamedListeners:function addNamedListeners(callback){var self=this;callback(function(){self.addNamedListener.apply(self,arguments);},function(){self.addNamedAsyncListener.apply(self,arguments);});return this;}});/** * {on} is the prefered method. * @api private - */ -AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on; - -/** + */AWS.SequentialExecutor.prototype.addListener=AWS.SequentialExecutor.prototype.on;/** * @api private - */ -module.exports = AWS.SequentialExecutor; - -},{"./core":18}],59:[function(require,module,exports){ -(function (process){(function (){ -var AWS = require('./core'); -var Api = require('./model/api'); -var regionConfig = require('./region_config'); - -var inherit = AWS.util.inherit; -var clientCount = 0; - -/** + */module.exports=AWS.SequentialExecutor;},{"./core":18}],59:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');var Api=require('./model/api');var regionConfig=require('./region_config');var inherit=AWS.util.inherit;var clientCount=0;/** * The service class representing an AWS service. * * @class_abstract This class is an abstract class. @@ -10972,159 +4369,30 @@ var clientCount = 0; * @!attribute apiVersions * @return [Array] the list of API versions supported by this service. * @readonly - */ -AWS.Service = inherit({ - /** + */AWS.Service=inherit({/** * Create a new service object with a configuration object * * @param config [map] a map of configuration options - */ - constructor: function Service(config) { - if (!this.loadServiceClass) { - throw AWS.util.error(new Error(), - 'Service must be constructed with `new\' operator'); - } - var ServiceClass = this.loadServiceClass(config || {}); - if (ServiceClass) { - var originalConfig = AWS.util.copy(config); - var svc = new ServiceClass(config); - Object.defineProperty(svc, '_originalConfig', { - get: function() { return originalConfig; }, - enumerable: false, - configurable: true - }); - svc._clientId = ++clientCount; - return svc; - } - this.initialize(config); - }, - - /** + */constructor:function Service(config){if(!this.loadServiceClass){throw AWS.util.error(new Error(),'Service must be constructed with `new\' operator');}var ServiceClass=this.loadServiceClass(config||{});if(ServiceClass){var originalConfig=AWS.util.copy(config);var svc=new ServiceClass(config);Object.defineProperty(svc,'_originalConfig',{get:function get(){return originalConfig;},enumerable:false,configurable:true});svc._clientId=++clientCount;return svc;}this.initialize(config);},/** * @api private - */ - initialize: function initialize(config) { - var svcConfig = AWS.config[this.serviceIdentifier]; - this.config = new AWS.Config(AWS.config); - if (svcConfig) this.config.update(svcConfig, true); - if (config) this.config.update(config, true); - - this.validateService(); - if (!this.config.endpoint) regionConfig(this); - - this.config.endpoint = this.endpointFromTemplate(this.config.endpoint); - this.setEndpoint(this.config.endpoint); - //enable attaching listeners to service client - AWS.SequentialExecutor.call(this); - AWS.Service.addDefaultMonitoringListeners(this); - if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) { - var publisher = this.publisher; - this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) { - process.nextTick(function() {publisher.eventHandler(event);}); - }); - this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) { - process.nextTick(function() {publisher.eventHandler(event);}); - }); - } - }, - - /** + */initialize:function initialize(config){var svcConfig=AWS.config[this.serviceIdentifier];this.config=new AWS.Config(AWS.config);if(svcConfig)this.config.update(svcConfig,true);if(config)this.config.update(config,true);this.validateService();if(!this.config.endpoint)regionConfig(this);this.config.endpoint=this.endpointFromTemplate(this.config.endpoint);this.setEndpoint(this.config.endpoint);//enable attaching listeners to service client +AWS.SequentialExecutor.call(this);AWS.Service.addDefaultMonitoringListeners(this);if((this.config.clientSideMonitoring||AWS.Service._clientSideMonitoring)&&this.publisher){var publisher=this.publisher;this.addNamedListener('PUBLISH_API_CALL','apiCall',function PUBLISH_API_CALL(event){process.nextTick(function(){publisher.eventHandler(event);});});this.addNamedListener('PUBLISH_API_ATTEMPT','apiCallAttempt',function PUBLISH_API_ATTEMPT(event){process.nextTick(function(){publisher.eventHandler(event);});});}},/** * @api private - */ - validateService: function validateService() { - }, - - /** + */validateService:function validateService(){},/** * @api private - */ - loadServiceClass: function loadServiceClass(serviceConfig) { - var config = serviceConfig; - if (!AWS.util.isEmpty(this.api)) { - return null; - } else if (config.apiConfig) { - return AWS.Service.defineServiceApi(this.constructor, config.apiConfig); - } else if (!this.constructor.services) { - return null; - } else { - config = new AWS.Config(AWS.config); - config.update(serviceConfig, true); - var version = config.apiVersions[this.constructor.serviceIdentifier]; - version = version || config.apiVersion; - return this.getLatestServiceClass(version); - } - }, - - /** + */loadServiceClass:function loadServiceClass(serviceConfig){var config=serviceConfig;if(!AWS.util.isEmpty(this.api)){return null;}else if(config.apiConfig){return AWS.Service.defineServiceApi(this.constructor,config.apiConfig);}else if(!this.constructor.services){return null;}else{config=new AWS.Config(AWS.config);config.update(serviceConfig,true);var version=config.apiVersions[this.constructor.serviceIdentifier];version=version||config.apiVersion;return this.getLatestServiceClass(version);}},/** * @api private - */ - getLatestServiceClass: function getLatestServiceClass(version) { - version = this.getLatestServiceVersion(version); - if (this.constructor.services[version] === null) { - AWS.Service.defineServiceApi(this.constructor, version); - } - - return this.constructor.services[version]; - }, - - /** + */getLatestServiceClass:function getLatestServiceClass(version){version=this.getLatestServiceVersion(version);if(this.constructor.services[version]===null){AWS.Service.defineServiceApi(this.constructor,version);}return this.constructor.services[version];},/** * @api private - */ - getLatestServiceVersion: function getLatestServiceVersion(version) { - if (!this.constructor.services || this.constructor.services.length === 0) { - throw new Error('No services defined on ' + - this.constructor.serviceIdentifier); - } - - if (!version) { - version = 'latest'; - } else if (AWS.util.isType(version, Date)) { - version = AWS.util.date.iso8601(version).split('T')[0]; - } - - if (Object.hasOwnProperty(this.constructor.services, version)) { - return version; - } - - var keys = Object.keys(this.constructor.services).sort(); - var selectedVersion = null; - for (var i = keys.length - 1; i >= 0; i--) { - // versions that end in "*" are not available on disk and can be - // skipped, so do not choose these as selectedVersions - if (keys[i][keys[i].length - 1] !== '*') { - selectedVersion = keys[i]; - } - if (keys[i].substr(0, 10) <= version) { - return selectedVersion; - } - } - - throw new Error('Could not find ' + this.constructor.serviceIdentifier + - ' API to satisfy version constraint `' + version + '\''); - }, - - /** + */getLatestServiceVersion:function getLatestServiceVersion(version){if(!this.constructor.services||this.constructor.services.length===0){throw new Error('No services defined on '+this.constructor.serviceIdentifier);}if(!version){version='latest';}else if(AWS.util.isType(version,Date)){version=AWS.util.date.iso8601(version).split('T')[0];}if(Object.hasOwnProperty(this.constructor.services,version)){return version;}var keys=Object.keys(this.constructor.services).sort();var selectedVersion=null;for(var i=keys.length-1;i>=0;i--){// versions that end in "*" are not available on disk and can be +// skipped, so do not choose these as selectedVersions +if(keys[i][keys[i].length-1]!=='*'){selectedVersion=keys[i];}if(keys[i].substr(0,10)<=version){return selectedVersion;}}throw new Error('Could not find '+this.constructor.serviceIdentifier+' API to satisfy version constraint `'+version+'\'');},/** * @api private - */ - api: {}, - - /** + */api:{},/** * @api private - */ - defaultRetryCount: 3, - - /** + */defaultRetryCount:3,/** * @api private - */ - customizeRequests: function customizeRequests(callback) { - if (!callback) { - this.customRequestHandler = null; - } else if (typeof callback === 'function') { - this.customRequestHandler = callback; - } else { - throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests'); - } - }, - - /** + */customizeRequests:function customizeRequests(callback){if(!callback){this.customRequestHandler=null;}else if(typeof callback==='function'){this.customRequestHandler=callback;}else{throw new Error('Invalid callback type \''+_typeof(callback)+'\' provided in customizeRequests');}},/** * Calls an operation on a service with the given input parameters. * * @param operation [String] the name of the operation to call on the service. @@ -11136,36 +4404,8 @@ AWS.Service = inherit({ * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. - */ - makeRequest: function makeRequest(operation, params, callback) { - if (typeof params === 'function') { - callback = params; - params = null; - } - - params = params || {}; - if (this.config.params) { // copy only toplevel bound params - var rules = this.api.operations[operation]; - if (rules) { - params = AWS.util.copy(params); - AWS.util.each(this.config.params, function(key, value) { - if (rules.input.members[key]) { - if (params[key] === undefined || params[key] === null) { - params[key] = value; - } - } - }); - } - } - - var request = new AWS.Request(this, operation, params); - this.addAllRequestListeners(request); - this.attachMonitoringEmitter(request); - if (callback) request.send(callback); - return request; - }, - - /** + */makeRequest:function makeRequest(operation,params,callback){if(typeof params==='function'){callback=params;params=null;}params=params||{};if(this.config.params){// copy only toplevel bound params +var rules=this.api.operations[operation];if(rules){params=AWS.util.copy(params);AWS.util.each(this.config.params,function(key,value){if(rules.input.members[key]){if(params[key]===undefined||params[key]===null){params[key]=value;}}});}}var request=new AWS.Request(this,operation,params);this.addAllRequestListeners(request);this.attachMonitoringEmitter(request);if(callback)request.send(callback);return request;},/** * Calls an operation on a service with the given input parameters, without * any authentication data. This method is useful for "public" API operations. * @@ -11178,18 +4418,7 @@ AWS.Service = inherit({ * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. - */ - makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) { - if (typeof params === 'function') { - callback = params; - params = {}; - } - - var request = this.makeRequest(operation, params).toUnauthenticated(); - return callback ? request.send(callback) : request; - }, - - /** + */makeUnauthenticatedRequest:function makeUnauthenticatedRequest(operation,params,callback){if(typeof params==='function'){callback=params;params={};}var request=this.makeRequest(operation,params).toUnauthenticated();return callback?request.send(callback):request;},/** * Waits for a given state * * @param state [String] the state on the service to wait for @@ -11206,437 +4435,87 @@ AWS.Service = inherit({ * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. - */ - waitFor: function waitFor(state, params, callback) { - var waiter = new AWS.ResourceWaiter(this, state); - return waiter.wait(params, callback); - }, - - /** + */waitFor:function waitFor(state,params,callback){var waiter=new AWS.ResourceWaiter(this,state);return waiter.wait(params,callback);},/** * @api private - */ - addAllRequestListeners: function addAllRequestListeners(request) { - var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(), - AWS.EventListeners.CorePost]; - for (var i = 0; i < list.length; i++) { - if (list[i]) request.addListeners(list[i]); - } - - // disable parameter validation - if (!this.config.paramValidation) { - request.removeListener('validate', - AWS.EventListeners.Core.VALIDATE_PARAMETERS); - } - - if (this.config.logger) { // add logging events - request.addListeners(AWS.EventListeners.Logger); - } - - this.setupRequestListeners(request); - // call prototype's customRequestHandler - if (typeof this.constructor.prototype.customRequestHandler === 'function') { - this.constructor.prototype.customRequestHandler(request); - } - // call instance's customRequestHandler - if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') { - this.customRequestHandler(request); - } - }, - - /** + */addAllRequestListeners:function addAllRequestListeners(request){var list=[AWS.events,AWS.EventListeners.Core,this.serviceInterface(),AWS.EventListeners.CorePost];for(var i=0;i 299) { - if (error.code) monitoringEvent.FinalAwsException = error.code; - if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message; - } else { - if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name; - if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message; - } - } - return monitoringEvent; - }, - - /** + */apiCallEvent:function apiCallEvent(request){var api=request.service.api.operations[request.operation];var monitoringEvent={Type:'ApiCall',Api:api?api.name:request.operation,Version:1,Service:request.service.api.serviceId||request.service.api.endpointPrefix,Region:request.httpRequest.region,MaxRetriesExceeded:0,UserAgent:request.httpRequest.getUserAgent()};var response=request.response;if(response.httpResponse.statusCode){monitoringEvent.FinalHttpStatusCode=response.httpResponse.statusCode;}if(response.error){var error=response.error;var statusCode=response.httpResponse.statusCode;if(statusCode>299){if(error.code)monitoringEvent.FinalAwsException=error.code;if(error.message)monitoringEvent.FinalAwsExceptionMessage=error.message;}else{if(error.code||error.name)monitoringEvent.FinalSdkException=error.code||error.name;if(error.message)monitoringEvent.FinalSdkExceptionMessage=error.message;}}return monitoringEvent;},/** * Event recording metrics for an API call attempt. * @returns {object} a subset of api call attempt metrics * @api private - */ - apiAttemptEvent: function apiAttemptEvent(request) { - var api = request.service.api.operations[request.operation]; - var monitoringEvent = { - Type: 'ApiCallAttempt', - Api: api ? api.name : request.operation, - Version: 1, - Service: request.service.api.serviceId || request.service.api.endpointPrefix, - Fqdn: request.httpRequest.endpoint.hostname, - UserAgent: request.httpRequest.getUserAgent(), - }; - var response = request.response; - if (response.httpResponse.statusCode) { - monitoringEvent.HttpStatusCode = response.httpResponse.statusCode; - } - if ( - !request._unAuthenticated && - request.service.config.credentials && - request.service.config.credentials.accessKeyId - ) { - monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId; - } - if (!response.httpResponse.headers) return monitoringEvent; - if (request.httpRequest.headers['x-amz-security-token']) { - monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token']; - } - if (response.httpResponse.headers['x-amzn-requestid']) { - monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid']; - } - if (response.httpResponse.headers['x-amz-request-id']) { - monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id']; - } - if (response.httpResponse.headers['x-amz-id-2']) { - monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2']; - } - return monitoringEvent; - }, - - /** + */apiAttemptEvent:function apiAttemptEvent(request){var api=request.service.api.operations[request.operation];var monitoringEvent={Type:'ApiCallAttempt',Api:api?api.name:request.operation,Version:1,Service:request.service.api.serviceId||request.service.api.endpointPrefix,Fqdn:request.httpRequest.endpoint.hostname,UserAgent:request.httpRequest.getUserAgent()};var response=request.response;if(response.httpResponse.statusCode){monitoringEvent.HttpStatusCode=response.httpResponse.statusCode;}if(!request._unAuthenticated&&request.service.config.credentials&&request.service.config.credentials.accessKeyId){monitoringEvent.AccessKey=request.service.config.credentials.accessKeyId;}if(!response.httpResponse.headers)return monitoringEvent;if(request.httpRequest.headers['x-amz-security-token']){monitoringEvent.SessionToken=request.httpRequest.headers['x-amz-security-token'];}if(response.httpResponse.headers['x-amzn-requestid']){monitoringEvent.XAmznRequestId=response.httpResponse.headers['x-amzn-requestid'];}if(response.httpResponse.headers['x-amz-request-id']){monitoringEvent.XAmzRequestId=response.httpResponse.headers['x-amz-request-id'];}if(response.httpResponse.headers['x-amz-id-2']){monitoringEvent.XAmzId2=response.httpResponse.headers['x-amz-id-2'];}return monitoringEvent;},/** * Add metrics of failed request. * @api private - */ - attemptFailEvent: function attemptFailEvent(request) { - var monitoringEvent = this.apiAttemptEvent(request); - var response = request.response; - var error = response.error; - if (response.httpResponse.statusCode > 299 ) { - if (error.code) monitoringEvent.AwsException = error.code; - if (error.message) monitoringEvent.AwsExceptionMessage = error.message; - } else { - if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name; - if (error.message) monitoringEvent.SdkExceptionMessage = error.message; - } - return monitoringEvent; - }, - - /** + */attemptFailEvent:function attemptFailEvent(request){var monitoringEvent=this.apiAttemptEvent(request);var response=request.response;var error=response.error;if(response.httpResponse.statusCode>299){if(error.code)monitoringEvent.AwsException=error.code;if(error.message)monitoringEvent.AwsExceptionMessage=error.message;}else{if(error.code||error.name)monitoringEvent.SdkException=error.code||error.name;if(error.message)monitoringEvent.SdkExceptionMessage=error.message;}return monitoringEvent;},/** * Attach listeners to request object to fetch metrics of each request * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events. * @api private - */ - attachMonitoringEmitter: function attachMonitoringEmitter(request) { - var attemptTimestamp; //timestamp marking the beginning of a request attempt - var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency - var attemptLatency; //latency from request sent out to http response reaching SDK - var callStartRealTime; //Start time of API call. Used to calculating API call latency - var attemptCount = 0; //request.retryCount is not reliable here - var region; //region cache region for each attempt since it can be updated in plase (e.g. s3) - var callTimestamp; //timestamp when the request is created - var self = this; - var addToHead = true; - - request.on('validate', function () { - callStartRealTime = AWS.util.realClock.now(); - callTimestamp = Date.now(); - }, addToHead); - request.on('sign', function () { - attemptStartRealTime = AWS.util.realClock.now(); - attemptTimestamp = Date.now(); - region = request.httpRequest.region; - attemptCount++; - }, addToHead); - request.on('validateResponse', function() { - attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime); - }); - request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() { - var apiAttemptEvent = self.apiAttemptEvent(request); - apiAttemptEvent.Timestamp = attemptTimestamp; - apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0; - apiAttemptEvent.Region = region; - self.emit('apiCallAttempt', [apiAttemptEvent]); - }); - request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() { - var apiAttemptEvent = self.attemptFailEvent(request); - apiAttemptEvent.Timestamp = attemptTimestamp; - //attemptLatency may not be available if fail before response - attemptLatency = attemptLatency || - Math.round(AWS.util.realClock.now() - attemptStartRealTime); - apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0; - apiAttemptEvent.Region = region; - self.emit('apiCallAttempt', [apiAttemptEvent]); - }); - request.addNamedListener('API_CALL', 'complete', function API_CALL() { - var apiCallEvent = self.apiCallEvent(request); - apiCallEvent.AttemptCount = attemptCount; - if (apiCallEvent.AttemptCount <= 0) return; - apiCallEvent.Timestamp = callTimestamp; - var latency = Math.round(AWS.util.realClock.now() - callStartRealTime); - apiCallEvent.Latency = latency >= 0 ? latency : 0; - var response = request.response; - if ( - typeof response.retryCount === 'number' && - typeof response.maxRetries === 'number' && - (response.retryCount >= response.maxRetries) - ) { - apiCallEvent.MaxRetriesExceeded = 1; - } - self.emit('apiCall', [apiCallEvent]); - }); - }, - - /** + */attachMonitoringEmitter:function attachMonitoringEmitter(request){var attemptTimestamp;//timestamp marking the beginning of a request attempt +var attemptStartRealTime;//Start time of request attempt. Used to calculating attemptLatency +var attemptLatency;//latency from request sent out to http response reaching SDK +var callStartRealTime;//Start time of API call. Used to calculating API call latency +var attemptCount=0;//request.retryCount is not reliable here +var region;//region cache region for each attempt since it can be updated in plase (e.g. s3) +var callTimestamp;//timestamp when the request is created +var self=this;var addToHead=true;request.on('validate',function(){callStartRealTime=AWS.util.realClock.now();callTimestamp=Date.now();},addToHead);request.on('sign',function(){attemptStartRealTime=AWS.util.realClock.now();attemptTimestamp=Date.now();region=request.httpRequest.region;attemptCount++;},addToHead);request.on('validateResponse',function(){attemptLatency=Math.round(AWS.util.realClock.now()-attemptStartRealTime);});request.addNamedListener('API_CALL_ATTEMPT','success',function API_CALL_ATTEMPT(){var apiAttemptEvent=self.apiAttemptEvent(request);apiAttemptEvent.Timestamp=attemptTimestamp;apiAttemptEvent.AttemptLatency=attemptLatency>=0?attemptLatency:0;apiAttemptEvent.Region=region;self.emit('apiCallAttempt',[apiAttemptEvent]);});request.addNamedListener('API_CALL_ATTEMPT_RETRY','retry',function API_CALL_ATTEMPT_RETRY(){var apiAttemptEvent=self.attemptFailEvent(request);apiAttemptEvent.Timestamp=attemptTimestamp;//attemptLatency may not be available if fail before response +attemptLatency=attemptLatency||Math.round(AWS.util.realClock.now()-attemptStartRealTime);apiAttemptEvent.AttemptLatency=attemptLatency>=0?attemptLatency:0;apiAttemptEvent.Region=region;self.emit('apiCallAttempt',[apiAttemptEvent]);});request.addNamedListener('API_CALL','complete',function API_CALL(){var apiCallEvent=self.apiCallEvent(request);apiCallEvent.AttemptCount=attemptCount;if(apiCallEvent.AttemptCount<=0)return;apiCallEvent.Timestamp=callTimestamp;var latency=Math.round(AWS.util.realClock.now()-callStartRealTime);apiCallEvent.Latency=latency>=0?latency:0;var response=request.response;if(typeof response.retryCount==='number'&&typeof response.maxRetries==='number'&&response.retryCount>=response.maxRetries){apiCallEvent.MaxRetriesExceeded=1;}self.emit('apiCall',[apiCallEvent]);});},/** * Override this method to setup any custom request listeners for each * new request to the service. * * @method_abstract This is an abstract method. - */ - setupRequestListeners: function setupRequestListeners(request) { - }, - - /** + */setupRequestListeners:function setupRequestListeners(request){},/** * Gets the signer class for a given request * @api private - */ - getSignerClass: function getSignerClass(request) { - var version; - // get operation authtype if present - var operation = null; - var authtype = ''; - if (request) { - var operations = request.service.api.operations || {}; - operation = operations[request.operation] || null; - authtype = operation ? operation.authtype : ''; - } - if (this.config.signatureVersion) { - version = this.config.signatureVersion; - } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') { - version = 'v4'; - } else { - version = this.api.signatureVersion; - } - return AWS.Signers.RequestSigner.getVersion(version); - }, - - /** + */getSignerClass:function getSignerClass(request){var version;// get operation authtype if present +var operation=null;var authtype='';if(request){var operations=request.service.api.operations||{};operation=operations[request.operation]||null;authtype=operation?operation.authtype:'';}if(this.config.signatureVersion){version=this.config.signatureVersion;}else if(authtype==='v4'||authtype==='v4-unsigned-body'){version='v4';}else{version=this.api.signatureVersion;}return AWS.Signers.RequestSigner.getVersion(version);},/** * @api private - */ - serviceInterface: function serviceInterface() { - switch (this.api.protocol) { - case 'ec2': return AWS.EventListeners.Query; - case 'query': return AWS.EventListeners.Query; - case 'json': return AWS.EventListeners.Json; - case 'rest-json': return AWS.EventListeners.RestJson; - case 'rest-xml': return AWS.EventListeners.RestXml; - } - if (this.api.protocol) { - throw new Error('Invalid service `protocol\' ' + - this.api.protocol + ' in API config'); - } - }, - - /** + */serviceInterface:function serviceInterface(){switch(this.api.protocol){case'ec2':return AWS.EventListeners.Query;case'query':return AWS.EventListeners.Query;case'json':return AWS.EventListeners.Json;case'rest-json':return AWS.EventListeners.RestJson;case'rest-xml':return AWS.EventListeners.RestXml;}if(this.api.protocol){throw new Error('Invalid service `protocol\' '+this.api.protocol+' in API config');}},/** * @api private - */ - successfulResponse: function successfulResponse(resp) { - return resp.httpResponse.statusCode < 300; - }, - - /** + */successfulResponse:function successfulResponse(resp){return resp.httpResponse.statusCode<300;},/** * How many times a failed request should be retried before giving up. * the defaultRetryCount can be overriden by service classes. * * @api private - */ - numRetries: function numRetries() { - if (this.config.maxRetries !== undefined) { - return this.config.maxRetries; - } else { - return this.defaultRetryCount; - } - }, - - /** + */numRetries:function numRetries(){if(this.config.maxRetries!==undefined){return this.config.maxRetries;}else{return this.defaultRetryCount;}},/** * @api private - */ - retryDelays: function retryDelays(retryCount) { - return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions); - }, - - /** + */retryDelays:function retryDelays(retryCount){return AWS.util.calculateRetryDelay(retryCount,this.config.retryDelayOptions);},/** * @api private - */ - retryableError: function retryableError(error) { - if (this.timeoutError(error)) return true; - if (this.networkingError(error)) return true; - if (this.expiredCredentialsError(error)) return true; - if (this.throttledError(error)) return true; - if (error.statusCode >= 500) return true; - return false; - }, - - /** + */retryableError:function retryableError(error){if(this.timeoutError(error))return true;if(this.networkingError(error))return true;if(this.expiredCredentialsError(error))return true;if(this.throttledError(error))return true;if(error.statusCode>=500)return true;return false;},/** * @api private - */ - networkingError: function networkingError(error) { - return error.code === 'NetworkingError'; - }, - - /** + */networkingError:function networkingError(error){return error.code==='NetworkingError';},/** * @api private - */ - timeoutError: function timeoutError(error) { - return error.code === 'TimeoutError'; - }, - - /** + */timeoutError:function timeoutError(error){return error.code==='TimeoutError';},/** * @api private - */ - expiredCredentialsError: function expiredCredentialsError(error) { - // TODO : this only handles *one* of the expired credential codes - return (error.code === 'ExpiredTokenException'); - }, - - /** + */expiredCredentialsError:function expiredCredentialsError(error){// TODO : this only handles *one* of the expired credential codes +return error.code==='ExpiredTokenException';},/** * @api private - */ - clockSkewError: function clockSkewError(error) { - switch (error.code) { - case 'RequestTimeTooSkewed': - case 'RequestExpired': - case 'InvalidSignatureException': - case 'SignatureDoesNotMatch': - case 'AuthFailure': - case 'RequestInTheFuture': - return true; - default: return false; - } - }, - - /** + */clockSkewError:function clockSkewError(error){switch(error.code){case'RequestTimeTooSkewed':case'RequestExpired':case'InvalidSignatureException':case'SignatureDoesNotMatch':case'AuthFailure':case'RequestInTheFuture':return true;default:return false;}},/** * @api private - */ - getSkewCorrectedDate: function getSkewCorrectedDate() { - return new Date(Date.now() + this.config.systemClockOffset); - }, - - /** + */getSkewCorrectedDate:function getSkewCorrectedDate(){return new Date(Date.now()+this.config.systemClockOffset);},/** * @api private - */ - applyClockOffset: function applyClockOffset(newServerTime) { - if (newServerTime) { - this.config.systemClockOffset = newServerTime - Date.now(); - } - }, - - /** + */applyClockOffset:function applyClockOffset(newServerTime){if(newServerTime){this.config.systemClockOffset=newServerTime-Date.now();}},/** * @api private - */ - isClockSkewed: function isClockSkewed(newServerTime) { - if (newServerTime) { - return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000; - } - }, - - /** + */isClockSkewed:function isClockSkewed(newServerTime){if(newServerTime){return Math.abs(this.getSkewCorrectedDate().getTime()-newServerTime)>=30000;}},/** * @api private - */ - throttledError: function throttledError(error) { - // this logic varies between services - if (error.statusCode === 429) return true; - switch (error.code) { - case 'ProvisionedThroughputExceededException': - case 'Throttling': - case 'ThrottlingException': - case 'RequestLimitExceeded': - case 'RequestThrottled': - case 'RequestThrottledException': - case 'TooManyRequestsException': - case 'TransactionInProgressException': //dynamodb - return true; - default: - return false; - } - }, - - /** + */throttledError:function throttledError(error){// this logic varies between services +if(error.statusCode===429)return true;switch(error.code){case'ProvisionedThroughputExceededException':case'Throttling':case'ThrottlingException':case'RequestLimitExceeded':case'RequestThrottled':case'RequestThrottledException':case'TooManyRequestsException':case'TransactionInProgressException'://dynamodb +return true;default:return false;}},/** * @api private - */ - endpointFromTemplate: function endpointFromTemplate(endpoint) { - if (typeof endpoint !== 'string') return endpoint; - - var e = endpoint; - e = e.replace(/\{service\}/g, this.api.endpointPrefix); - e = e.replace(/\{region\}/g, this.config.region); - e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http'); - return e; - }, - - /** + */endpointFromTemplate:function endpointFromTemplate(endpoint){if(typeof endpoint!=='string')return endpoint;var e=endpoint;e=e.replace(/\{service\}/g,this.api.endpointPrefix);e=e.replace(/\{region\}/g,this.config.region);e=e.replace(/\{scheme\}/g,this.config.sslEnabled?'https':'http');return e;},/** * @api private - */ - setEndpoint: function setEndpoint(endpoint) { - this.endpoint = new AWS.Endpoint(endpoint, this.config); - }, - - /** + */setEndpoint:function setEndpoint(endpoint){this.endpoint=new AWS.Endpoint(endpoint,this.config);},/** * @api private - */ - paginationConfig: function paginationConfig(operation, throwException) { - var paginator = this.api.operations[operation].paginator; - if (!paginator) { - if (throwException) { - var e = new Error(); - throw AWS.util.error(e, 'No pagination configuration for ' + operation); - } - return null; - } - - return paginator; - } -}); - -AWS.util.update(AWS.Service, { - - /** + */paginationConfig:function paginationConfig(operation,throwException){var paginator=this.api.operations[operation].paginator;if(!paginator){if(throwException){var e=new Error();throw AWS.util.error(e,'No pagination configuration for '+operation);}return null;}return paginator;}});AWS.util.update(AWS.Service,{/** * Adds one method for each operation described in the api configuration * * @api private - */ - defineMethods: function defineMethods(svc) { - AWS.util.each(svc.prototype.api.operations, function iterator(method) { - if (svc.prototype[method]) return; - var operation = svc.prototype.api.operations[method]; - if (operation.authtype === 'none') { - svc.prototype[method] = function (params, callback) { - return this.makeUnauthenticatedRequest(method, params, callback); - }; - } else { - svc.prototype[method] = function (params, callback) { - return this.makeRequest(method, params, callback); - }; - } - }); - }, - - /** + */defineMethods:function defineMethods(svc){AWS.util.each(svc.prototype.api.operations,function iterator(method){if(svc.prototype[method])return;var operation=svc.prototype.api.operations[method];if(operation.authtype==='none'){svc.prototype[method]=function(params,callback){return this.makeUnauthenticatedRequest(method,params,callback);};}else{svc.prototype[method]=function(params,callback){return this.makeRequest(method,params,callback);};}});},/** * Defines a new Service class using a service identifier and list of versions * including an optional set of features (functions) to apply to the class * prototype. @@ -11646,16230 +4525,6292 @@ AWS.util.update(AWS.Service, { * service * @param features [Object] an object to attach to the prototype * @return [Class] the service class defined by this function. - */ - defineService: function defineService(serviceIdentifier, versions, features) { - AWS.Service._serviceMap[serviceIdentifier] = true; - if (!Array.isArray(versions)) { - features = versions; - versions = []; - } - - var svc = inherit(AWS.Service, features || {}); - - if (typeof serviceIdentifier === 'string') { - AWS.Service.addVersions(svc, versions); - - var identifier = svc.serviceIdentifier || serviceIdentifier; - svc.serviceIdentifier = identifier; - } else { // defineService called with an API - svc.prototype.api = serviceIdentifier; - AWS.Service.defineMethods(svc); - } - AWS.SequentialExecutor.call(this.prototype); - //util.clientSideMonitoring is only available in node - if (!this.prototype.publisher && AWS.util.clientSideMonitoring) { - var Publisher = AWS.util.clientSideMonitoring.Publisher; - var configProvider = AWS.util.clientSideMonitoring.configProvider; - var publisherConfig = configProvider(); - this.prototype.publisher = new Publisher(publisherConfig); - if (publisherConfig.enabled) { - //if csm is enabled in environment, SDK should send all metrics - AWS.Service._clientSideMonitoring = true; - } - } - AWS.SequentialExecutor.call(svc.prototype); - AWS.Service.addDefaultMonitoringListeners(svc.prototype); - return svc; - }, - - /** + */defineService:function defineService(serviceIdentifier,versions,features){AWS.Service._serviceMap[serviceIdentifier]=true;if(!Array.isArray(versions)){features=versions;versions=[];}var svc=inherit(AWS.Service,features||{});if(typeof serviceIdentifier==='string'){AWS.Service.addVersions(svc,versions);var identifier=svc.serviceIdentifier||serviceIdentifier;svc.serviceIdentifier=identifier;}else{// defineService called with an API +svc.prototype.api=serviceIdentifier;AWS.Service.defineMethods(svc);}AWS.SequentialExecutor.call(this.prototype);//util.clientSideMonitoring is only available in node +if(!this.prototype.publisher&&AWS.util.clientSideMonitoring){var Publisher=AWS.util.clientSideMonitoring.Publisher;var configProvider=AWS.util.clientSideMonitoring.configProvider;var publisherConfig=configProvider();this.prototype.publisher=new Publisher(publisherConfig);if(publisherConfig.enabled){//if csm is enabled in environment, SDK should send all metrics +AWS.Service._clientSideMonitoring=true;}}AWS.SequentialExecutor.call(svc.prototype);AWS.Service.addDefaultMonitoringListeners(svc.prototype);return svc;},/** * @api private - */ - addVersions: function addVersions(svc, versions) { - if (!Array.isArray(versions)) versions = [versions]; - - svc.services = svc.services || {}; - for (var i = 0; i < versions.length; i++) { - if (svc.services[versions[i]] === undefined) { - svc.services[versions[i]] = null; - } - } - - svc.apiVersions = Object.keys(svc.services).sort(); - }, - - /** + */addVersions:function addVersions(svc,versions){if(!Array.isArray(versions))versions=[versions];svc.services=svc.services||{};for(var i=0;i= 0) { - this.config.stsRegionalEndpoints = configValue.toLowerCase(); - return; - } else { - throw AWS.util.error(new Error(), errorOptions); - } - }, - - /** - * @api private - */ - validateRegionalEndpointsFlag: function validateRegionalEndpointsFlag() { - //validate config value - var config = this.config; - if (config.stsRegionalEndpoints) { - this.validateRegionalEndpointsFlagValue(config.stsRegionalEndpoints, { - code: 'InvalidConfiguration', - message: 'invalid "stsRegionalEndpoints" configuration. Expect "legacy" ' + - ' or "regional". Got "' + config.stsRegionalEndpoints + '".' - }); - } - if (!AWS.util.isNode()) return; - //validate environmental variable - if (Object.prototype.hasOwnProperty.call(process.env, ENV_REGIONAL_ENDPOINT_ENABLED)) { - var envFlag = process.env[ENV_REGIONAL_ENDPOINT_ENABLED]; - this.validateRegionalEndpointsFlagValue(envFlag, { - code: 'InvalidEnvironmentalVariable', - message: 'invalid ' + ENV_REGIONAL_ENDPOINT_ENABLED + ' environmental variable. Expect "legacy" ' + - ' or "regional". Got "' + process.env[ENV_REGIONAL_ENDPOINT_ENABLED] + '".' - }); - } - //validate shared config file - var profile = {}; - try { - var profiles = AWS.util.getProfilesFromSharedConfig(AWS.util.iniLoader); - profile = profiles[process.env.AWS_PROFILE || AWS.util.defaultProfile]; - } catch (e) {}; - if (profile && Object.prototype.hasOwnProperty.call(profile, CONFIG_REGIONAL_ENDPOINT_ENABLED)) { - var fileFlag = profile[CONFIG_REGIONAL_ENDPOINT_ENABLED]; - this.validateRegionalEndpointsFlagValue(fileFlag, { - code: 'InvalidConfiguration', - message: 'invalid '+CONFIG_REGIONAL_ENDPOINT_ENABLED+' profile config. Expect "legacy" ' + - ' or "regional". Got "' + profile[CONFIG_REGIONAL_ENDPOINT_ENABLED] + '".' - }); - } - }, - - /** - * @api private - */ - optInRegionalEndpoint: function optInRegionalEndpoint() { - this.validateRegionalEndpointsFlag(); - var config = this.config; - if (config.stsRegionalEndpoints === 'regional') { - regionConfig(this); - if (!this.isGlobalEndpoint) return; - this.isGlobalEndpoint = false; - //client will throw if region is not supplied; request will be signed with specified region - if (!config.region) { - throw AWS.util.error(new Error(), - {code: 'ConfigError', message: 'Missing region in config'}); - } - var insertPoint = config.endpoint.indexOf('.amazonaws.com'); - config.endpoint = config.endpoint.substring(0, insertPoint) + - '.' + config.region + config.endpoint.substring(insertPoint); - } - }, - - validateService: function validateService() { - this.optInRegionalEndpoint(); - } - -}); - -}).call(this)}).call(this,require('_process')) -},{"../core":18,"../region_config":53,"_process":86}],62:[function(require,module,exports){ -var AWS = require('../core'); -var inherit = AWS.util.inherit; - -/** - * @api private - */ -var expiresHeader = 'presigned-expires'; - -/** - * @api private - */ -function signedUrlBuilder(request) { - var expires = request.httpRequest.headers[expiresHeader]; - var signerClass = request.service.getSignerClass(request); - - delete request.httpRequest.headers['User-Agent']; - delete request.httpRequest.headers['X-Amz-User-Agent']; - - if (signerClass === AWS.Signers.V4) { - if (expires > 604800) { // one week expiry is invalid - var message = 'Presigning does not support expiry time greater ' + - 'than a week with SigV4 signing.'; - throw AWS.util.error(new Error(), { - code: 'InvalidExpiryTime', message: message, retryable: false - }); - } - request.httpRequest.headers[expiresHeader] = expires; - } else if (signerClass === AWS.Signers.S3) { - var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate(); - request.httpRequest.headers[expiresHeader] = parseInt( - AWS.util.date.unixTimestamp(now) + expires, 10).toString(); - } else { - throw AWS.util.error(new Error(), { - message: 'Presigning only supports S3 or SigV4 signing.', - code: 'UnsupportedSigner', retryable: false - }); - } -} - -/** - * @api private - */ -function signedUrlSigner(request) { - var endpoint = request.httpRequest.endpoint; - var parsedUrl = AWS.util.urlParse(request.httpRequest.path); - var queryParams = {}; - - if (parsedUrl.search) { - queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1)); - } - - var auth = request.httpRequest.headers['Authorization'].split(' '); - if (auth[0] === 'AWS') { - auth = auth[1].split(':'); - queryParams['AWSAccessKeyId'] = auth[0]; - queryParams['Signature'] = auth[1]; - - AWS.util.each(request.httpRequest.headers, function (key, value) { - if (key === expiresHeader) key = 'Expires'; - if (key.indexOf('x-amz-meta-') === 0) { - // Delete existing, potentially not normalized key - delete queryParams[key]; - key = key.toLowerCase(); - } - queryParams[key] = value; - }); - delete request.httpRequest.headers[expiresHeader]; - delete queryParams['Authorization']; - delete queryParams['Host']; - } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing - auth.shift(); - var rest = auth.join(' '); - var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1]; - queryParams['X-Amz-Signature'] = signature; - delete queryParams['Expires']; - } - - // build URL - endpoint.pathname = parsedUrl.pathname; - endpoint.search = AWS.util.queryParamsToString(queryParams); -} - -/** - * @api private - */ -AWS.Signers.Presign = inherit({ - /** - * @api private - */ - sign: function sign(request, expireTime, callback) { - request.httpRequest.headers[expiresHeader] = expireTime || 3600; - request.on('build', signedUrlBuilder); - request.on('sign', signedUrlSigner); - request.removeListener('afterBuild', - AWS.EventListeners.Core.SET_CONTENT_LENGTH); - request.removeListener('afterBuild', - AWS.EventListeners.Core.COMPUTE_SHA256); - - request.emit('beforePresign', [request]); - - if (callback) { - request.build(function() { - if (this.response.error) callback(this.response.error); - else { - callback(null, AWS.util.urlFormat(request.httpRequest.endpoint)); - } - }); - } else { - request.build(); - if (request.response.error) throw request.response.error; - return AWS.util.urlFormat(request.httpRequest.endpoint); - } - } -}); - -/** - * @api private - */ -module.exports = AWS.Signers.Presign; - -},{"../core":18}],63:[function(require,module,exports){ -var AWS = require('../core'); - -var inherit = AWS.util.inherit; - -/** - * @api private - */ -AWS.Signers.RequestSigner = inherit({ - constructor: function RequestSigner(request) { - this.request = request; - }, - - setServiceClientId: function setServiceClientId(id) { - this.serviceClientId = id; - }, - - getServiceClientId: function getServiceClientId() { - return this.serviceClientId; - } -}); - -AWS.Signers.RequestSigner.getVersion = function getVersion(version) { - switch (version) { - case 'v2': return AWS.Signers.V2; - case 'v3': return AWS.Signers.V3; - case 's3v4': return AWS.Signers.V4; - case 'v4': return AWS.Signers.V4; - case 's3': return AWS.Signers.S3; - case 'v3https': return AWS.Signers.V3Https; - } - throw new Error('Unknown signing version ' + version); -}; - -require('./v2'); -require('./v3'); -require('./v3https'); -require('./v4'); -require('./s3'); -require('./presign'); - -},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(require,module,exports){ -var AWS = require('../core'); -var inherit = AWS.util.inherit; - -/** - * @api private - */ -AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, { - /** - * When building the stringToSign, these sub resource params should be - * part of the canonical resource string with their NON-decoded values - */ - 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 - }, - - // when building the stringToSign, these querystring params should be - // part of the canonical resource string with their NON-encoded values - 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 addAuthorization(credentials, date) { - if (!this.request.headers['presigned-expires']) { - this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date); - } - - if (credentials.sessionToken) { - // presigned URLs require this header to be lowercased - this.request.headers['x-amz-security-token'] = credentials.sessionToken; - } - - var signature = this.sign(credentials.secretAccessKey, this.stringToSign()); - var auth = 'AWS ' + credentials.accessKeyId + ':' + signature; - - this.request.headers['Authorization'] = auth; - }, - - stringToSign: function stringToSign() { - var r = this.request; - - var parts = []; - parts.push(r.method); - parts.push(r.headers['Content-MD5'] || ''); - parts.push(r.headers['Content-Type'] || ''); - - // This is the "Date" header, but we use X-Amz-Date. - // The S3 signing mechanism requires us to pass an empty - // string for this Date header regardless. - parts.push(r.headers['presigned-expires'] || ''); - - var headers = this.canonicalizedAmzHeaders(); - if (headers) parts.push(headers); - parts.push(this.canonicalizedResource()); - - return parts.join('\n'); - - }, - - canonicalizedAmzHeaders: function canonicalizedAmzHeaders() { - - var amzHeaders = []; - - AWS.util.each(this.request.headers, function (name) { - if (name.match(/^x-amz-/i)) - amzHeaders.push(name); - }); - - amzHeaders.sort(function (a, b) { - return a.toLowerCase() < b.toLowerCase() ? -1 : 1; - }); - - var parts = []; - AWS.util.arrayEach.call(this, amzHeaders, function (name) { - parts.push(name.toLowerCase() + ':' + String(this.request.headers[name])); - }); - - return parts.join('\n'); - - }, - - canonicalizedResource: function canonicalizedResource() { - - var r = this.request; - - var parts = r.path.split('?'); - var path = parts[0]; - var querystring = parts[1]; - - var resource = ''; - - if (r.virtualHostedBucket) - resource += '/' + r.virtualHostedBucket; - - resource += path; - - if (querystring) { - - // collect a list of sub resources and query params that need to be signed - var resources = []; - - AWS.util.arrayEach.call(this, querystring.split('&'), function (param) { - var name = param.split('=')[0]; - var value = param.split('=')[1]; - if (this.subResources[name] || this.responseHeaders[name]) { - var subresource = { name: name }; - if (value !== undefined) { - if (this.subResources[name]) { - subresource.value = value; - } else { - subresource.value = decodeURIComponent(value); - } - } - resources.push(subresource); - } - }); - - resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; }); - - if (resources.length) { - - querystring = []; - AWS.util.arrayEach(resources, function (res) { - if (res.value === undefined) { - querystring.push(res.name); - } else { - querystring.push(res.name + '=' + res.value); - } - }); - - resource += '?' + querystring.join('&'); - } - - } - - return resource; - - }, - - sign: function sign(secret, string) { - return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1'); - } -}); - -/** - * @api private - */ -module.exports = AWS.Signers.S3; - -},{"../core":18}],65:[function(require,module,exports){ -var AWS = require('../core'); -var inherit = AWS.util.inherit; - -/** - * @api private - */ -AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, { - addAuthorization: function addAuthorization(credentials, date) { - - if (!date) date = AWS.util.date.getDate(); - - var r = this.request; - - r.params.Timestamp = AWS.util.date.iso8601(date); - r.params.SignatureVersion = '2'; - r.params.SignatureMethod = 'HmacSHA256'; - r.params.AWSAccessKeyId = credentials.accessKeyId; - - if (credentials.sessionToken) { - r.params.SecurityToken = credentials.sessionToken; - } - - delete r.params.Signature; // delete old Signature for re-signing - r.params.Signature = this.signature(credentials); - - r.body = AWS.util.queryParamsToString(r.params); - r.headers['Content-Length'] = r.body.length; - }, - - signature: function signature(credentials) { - return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64'); - }, - - stringToSign: function stringToSign() { - var parts = []; - parts.push(this.request.method); - parts.push(this.request.endpoint.host.toLowerCase()); - parts.push(this.request.pathname()); - parts.push(AWS.util.queryParamsToString(this.request.params)); - return parts.join('\n'); - } - -}); - -/** - * @api private - */ -module.exports = AWS.Signers.V2; - -},{"../core":18}],66:[function(require,module,exports){ -var AWS = require('../core'); -var inherit = AWS.util.inherit; - -/** - * @api private - */ -AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, { - addAuthorization: function addAuthorization(credentials, date) { - - var datetime = AWS.util.date.rfc822(date); - - this.request.headers['X-Amz-Date'] = datetime; - - if (credentials.sessionToken) { - this.request.headers['x-amz-security-token'] = credentials.sessionToken; - } - - this.request.headers['X-Amzn-Authorization'] = - this.authorization(credentials, datetime); - - }, - - authorization: function authorization(credentials) { - return 'AWS3 ' + - 'AWSAccessKeyId=' + credentials.accessKeyId + ',' + - 'Algorithm=HmacSHA256,' + - 'SignedHeaders=' + this.signedHeaders() + ',' + - 'Signature=' + this.signature(credentials); - }, - - signedHeaders: function signedHeaders() { - var headers = []; - AWS.util.arrayEach(this.headersToSign(), function iterator(h) { - headers.push(h.toLowerCase()); - }); - return headers.sort().join(';'); - }, - - canonicalHeaders: function canonicalHeaders() { - var headers = this.request.headers; - var parts = []; - AWS.util.arrayEach(this.headersToSign(), function iterator(h) { - parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim()); - }); - return parts.sort().join('\n') + '\n'; - }, - - headersToSign: function headersToSign() { - var headers = []; - AWS.util.each(this.request.headers, function iterator(k) { - if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) { - headers.push(k); - } - }); - return headers; - }, - - signature: function signature(credentials) { - return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64'); - }, - - stringToSign: function stringToSign() { - var parts = []; - parts.push(this.request.method); - parts.push('/'); - parts.push(''); - parts.push(this.canonicalHeaders()); - parts.push(this.request.body); - return AWS.util.crypto.sha256(parts.join('\n')); - } - -}); - -/** - * @api private - */ -module.exports = AWS.Signers.V3; - -},{"../core":18}],67:[function(require,module,exports){ -var AWS = require('../core'); -var inherit = AWS.util.inherit; - -require('./v3'); - -/** - * @api private - */ -AWS.Signers.V3Https = inherit(AWS.Signers.V3, { - authorization: function authorization(credentials) { - return 'AWS3-HTTPS ' + - 'AWSAccessKeyId=' + credentials.accessKeyId + ',' + - 'Algorithm=HmacSHA256,' + - 'Signature=' + this.signature(credentials); - }, - - stringToSign: function stringToSign() { - return this.request.headers['X-Amz-Date']; - } -}); - -/** - * @api private - */ -module.exports = AWS.Signers.V3Https; - -},{"../core":18,"./v3":66}],68:[function(require,module,exports){ -var AWS = require('../core'); -var v4Credentials = require('./v4_credentials'); -var inherit = AWS.util.inherit; - -/** - * @api private - */ -var expiresHeader = 'presigned-expires'; - -/** - * @api private - */ -AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { - constructor: function V4(request, serviceName, options) { - AWS.Signers.RequestSigner.call(this, request); - this.serviceName = serviceName; - options = options || {}; - this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true; - this.operation = options.operation; - this.signatureVersion = options.signatureVersion; - }, - - algorithm: 'AWS4-HMAC-SHA256', - - addAuthorization: function addAuthorization(credentials, date) { - var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, ''); - - if (this.isPresigned()) { - this.updateForPresigned(credentials, datetime); - } else { - this.addHeaders(credentials, datetime); - } - - this.request.headers['Authorization'] = - this.authorization(credentials, datetime); - }, - - addHeaders: function addHeaders(credentials, datetime) { - this.request.headers['X-Amz-Date'] = datetime; - if (credentials.sessionToken) { - this.request.headers['x-amz-security-token'] = credentials.sessionToken; - } - }, - - updateForPresigned: function updateForPresigned(credentials, datetime) { - var credString = this.credentialString(datetime); - var qs = { - 'X-Amz-Date': datetime, - 'X-Amz-Algorithm': this.algorithm, - 'X-Amz-Credential': credentials.accessKeyId + '/' + credString, - 'X-Amz-Expires': this.request.headers[expiresHeader], - 'X-Amz-SignedHeaders': this.signedHeaders() - }; - - if (credentials.sessionToken) { - qs['X-Amz-Security-Token'] = credentials.sessionToken; - } - - if (this.request.headers['Content-Type']) { - qs['Content-Type'] = this.request.headers['Content-Type']; - } - if (this.request.headers['Content-MD5']) { - qs['Content-MD5'] = this.request.headers['Content-MD5']; - } - if (this.request.headers['Cache-Control']) { - qs['Cache-Control'] = this.request.headers['Cache-Control']; - } - - // need to pull in any other X-Amz-* headers - AWS.util.each.call(this, this.request.headers, function(key, value) { - if (key === expiresHeader) return; - if (this.isSignableHeader(key)) { - var lowerKey = key.toLowerCase(); - // Metadata should be normalized - if (lowerKey.indexOf('x-amz-meta-') === 0) { - qs[lowerKey] = value; - } else if (lowerKey.indexOf('x-amz-') === 0) { - qs[key] = value; - } - } - }); - - var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?'; - this.request.path += sep + AWS.util.queryParamsToString(qs); - }, - - authorization: function authorization(credentials, datetime) { - var parts = []; - var credString = this.credentialString(datetime); - parts.push(this.algorithm + ' Credential=' + - credentials.accessKeyId + '/' + credString); - parts.push('SignedHeaders=' + this.signedHeaders()); - parts.push('Signature=' + this.signature(credentials, datetime)); - return parts.join(', '); - }, - - signature: function signature(credentials, datetime) { - var signingKey = v4Credentials.getSigningKey( - credentials, - datetime.substr(0, 8), - this.request.region, - this.serviceName, - this.signatureCache - ); - return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex'); - }, - - stringToSign: function stringToSign(datetime) { - var parts = []; - parts.push('AWS4-HMAC-SHA256'); - parts.push(datetime); - parts.push(this.credentialString(datetime)); - parts.push(this.hexEncodedHash(this.canonicalString())); - return parts.join('\n'); - }, - - canonicalString: function canonicalString() { - var parts = [], pathname = this.request.pathname(); - if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname); - - parts.push(this.request.method); - parts.push(pathname); - parts.push(this.request.search()); - parts.push(this.canonicalHeaders() + '\n'); - parts.push(this.signedHeaders()); - parts.push(this.hexEncodedBodyHash()); - return parts.join('\n'); - }, - - canonicalHeaders: function canonicalHeaders() { - var headers = []; - AWS.util.each.call(this, this.request.headers, function (key, item) { - headers.push([key, item]); - }); - headers.sort(function (a, b) { - return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1; - }); - var parts = []; - AWS.util.arrayEach.call(this, headers, function (item) { - var key = item[0].toLowerCase(); - if (this.isSignableHeader(key)) { - var value = item[1]; - if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') { - throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), { - code: 'InvalidHeader' - }); - } - parts.push(key + ':' + - this.canonicalHeaderValues(value.toString())); - } - }); - return parts.join('\n'); - }, - - canonicalHeaderValues: function canonicalHeaderValues(values) { - return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, ''); - }, - - signedHeaders: function signedHeaders() { - var keys = []; - AWS.util.each.call(this, this.request.headers, function (key) { - key = key.toLowerCase(); - if (this.isSignableHeader(key)) keys.push(key); - }); - return keys.sort().join(';'); - }, - - credentialString: function credentialString(datetime) { - return v4Credentials.createScope( - datetime.substr(0, 8), - this.request.region, - this.serviceName - ); - }, - - hexEncodedHash: function hash(string) { - return AWS.util.crypto.sha256(string, 'hex'); - }, - - hexEncodedBodyHash: function hexEncodedBodyHash() { - var request = this.request; - if (this.isPresigned() && this.serviceName === 's3' && !request.body) { - return 'UNSIGNED-PAYLOAD'; - } else if (request.headers['X-Amz-Content-Sha256']) { - return request.headers['X-Amz-Content-Sha256']; - } else { - return this.hexEncodedHash(this.request.body || ''); - } - }, - - unsignableHeaders: [ - 'authorization', - 'content-type', - 'content-length', - 'user-agent', - expiresHeader, - 'expect', - 'x-amzn-trace-id' - ], - - isSignableHeader: function isSignableHeader(key) { - if (key.toLowerCase().indexOf('x-amz-') === 0) return true; - return this.unsignableHeaders.indexOf(key) < 0; - }, - - isPresigned: function isPresigned() { - return this.request.headers[expiresHeader] ? true : false; - } - -}); - -/** - * @api private - */ -module.exports = AWS.Signers.V4; - -},{"../core":18,"./v4_credentials":69}],69:[function(require,module,exports){ -var AWS = require('../core'); - -/** - * @api private - */ -var cachedSecret = {}; - -/** - * @api private - */ -var cacheQueue = []; - -/** - * @api private - */ -var maxCacheEntries = 50; - -/** - * @api private - */ -var v4Identifier = 'aws4_request'; - -/** - * @api private - */ -module.exports = { - /** - * @api private - * - * @param date [String] - * @param region [String] - * @param serviceName [String] - * @return [String] - */ - createScope: function createScope(date, region, serviceName) { - return [ - date.substr(0, 8), - region, - serviceName, - v4Identifier - ].join('/'); - }, - - /** - * @api private - * - * @param credentials [Credentials] - * @param date [String] - * @param region [String] - * @param service [String] - * @param shouldCache [Boolean] - * @return [String] - */ - getSigningKey: function getSigningKey( - credentials, - date, - region, - service, - shouldCache - ) { - var credsIdentifier = AWS.util.crypto - .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64'); - var cacheKey = [credsIdentifier, date, region, service].join('_'); - shouldCache = shouldCache !== false; - if (shouldCache && (cacheKey in cachedSecret)) { - return cachedSecret[cacheKey]; - } - - var kDate = AWS.util.crypto.hmac( - 'AWS4' + credentials.secretAccessKey, - date, - 'buffer' - ); - var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer'); - var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer'); - - var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer'); - if (shouldCache) { - cachedSecret[cacheKey] = signingKey; - cacheQueue.push(cacheKey); - if (cacheQueue.length > maxCacheEntries) { - // remove the oldest entry (not the least recently used) - delete cachedSecret[cacheQueue.shift()]; - } - } - - return signingKey; - }, - - /** - * @api private - * - * Empties the derived signing key cache. Made available for testing purposes - * only. - */ - emptyCache: function emptyCache() { - cachedSecret = {}; - cacheQueue = []; - } -}; - -},{"../core":18}],70:[function(require,module,exports){ -function AcceptorStateMachine(states, state) { - this.currentState = state || null; - this.states = states || {}; -} - -AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) { - if (typeof finalState === 'function') { - inputError = bindObject; bindObject = done; - done = finalState; finalState = null; - } - - var self = this; - var state = self.states[self.currentState]; - state.fn.call(bindObject || self, inputError, function(err) { - if (err) { - if (state.fail) self.currentState = state.fail; - else return done ? done.call(bindObject, err) : null; - } else { - if (state.accept) self.currentState = state.accept; - else return done ? done.call(bindObject) : null; - } - if (self.currentState === finalState) { - return done ? done.call(bindObject, err) : null; - } - - self.runTo(finalState, done, bindObject, err); - }); -}; - -AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) { - if (typeof acceptState === 'function') { - fn = acceptState; acceptState = null; failState = null; - } else if (typeof failState === 'function') { - fn = failState; failState = null; - } - - if (!this.currentState) this.currentState = name; - this.states[name] = { accept: acceptState, fail: failState, fn: fn }; - return this; -}; - -/** - * @api private - */ -module.exports = AcceptorStateMachine; - -},{}],71:[function(require,module,exports){ -(function (process,setImmediate){(function (){ -/* eslint guard-for-in:0 */ -var AWS; - -/** - * A set of utility methods for use with the AWS SDK. - * - * @!attribute abort - * Return this value from an iterator function {each} or {arrayEach} - * to break out of the iteration. - * @example Breaking out of an iterator function - * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) { - * if (key == 'b') return AWS.util.abort; - * }); - * @see each - * @see arrayEach - * @api private - */ -var util = { - environment: 'nodejs', - engine: function engine() { - if (util.isBrowser() && typeof navigator !== 'undefined') { - return navigator.userAgent; - } else { - var engine = process.platform + '/' + process.version; - if (process.env.AWS_EXECUTION_ENV) { - engine += ' exec-env/' + process.env.AWS_EXECUTION_ENV; - } - return engine; - } - }, - - userAgent: function userAgent() { - var name = util.environment; - var agent = 'aws-sdk-' + name + '/' + require('./core').VERSION; - if (name === 'nodejs') agent += ' ' + util.engine(); - return agent; - }, - - uriEscape: function uriEscape(string) { - var output = encodeURIComponent(string); - output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape); - - // AWS percent-encodes some extra non-standard characters in a URI - output = output.replace(/[*]/g, function(ch) { - return '%' + ch.charCodeAt(0).toString(16).toUpperCase(); - }); - - return output; - }, - - uriEscapePath: function uriEscapePath(string) { - var parts = []; - util.arrayEach(string.split('/'), function (part) { - parts.push(util.uriEscape(part)); - }); - return parts.join('/'); - }, - - urlParse: function urlParse(url) { - return util.url.parse(url); - }, - - urlFormat: function urlFormat(url) { - return util.url.format(url); - }, - - queryStringParse: function queryStringParse(qs) { - return util.querystring.parse(qs); - }, - - queryParamsToString: function queryParamsToString(params) { - var items = []; - var escape = util.uriEscape; - var sortedKeys = Object.keys(params).sort(); - - util.arrayEach(sortedKeys, function(name) { - var value = params[name]; - var ename = escape(name); - var result = ename + '='; - if (Array.isArray(value)) { - var vals = []; - util.arrayEach(value, function(item) { vals.push(escape(item)); }); - result = ename + '=' + vals.sort().join('&' + ename + '='); - } else if (value !== undefined && value !== null) { - result = ename + '=' + escape(value); - } - items.push(result); - }); - - return items.join('&'); - }, - - readFileSync: function readFileSync(path) { - if (util.isBrowser()) return null; - return require('fs').readFileSync(path, 'utf-8'); - }, - - base64: { - encode: function encode64(string) { - if (typeof string === 'number') { - throw util.error(new Error('Cannot base64 encode number ' + string)); - } - if (string === null || typeof string === 'undefined') { - return string; - } - var buf = util.buffer.toBuffer(string); - return buf.toString('base64'); - }, - - decode: function decode64(string) { - if (typeof string === 'number') { - throw util.error(new Error('Cannot base64 decode number ' + string)); - } - if (string === null || typeof string === 'undefined') { - return string; - } - return util.buffer.toBuffer(string, 'base64'); - } - - }, - - buffer: { - /** - * Buffer constructor for Node buffer and buffer pollyfill - */ - toBuffer: function(data, encoding) { - return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? - util.Buffer.from(data, encoding) : new util.Buffer(data, encoding); - }, - - alloc: function(size, fill, encoding) { - if (typeof size !== 'number') { - throw new Error('size passed to alloc must be a number.'); - } - if (typeof util.Buffer.alloc === 'function') { - return util.Buffer.alloc(size, fill, encoding); - } else { - var buf = new util.Buffer(size); - if (fill !== undefined && typeof buf.fill === 'function') { - buf.fill(fill, undefined, undefined, encoding); - } - return buf; - } - }, - - toStream: function toStream(buffer) { - if (!util.Buffer.isBuffer(buffer)) buffer = util.buffer.toBuffer(buffer); - - var readable = new (util.stream.Readable)(); - var pos = 0; - readable._read = function(size) { - if (pos >= buffer.length) return readable.push(null); - - var end = pos + size; - if (end > buffer.length) end = buffer.length; - readable.push(buffer.slice(pos, end)); - pos = end; - }; - - return readable; - }, - - /** - * Concatenates a list of Buffer objects. - */ - concat: function(buffers) { - var length = 0, - offset = 0, - buffer = null, i; - - for (i = 0; i < buffers.length; i++) { - length += buffers[i].length; - } - - buffer = util.buffer.alloc(length); - - for (i = 0; i < buffers.length; i++) { - buffers[i].copy(buffer, offset); - offset += buffers[i].length; - } - - return buffer; - } - }, - - string: { - byteLength: function byteLength(string) { - if (string === null || string === undefined) return 0; - if (typeof string === 'string') string = util.buffer.toBuffer(string); - - if (typeof string.byteLength === 'number') { - return string.byteLength; - } else if (typeof string.length === 'number') { - return string.length; - } else if (typeof string.size === 'number') { - return string.size; - } else if (typeof string.path === 'string') { - return require('fs').lstatSync(string.path).size; - } else { - throw util.error(new Error('Cannot determine length of ' + string), - { object: string }); - } - }, - - upperFirst: function upperFirst(string) { - return string[0].toUpperCase() + string.substr(1); - }, - - lowerFirst: function lowerFirst(string) { - return string[0].toLowerCase() + string.substr(1); - } - }, - - ini: { - parse: function string(ini) { - var currentSection, map = {}; - util.arrayEach(ini.split(/\r?\n/), function(line) { - line = line.split(/(^|\s)[;#]/)[0]; // remove comments - var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/); - if (section) { - currentSection = section[1]; - } else if (currentSection) { - var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); - if (item) { - map[currentSection] = map[currentSection] || {}; - map[currentSection][item[1]] = item[2]; - } - } - }); - - return map; - } - }, - - fn: { - noop: function() {}, - callback: function (err) { if (err) throw err; }, - - /** - * Turn a synchronous function into as "async" function by making it call - * a callback. The underlying function is called with all but the last argument, - * which is treated as the callback. The callback is passed passed a first argument - * of null on success to mimick standard node callbacks. - */ - makeAsync: function makeAsync(fn, expectedArgs) { - if (expectedArgs && expectedArgs <= fn.length) { - return fn; - } - - return function() { - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - var result = fn.apply(null, args); - callback(result); - }; - } - }, - - /** - * Date and time utility functions. - */ - date: { - - /** - * @return [Date] the current JavaScript date object. Since all - * AWS services rely on this date object, you can override - * this function to provide a special time value to AWS service - * requests. - */ - getDate: function getDate() { - if (!AWS) AWS = require('./core'); - if (AWS.config.systemClockOffset) { // use offset when non-zero - return new Date(new Date().getTime() + AWS.config.systemClockOffset); - } else { - return new Date(); - } - }, - - /** - * @return [String] the date in ISO-8601 format - */ - iso8601: function iso8601(date) { - if (date === undefined) { date = util.date.getDate(); } - return date.toISOString().replace(/\.\d{3}Z$/, 'Z'); - }, - - /** - * @return [String] the date in RFC 822 format - */ - rfc822: function rfc822(date) { - if (date === undefined) { date = util.date.getDate(); } - return date.toUTCString(); - }, - - /** - * @return [Integer] the UNIX timestamp value for the current time - */ - unixTimestamp: function unixTimestamp(date) { - if (date === undefined) { date = util.date.getDate(); } - return date.getTime() / 1000; - }, - - /** - * @param [String,number,Date] date - * @return [Date] - */ - from: function format(date) { - if (typeof date === 'number') { - return new Date(date * 1000); // unix timestamp - } else { - return new Date(date); - } - }, - - /** - * Given a Date or date-like value, this function formats the - * date into a string of the requested value. - * @param [String,number,Date] date - * @param [String] formatter Valid formats are: - # * 'iso8601' - # * 'rfc822' - # * 'unixTimestamp' - * @return [String] - */ - format: function format(date, formatter) { - if (!formatter) formatter = 'iso8601'; - return util.date[formatter](util.date.from(date)); - }, - - parseTimestamp: function parseTimestamp(value) { - if (typeof value === 'number') { // unix timestamp (number) - return new Date(value * 1000); - } else if (value.match(/^\d+$/)) { // unix timestamp - return new Date(value * 1000); - } else if (value.match(/^\d{4}/)) { // iso8601 - return new Date(value); - } else if (value.match(/^\w{3},/)) { // rfc822 - return new Date(value); - } else { - throw util.error( - new Error('unhandled timestamp format: ' + value), - {code: 'TimestampParserError'}); - } - } - - }, - - crypto: { - crc32Table: [ - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D], - - crc32: function crc32(data) { - var tbl = util.crypto.crc32Table; - var crc = 0 ^ -1; - - if (typeof data === 'string') { - data = util.buffer.toBuffer(data); - } - - for (var i = 0; i < data.length; i++) { - var code = data.readUInt8(i); - crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF]; - } - return (crc ^ -1) >>> 0; - }, - - hmac: function hmac(key, string, digest, fn) { - if (!digest) digest = 'binary'; - if (digest === 'buffer') { digest = undefined; } - if (!fn) fn = 'sha256'; - if (typeof string === 'string') string = util.buffer.toBuffer(string); - return util.crypto.lib.createHmac(fn, key).update(string).digest(digest); - }, - - md5: function md5(data, digest, callback) { - return util.crypto.hash('md5', data, digest, callback); - }, - - sha256: function sha256(data, digest, callback) { - return util.crypto.hash('sha256', data, digest, callback); - }, - - hash: function(algorithm, data, digest, callback) { - var hash = util.crypto.createHash(algorithm); - if (!digest) { digest = 'binary'; } - if (digest === 'buffer') { digest = undefined; } - if (typeof data === 'string') data = util.buffer.toBuffer(data); - var sliceFn = util.arraySliceFn(data); - var isBuffer = util.Buffer.isBuffer(data); - //Identifying objects with an ArrayBuffer as buffers - if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true; - - if (callback && typeof data === 'object' && - typeof data.on === 'function' && !isBuffer) { - data.on('data', function(chunk) { hash.update(chunk); }); - data.on('error', function(err) { callback(err); }); - data.on('end', function() { callback(null, hash.digest(digest)); }); - } else if (callback && sliceFn && !isBuffer && - typeof FileReader !== 'undefined') { - // this might be a File/Blob - var index = 0, size = 1024 * 512; - var reader = new FileReader(); - reader.onerror = function() { - callback(new Error('Failed to read data.')); - }; - reader.onload = function() { - var buf = new util.Buffer(new Uint8Array(reader.result)); - hash.update(buf); - index += buf.length; - reader._continueReading(); - }; - reader._continueReading = function() { - if (index >= data.size) { - callback(null, hash.digest(digest)); - return; - } - - var back = index + size; - if (back > data.size) back = data.size; - reader.readAsArrayBuffer(sliceFn.call(data, index, back)); - }; - - reader._continueReading(); - } else { - if (util.isBrowser() && typeof data === 'object' && !isBuffer) { - data = new util.Buffer(new Uint8Array(data)); - } - var out = hash.update(data).digest(digest); - if (callback) callback(null, out); - return out; - } - }, - - toHex: function toHex(data) { - var out = []; - for (var i = 0; i < data.length; i++) { - out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2)); - } - return out.join(''); - }, - - createHash: function createHash(algorithm) { - return util.crypto.lib.createHash(algorithm); - } - - }, - - /** @!ignore */ - - /* Abort constant */ - abort: {}, - - each: function each(object, iterFunction) { - for (var key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - var ret = iterFunction.call(this, key, object[key]); - if (ret === util.abort) break; - } - } - }, - - arrayEach: function arrayEach(array, iterFunction) { - for (var idx in array) { - if (Object.prototype.hasOwnProperty.call(array, idx)) { - var ret = iterFunction.call(this, array[idx], parseInt(idx, 10)); - if (ret === util.abort) break; - } - } - }, - - update: function update(obj1, obj2) { - util.each(obj2, function iterator(key, item) { - obj1[key] = item; - }); - return obj1; - }, - - merge: function merge(obj1, obj2) { - return util.update(util.copy(obj1), obj2); - }, - - copy: function copy(object) { - if (object === null || object === undefined) return object; - var dupe = {}; - // jshint forin:false - for (var key in object) { - dupe[key] = object[key]; - } - return dupe; - }, - - isEmpty: function isEmpty(obj) { - for (var prop in obj) { - if (Object.prototype.hasOwnProperty.call(obj, prop)) { - return false; - } - } - return true; - }, - - arraySliceFn: function arraySliceFn(obj) { - var fn = obj.slice || obj.webkitSlice || obj.mozSlice; - return typeof fn === 'function' ? fn : null; - }, - - isType: function isType(obj, type) { - // handle cross-"frame" objects - if (typeof type === 'function') type = util.typeName(type); - return Object.prototype.toString.call(obj) === '[object ' + type + ']'; - }, - - typeName: function typeName(type) { - if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name; - var str = type.toString(); - var match = str.match(/^\s*function (.+)\(/); - return match ? match[1] : str; - }, - - error: function error(err, options) { - var originalError = null; - if (typeof err.message === 'string' && err.message !== '') { - if (typeof options === 'string' || (options && options.message)) { - originalError = util.copy(err); - originalError.message = err.message; - } - } - err.message = err.message || null; - - if (typeof options === 'string') { - err.message = options; - } else if (typeof options === 'object' && options !== null) { - util.update(err, options); - if (options.message) - err.message = options.message; - if (options.code || options.name) - err.code = options.code || options.name; - if (options.stack) - err.stack = options.stack; - } - - if (typeof Object.defineProperty === 'function') { - Object.defineProperty(err, 'name', {writable: true, enumerable: false}); - Object.defineProperty(err, 'message', {enumerable: true}); - } - - err.name = options && options.name || err.name || err.code || 'Error'; - err.time = new Date(); - - if (originalError) err.originalError = originalError; - - return err; - }, - - /** - * @api private - */ - inherit: function inherit(klass, features) { - var newObject = null; - if (features === undefined) { - features = klass; - klass = Object; - newObject = {}; - } else { - var ctor = function ConstructorWrapper() {}; - ctor.prototype = klass.prototype; - newObject = new ctor(); - } - - // constructor not supplied, create pass-through ctor - if (features.constructor === Object) { - features.constructor = function() { - if (klass !== Object) { - return klass.apply(this, arguments); - } - }; - } - - features.constructor.prototype = newObject; - util.update(features.constructor.prototype, features); - features.constructor.__super__ = klass; - return features.constructor; - }, - - /** - * @api private - */ - mixin: function mixin() { - var klass = arguments[0]; - for (var i = 1; i < arguments.length; i++) { - // jshint forin:false - for (var prop in arguments[i].prototype) { - var fn = arguments[i].prototype[prop]; - if (prop !== 'constructor') { - klass.prototype[prop] = fn; - } - } - } - return klass; - }, - - /** - * @api private - */ - hideProperties: function hideProperties(obj, props) { - if (typeof Object.defineProperty !== 'function') return; - - util.arrayEach(props, function (key) { - Object.defineProperty(obj, key, { - enumerable: false, writable: true, configurable: true }); - }); - }, - - /** - * @api private - */ - property: function property(obj, name, value, enumerable, isValue) { - var opts = { - configurable: true, - enumerable: enumerable !== undefined ? enumerable : true - }; - if (typeof value === 'function' && !isValue) { - opts.get = value; - } - else { - opts.value = value; opts.writable = true; - } - - Object.defineProperty(obj, name, opts); - }, - - /** - * @api private - */ - memoizedProperty: function memoizedProperty(obj, name, get, enumerable) { - var cachedValue = null; - - // build enumerable attribute for each value with lazy accessor. - util.property(obj, name, function() { - if (cachedValue === null) { - cachedValue = get(); - } - return cachedValue; - }, enumerable); - }, - - /** - * TODO Remove in major version revision - * This backfill populates response data without the - * top-level payload name. - * - * @api private - */ - hoistPayloadMember: function hoistPayloadMember(resp) { - var req = resp.request; - var operationName = req.operation; - var operation = req.service.api.operations[operationName]; - var output = operation.output; - if (output.payload && !operation.hasEventOutput) { - var payloadMember = output.members[output.payload]; - var responsePayload = resp.data[output.payload]; - if (payloadMember.type === 'structure') { - util.each(responsePayload, function(key, value) { - util.property(resp.data, key, value, false); - }); - } - } - }, - - /** - * Compute SHA-256 checksums of streams - * - * @api private - */ - computeSha256: function computeSha256(body, done) { - if (util.isNode()) { - var Stream = util.stream.Stream; - var fs = require('fs'); - if (typeof Stream === 'function' && body instanceof Stream) { - if (typeof body.path === 'string') { // assume file object - var settings = {}; - if (typeof body.start === 'number') { - settings.start = body.start; - } - if (typeof body.end === 'number') { - settings.end = body.end; - } - body = fs.createReadStream(body.path, settings); - } else { // TODO support other stream types - return done(new Error('Non-file stream objects are ' + - 'not supported with SigV4')); - } - } - } - - util.crypto.sha256(body, 'hex', function(err, sha) { - if (err) done(err); - else done(null, sha); - }); - }, - - /** - * @api private - */ - isClockSkewed: function isClockSkewed(serverTime) { - if (serverTime) { - util.property(AWS.config, 'isClockSkewed', - Math.abs(new Date().getTime() - serverTime) >= 300000, false); - return AWS.config.isClockSkewed; - } - }, - - applyClockOffset: function applyClockOffset(serverTime) { - if (serverTime) - AWS.config.systemClockOffset = serverTime - new Date().getTime(); - }, - - /** - * @api private - */ - extractRequestId: function extractRequestId(resp) { - var requestId = resp.httpResponse.headers['x-amz-request-id'] || - resp.httpResponse.headers['x-amzn-requestid']; - - if (!requestId && resp.data && resp.data.ResponseMetadata) { - requestId = resp.data.ResponseMetadata.RequestId; - } - - if (requestId) { - resp.requestId = requestId; - } - - if (resp.error) { - resp.error.requestId = requestId; - } - }, - - /** - * @api private - */ - addPromises: function addPromises(constructors, PromiseDependency) { - var deletePromises = false; - if (PromiseDependency === undefined && AWS && AWS.config) { - PromiseDependency = AWS.config.getPromisesDependency(); - } - if (PromiseDependency === undefined && typeof Promise !== 'undefined') { - PromiseDependency = Promise; - } - if (typeof PromiseDependency !== 'function') deletePromises = true; - if (!Array.isArray(constructors)) constructors = [constructors]; - - for (var ind = 0; ind < constructors.length; ind++) { - var constructor = constructors[ind]; - if (deletePromises) { - if (constructor.deletePromisesFromClass) { - constructor.deletePromisesFromClass(); - } - } else if (constructor.addPromisesToClass) { - constructor.addPromisesToClass(PromiseDependency); - } - } - }, - - /** - * @api private - * Return a function that will return a promise whose fate is decided by the - * callback behavior of the given method with `methodName`. The method to be - * promisified should conform to node.js convention of accepting a callback as - * last argument and calling that callback with error as the first argument - * and success value on the second argument. - */ - promisifyMethod: function promisifyMethod(methodName, PromiseDependency) { - return function promise() { - var self = this; - var args = Array.prototype.slice.call(arguments); - return new PromiseDependency(function(resolve, reject) { - args.push(function(err, data) { - if (err) { - reject(err); - } else { - resolve(data); - } - }); - self[methodName].apply(self, args); - }); - }; - }, - - /** - * @api private - */ - isDualstackAvailable: function isDualstackAvailable(service) { - if (!service) return false; - var metadata = require('../apis/metadata.json'); - if (typeof service !== 'string') service = service.serviceIdentifier; - if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false; - return !!metadata[service].dualstackAvailable; - }, - - /** - * @api private - */ - calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) { - if (!retryDelayOptions) retryDelayOptions = {}; - var customBackoff = retryDelayOptions.customBackoff || null; - if (typeof customBackoff === 'function') { - return customBackoff(retryCount); - } - var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100; - var delay = Math.random() * (Math.pow(2, retryCount) * base); - return delay; - }, - - /** - * @api private - */ - handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) { - if (!options) options = {}; - var http = AWS.HttpClient.getInstance(); - var httpOptions = options.httpOptions || {}; - var retryCount = 0; - - var errCallback = function(err) { - var maxRetries = options.maxRetries || 0; - if (err && err.code === 'TimeoutError') err.retryable = true; - if (err && err.retryable && retryCount < maxRetries) { - retryCount++; - var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions); - setTimeout(sendRequest, delay + (err.retryAfter || 0)); - } else { - cb(err); - } - }; - - var sendRequest = function() { - var data = ''; - http.handleRequest(httpRequest, httpOptions, function(httpResponse) { - httpResponse.on('data', function(chunk) { data += chunk.toString(); }); - httpResponse.on('end', function() { - var statusCode = httpResponse.statusCode; - if (statusCode < 300) { - cb(null, data); - } else { - var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0; - var err = util.error(new Error(), - { retryable: statusCode >= 500 || statusCode === 429 } - ); - if (retryAfter && err.retryable) err.retryAfter = retryAfter; - errCallback(err); - } - }); - }, errCallback); - }; - - AWS.util.defer(sendRequest); - }, - - /** - * @api private - */ - uuid: { - v4: function uuidV4() { - return require('uuid').v4(); - } - }, - - /** - * @api private - */ - convertPayloadToString: function convertPayloadToString(resp) { - var req = resp.request; - var operation = req.operation; - var rules = req.service.api.operations[operation].output || {}; - if (rules.payload && resp.data[rules.payload]) { - resp.data[rules.payload] = resp.data[rules.payload].toString(); - } - }, - - /** - * @api private - */ - defer: function defer(callback) { - if (typeof process === 'object' && typeof process.nextTick === 'function') { - process.nextTick(callback); - } else if (typeof setImmediate === 'function') { - setImmediate(callback); - } else { - setTimeout(callback, 0); - } - }, - - /** - * @api private - */ - getRequestPayloadShape: function getRequestPayloadShape(req) { - var operations = req.service.api.operations; - if (!operations) return undefined; - var operation = (operations || {})[req.operation]; - if (!operation || !operation.input || !operation.input.payload) return undefined; - return operation.input.members[operation.input.payload]; - }, - - getProfilesFromSharedConfig: function getProfilesFromSharedConfig(iniLoader, filename) { - var profiles = {}; - var profilesFromConfig = {}; - if (process.env[util.configOptInEnv]) { - var profilesFromConfig = iniLoader.loadFrom({ - isConfig: true, - filename: process.env[util.sharedConfigFileEnv] - }); - } - var profilesFromCreds = iniLoader.loadFrom({ - filename: filename || - (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv]) - }); - for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) { - profiles[profileNames[i]] = profilesFromConfig[profileNames[i]]; - } - for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) { - profiles[profileNames[i]] = profilesFromCreds[profileNames[i]]; - } - return profiles; - }, - - /** - * @api private - */ - defaultProfile: 'default', - - /** - * @api private - */ - configOptInEnv: 'AWS_SDK_LOAD_CONFIG', - - /** - * @api private - */ - sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE', - - /** - * @api private - */ - sharedConfigFileEnv: 'AWS_CONFIG_FILE', - - /** - * @api private - */ - imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED' -}; - -/** - * @api private - */ -module.exports = util; - -}).call(this)}).call(this,require('_process'),require("timers").setImmediate) -},{"../apis/metadata.json":4,"./core":18,"_process":86,"fs":79,"timers":93,"uuid":98}],72:[function(require,module,exports){ -var util = require('../util'); -var Shape = require('../model/shape'); - -function DomXmlParser() { } - -DomXmlParser.prototype.parse = function(xml, shape) { - if (xml.replace(/^\s+/, '') === '') return {}; - - var result, error; - try { - if (window.DOMParser) { - try { - var parser = new DOMParser(); - result = parser.parseFromString(xml, 'text/xml'); - } catch (syntaxError) { - throw util.error(new Error('Parse error in document'), - { - originalError: syntaxError, - code: 'XMLParserError', - retryable: true - }); - } - - if (result.documentElement === null) { - throw util.error(new Error('Cannot parse empty document.'), - { - code: 'XMLParserError', - retryable: true - }); - } - - var isError = result.getElementsByTagName('parsererror')[0]; - if (isError && (isError.parentNode === result || - isError.parentNode.nodeName === 'body' || - isError.parentNode.parentNode === result || - isError.parentNode.parentNode.nodeName === 'body')) { - var errorElement = isError.getElementsByTagName('div')[0] || isError; - throw util.error(new Error(errorElement.textContent || 'Parser error in document'), - { - code: 'XMLParserError', - retryable: true - }); - } - } else if (window.ActiveXObject) { - result = new window.ActiveXObject('Microsoft.XMLDOM'); - result.async = false; - - if (!result.loadXML(xml)) { - throw util.error(new Error('Parse error in document'), - { - code: 'XMLParserError', - retryable: true - }); - } - } else { - throw new Error('Cannot load XML parser'); - } - } catch (e) { - error = e; - } - - if (result && result.documentElement && !error) { - var data = parseXml(result.documentElement, shape); - var metadata = getElementByTagName(result.documentElement, 'ResponseMetadata'); - if (metadata) { - data.ResponseMetadata = parseXml(metadata, {}); - } - return data; - } else if (error) { - throw util.error(error || new Error(), {code: 'XMLParserError', retryable: true}); - } else { // empty xml document - return {}; - } -}; - -function getElementByTagName(xml, tag) { - var elements = xml.getElementsByTagName(tag); - for (var i = 0, iLen = elements.length; i < iLen; i++) { - if (elements[i].parentNode === xml) { - return elements[i]; - } - } -} - -function parseXml(xml, shape) { - if (!shape) shape = {}; - switch (shape.type) { - case 'structure': return parseStructure(xml, shape); - case 'map': return parseMap(xml, shape); - case 'list': return parseList(xml, shape); - case undefined: case null: return parseUnknown(xml); - default: return parseScalar(xml, shape); - } -} - -function parseStructure(xml, shape) { - var data = {}; - if (xml === null) return data; - - util.each(shape.members, function(memberName, memberShape) { - if (memberShape.isXmlAttribute) { - if (Object.prototype.hasOwnProperty.call(xml.attributes, memberShape.name)) { - var value = xml.attributes[memberShape.name].value; - data[memberName] = parseXml({textContent: value}, memberShape); - } - } else { - var xmlChild = memberShape.flattened ? xml : - getElementByTagName(xml, memberShape.name); - if (xmlChild) { - data[memberName] = parseXml(xmlChild, memberShape); - } else if (!memberShape.flattened && memberShape.type === 'list') { - data[memberName] = memberShape.defaultValue; - } - } - }); - - return data; -} - -function parseMap(xml, shape) { - var data = {}; - var xmlKey = shape.key.name || 'key'; - var xmlValue = shape.value.name || 'value'; - var tagName = shape.flattened ? shape.name : 'entry'; - - var child = xml.firstElementChild; - while (child) { - if (child.nodeName === tagName) { - var key = getElementByTagName(child, xmlKey).textContent; - var value = getElementByTagName(child, xmlValue); - data[key] = parseXml(value, shape.value); - } - child = child.nextElementSibling; - } - return data; -} - -function parseList(xml, shape) { - var data = []; - var tagName = shape.flattened ? shape.name : (shape.member.name || 'member'); - - var child = xml.firstElementChild; - while (child) { - if (child.nodeName === tagName) { - data.push(parseXml(child, shape.member)); - } - child = child.nextElementSibling; - } - return data; -} - -function parseScalar(xml, shape) { - if (xml.getAttribute) { - var encoding = xml.getAttribute('encoding'); - if (encoding === 'base64') { - shape = new Shape.create({type: encoding}); - } - } - - var text = xml.textContent; - if (text === '') text = null; - if (typeof shape.toType === 'function') { - return shape.toType(text); - } else { - return text; - } -} - -function parseUnknown(xml) { - if (xml === undefined || xml === null) return ''; - - // empty object - if (!xml.firstElementChild) { - if (xml.parentNode.parentNode === null) return {}; - if (xml.childNodes.length === 0) return ''; - else return xml.textContent; - } - - // object, parse as structure - var shape = {type: 'structure', members: {}}; - var child = xml.firstElementChild; - while (child) { - var tag = child.nodeName; - if (Object.prototype.hasOwnProperty.call(shape.members, tag)) { - // multiple tags of the same name makes it a list - shape.members[tag].type = 'list'; - } else { - shape.members[tag] = {name: tag}; - } - child = child.nextElementSibling; - } - return parseStructure(xml, shape); -} - -/** - * @api private - */ -module.exports = DomXmlParser; - -},{"../model/shape":43,"../util":71}],73:[function(require,module,exports){ -var util = require('../util'); -var XmlNode = require('./xml-node').XmlNode; -var XmlText = require('./xml-text').XmlText; - -function XmlBuilder() { } - -XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) { - var xml = new XmlNode(rootElement); - applyNamespaces(xml, shape, true); - serialize(xml, params, shape); - return xml.children.length > 0 || noEmpty ? xml.toString() : ''; -}; - -function serialize(xml, value, shape) { - switch (shape.type) { - case 'structure': return serializeStructure(xml, value, shape); - case 'map': return serializeMap(xml, value, shape); - case 'list': return serializeList(xml, value, shape); - default: return serializeScalar(xml, value, shape); - } -} - -function serializeStructure(xml, params, shape) { - util.arrayEach(shape.memberNames, function(memberName) { - var memberShape = shape.members[memberName]; - if (memberShape.location !== 'body') return; - - var value = params[memberName]; - var name = memberShape.name; - if (value !== undefined && value !== null) { - if (memberShape.isXmlAttribute) { - xml.addAttribute(name, value); - } else if (memberShape.flattened) { - serialize(xml, value, memberShape); - } else { - var element = new XmlNode(name); - xml.addChildNode(element); - applyNamespaces(element, memberShape); - serialize(element, value, memberShape); - } - } - }); -} - -function serializeMap(xml, map, shape) { - var xmlKey = shape.key.name || 'key'; - var xmlValue = shape.value.name || 'value'; - - util.each(map, function(key, value) { - var entry = new XmlNode(shape.flattened ? shape.name : 'entry'); - xml.addChildNode(entry); - - var entryKey = new XmlNode(xmlKey); - var entryValue = new XmlNode(xmlValue); - entry.addChildNode(entryKey); - entry.addChildNode(entryValue); - - serialize(entryKey, key, shape.key); - serialize(entryValue, value, shape.value); - }); -} - -function serializeList(xml, list, shape) { - if (shape.flattened) { - util.arrayEach(list, function(value) { - var name = shape.member.name || shape.name; - var element = new XmlNode(name); - xml.addChildNode(element); - serialize(element, value, shape.member); - }); - } else { - util.arrayEach(list, function(value) { - var name = shape.member.name || 'member'; - var element = new XmlNode(name); - xml.addChildNode(element); - serialize(element, value, shape.member); - }); - } -} - -function serializeScalar(xml, value, shape) { - xml.addChildNode( - new XmlText(shape.toWireFormat(value)) - ); -} - -function applyNamespaces(xml, shape, isRoot) { - var uri, prefix = 'xmlns'; - if (shape.xmlNamespaceUri) { - uri = shape.xmlNamespaceUri; - if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix; - } else if (isRoot && shape.api.xmlNamespaceUri) { - uri = shape.api.xmlNamespaceUri; - } - - if (uri) xml.addAttribute(prefix, uri); -} - -/** - * @api private - */ -module.exports = XmlBuilder; - -},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(require,module,exports){ -/** - * Escapes characters that can not be in an XML attribute. - */ -function escapeAttribute(value) { - return value.replace(/&/g, '&').replace(/'/g, ''').replace(//g, '>').replace(/"/g, '"'); -} - -/** - * @api private - */ -module.exports = { - escapeAttribute: escapeAttribute -}; - -},{}],75:[function(require,module,exports){ -/** - * Escapes characters that can not be in an XML element. - */ -function escapeElement(value) { - return value.replace(/&/g, '&').replace(//g, '>'); -} - -/** - * @api private - */ -module.exports = { - escapeElement: escapeElement -}; - -},{}],76:[function(require,module,exports){ -var escapeAttribute = require('./escape-attribute').escapeAttribute; - -/** - * Represents an XML node. - * @api private - */ -function XmlNode(name, children) { - if (children === void 0) { children = []; } - this.name = name; - this.children = children; - this.attributes = {}; -} -XmlNode.prototype.addAttribute = function (name, value) { - this.attributes[name] = value; - return this; -}; -XmlNode.prototype.addChildNode = function (child) { - this.children.push(child); - return this; -}; -XmlNode.prototype.removeAttribute = function (name) { - delete this.attributes[name]; - return this; -}; -XmlNode.prototype.toString = function () { - var hasChildren = Boolean(this.children.length); - var xmlText = '<' + this.name; - // add attributes - var attributes = this.attributes; - for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) { - var attributeName = attributeNames[i]; - var attribute = attributes[attributeName]; - if (typeof attribute !== 'undefined' && attribute !== null) { - xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"'; - } - } - return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + ''; -}; - -/** - * @api private - */ -module.exports = { - XmlNode: XmlNode -}; - -},{"./escape-attribute":74}],77:[function(require,module,exports){ -var escapeElement = require('./escape-element').escapeElement; - -/** - * Represents an XML text value. - * @api private - */ -function XmlText(value) { - this.value = value; -} - -XmlText.prototype.toString = function () { - return escapeElement('' + this.value); -}; - -/** - * @api private - */ -module.exports = { - XmlText: XmlText -}; - -},{"./escape-element":75}],78:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],79:[function(require,module,exports){ - -},{}],80:[function(require,module,exports){ -(function (global){(function (){ -/*! https://mths.be/punycode v1.3.2 by @mathias */ -;(function(root) { - - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; - var freeModule = typeof module == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof global == 'object' && global; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * http://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.3.2', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { // in Rhino or a web browser - root.punycode = punycode; - } - -}(this)); - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],81:[function(require,module,exports){ -(function (global,Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var isArray = require('isarray') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} - -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} - -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} - -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that -} - -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} - -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"base64-js":78,"buffer":81,"ieee754":83,"isarray":84}],82:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - -},{}],83:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],84:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -},{}],85:[function(require,module,exports){ -(function(exports) { - "use strict"; - - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; - } - } - - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; - } - } - - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; - } - - // Check if they are the same type. - var firstType = Object.prototype.toString.call(first); - if (firstType !== Object.prototype.toString.call(second)) { - return false; - } - // We know that first and second have the same type so we can just check the - // first type from now on. - if (isArray(first) === true) { - // Short circuit if they're not the same length; - if (first.length !== second.length) { - return false; - } - for (var i = 0; i < first.length; i++) { - if (strictDeepEqual(first[i], second[i]) === false) { - return false; - } - } - return true; - } - if (isObject(first) === true) { - // An object is equal if it has the same key/value pairs. - var keysSeen = {}; - for (var key in first) { - if (hasOwnProperty.call(first, key)) { - if (strictDeepEqual(first[key], second[key]) === false) { - return false; - } - keysSeen[key] = true; - } - } - // Now check that there aren't any keys in second that weren't - // in first. - for (var key2 in second) { - if (hasOwnProperty.call(second, key2)) { - if (keysSeen[key2] !== true) { - return false; - } - } - } - return true; - } - return false; - } - - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value - - // First check the scalar values. - if (obj === "" || obj === false || obj === null) { - return true; - } else if (isArray(obj) && obj.length === 0) { - // Check for an empty array. - return true; - } else if (isObject(obj)) { - // Check for an empty object. - for (var key in obj) { - // If there are any keys, then - // the object is not empty so the object - // is not false. - if (obj.hasOwnProperty(key)) { - return false; - } - } - return true; - } else { - return false; - } - } - - function objValues(obj) { - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); - } - return values; - } - - function merge(a, b) { - var merged = {}; - for (var key in a) { - merged[key] = a[key]; - } - for (var key2 in b) { - merged[key2] = b[key2]; - } - return merged; - } - - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; - } else { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; - } - - // Type constants used to define functions. - var TYPE_NUMBER = 0; - var TYPE_ANY = 1; - var TYPE_STRING = 2; - var TYPE_ARRAY = 3; - var TYPE_OBJECT = 4; - var TYPE_BOOLEAN = 5; - var TYPE_EXPREF = 6; - var TYPE_NULL = 7; - var TYPE_ARRAY_NUMBER = 8; - var TYPE_ARRAY_STRING = 9; - - var TOK_EOF = "EOF"; - var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; - var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; - var TOK_RBRACKET = "Rbracket"; - var TOK_RPAREN = "Rparen"; - var TOK_COMMA = "Comma"; - var TOK_COLON = "Colon"; - var TOK_RBRACE = "Rbrace"; - var TOK_NUMBER = "Number"; - var TOK_CURRENT = "Current"; - var TOK_EXPREF = "Expref"; - var TOK_PIPE = "Pipe"; - var TOK_OR = "Or"; - var TOK_AND = "And"; - var TOK_EQ = "EQ"; - var TOK_GT = "GT"; - var TOK_LT = "LT"; - var TOK_GTE = "GTE"; - var TOK_LTE = "LTE"; - var TOK_NE = "NE"; - var TOK_FLATTEN = "Flatten"; - var TOK_STAR = "Star"; - var TOK_FILTER = "Filter"; - var TOK_DOT = "Dot"; - var TOK_NOT = "Not"; - var TOK_LBRACE = "Lbrace"; - var TOK_LBRACKET = "Lbracket"; - var TOK_LPAREN= "Lparen"; - var TOK_LITERAL= "Literal"; - - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. - - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; - - var operatorStartToken = { - "<": true, - ">": true, - "=": true, - "!": true - }; - - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; - - - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; - } - - function isNum(ch) { - return (ch >= "0" && ch <= "9") || - ch === "-"; - } - function isAlphaNum(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - (ch >= "0" && ch <= "9") || - ch === "_"; - } - - function Lexer() { - } - Lexer.prototype = { - tokenize: function(stream) { - var tokens = []; - this._current = 0; - var start; - var identifier; - var token; - while (this._current < stream.length) { - if (isAlpha(stream[this._current])) { - start = this._current; - identifier = this._consumeUnquotedIdentifier(stream); - tokens.push({type: TOK_UNQUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (basicTokens[stream[this._current]] !== undefined) { - tokens.push({type: basicTokens[stream[this._current]], - value: stream[this._current], - start: this._current}); - this._current++; - } else if (isNum(stream[this._current])) { - token = this._consumeNumber(stream); - tokens.push(token); - } else if (stream[this._current] === "[") { - // No need to increment this._current. This happens - // in _consumeLBracket - token = this._consumeLBracket(stream); - tokens.push(token); - } else if (stream[this._current] === "\"") { - start = this._current; - identifier = this._consumeQuotedIdentifier(stream); - tokens.push({type: TOK_QUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (stream[this._current] === "'") { - start = this._current; - identifier = this._consumeRawStringLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: identifier, - start: start}); - } else if (stream[this._current] === "`") { - start = this._current; - var literal = this._consumeLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: literal, - start: start}); - } else if (operatorStartToken[stream[this._current]] !== undefined) { - tokens.push(this._consumeOperator(stream)); - } else if (skipChars[stream[this._current]] !== undefined) { - // Ignore whitespace. - this._current++; - } else if (stream[this._current] === "&") { - start = this._current; - this._current++; - if (stream[this._current] === "&") { - this._current++; - tokens.push({type: TOK_AND, value: "&&", start: start}); - } else { - tokens.push({type: TOK_EXPREF, value: "&", start: start}); - } - } else if (stream[this._current] === "|") { - start = this._current; - this._current++; - if (stream[this._current] === "|") { - this._current++; - tokens.push({type: TOK_OR, value: "||", start: start}); - } else { - tokens.push({type: TOK_PIPE, value: "|", start: start}); - } - } else { - var error = new Error("Unknown character:" + stream[this._current]); - error.name = "LexerError"; - throw error; - } - } - return tokens; - }, - - _consumeUnquotedIdentifier: function(stream) { - var start = this._current; - this._current++; - while (this._current < stream.length && isAlphaNum(stream[this._current])) { - this._current++; - } - return stream.slice(start, this._current); - }, - - _consumeQuotedIdentifier: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "\"" && this._current < maxLength) { - // You can escape a double quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "\"")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - return JSON.parse(stream.slice(start, this._current)); - }, - - _consumeRawStringLiteral: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "'" && this._current < maxLength) { - // You can escape a single quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "'")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - var literal = stream.slice(start + 1, this._current - 1); - return literal.replace("\\'", "'"); - }, - - _consumeNumber: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (isNum(stream[this._current]) && this._current < maxLength) { - this._current++; - } - var value = parseInt(stream.slice(start, this._current)); - return {type: TOK_NUMBER, value: value, start: start}; - }, - - _consumeLBracket: function(stream) { - var start = this._current; - this._current++; - if (stream[this._current] === "?") { - this._current++; - return {type: TOK_FILTER, value: "[?", start: start}; - } else if (stream[this._current] === "]") { - this._current++; - return {type: TOK_FLATTEN, value: "[]", start: start}; - } else { - return {type: TOK_LBRACKET, value: "[", start: start}; - } - }, - - _consumeOperator: function(stream) { - var start = this._current; - var startingChar = stream[start]; - this._current++; - if (startingChar === "!") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_NE, value: "!=", start: start}; - } else { - return {type: TOK_NOT, value: "!", start: start}; - } - } else if (startingChar === "<") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_LTE, value: "<=", start: start}; - } else { - return {type: TOK_LT, value: "<", start: start}; - } - } else if (startingChar === ">") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_GTE, value: ">=", start: start}; - } else { - return {type: TOK_GT, value: ">", start: start}; - } - } else if (startingChar === "=") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_EQ, value: "==", start: start}; - } - } - }, - - _consumeLiteral: function(stream) { - this._current++; - var start = this._current; - var maxLength = stream.length; - var literal; - while(stream[this._current] !== "`" && this._current < maxLength) { - // You can escape a literal char or you can escape the escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "`")) { - current += 2; - } else { - current++; - } - this._current = current; - } - var literalString = trimLeft(stream.slice(start, this._current)); - literalString = literalString.replace("\\`", "`"); - if (this._looksLikeJSON(literalString)) { - literal = JSON.parse(literalString); - } else { - // Try to JSON parse it as "" - literal = JSON.parse("\"" + literalString + "\""); - } - // +1 gets us to the ending "`", +1 to move on to the next char. - this._current++; - return literal; - }, - - _looksLikeJSON: function(literalString) { - var startingChars = "[{\""; - var jsonLiterals = ["true", "false", "null"]; - var numberLooking = "-0123456789"; - - if (literalString === "") { - return false; - } else if (startingChars.indexOf(literalString[0]) >= 0) { - return true; - } else if (jsonLiterals.indexOf(literalString) >= 0) { - return true; - } else if (numberLooking.indexOf(literalString[0]) >= 0) { - try { - JSON.parse(literalString); - return true; - } catch (ex) { - return false; - } - } else { - return false; - } - } - }; - - var bindingPower = {}; - bindingPower[TOK_EOF] = 0; - bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; - bindingPower[TOK_QUOTEDIDENTIFIER] = 0; - bindingPower[TOK_RBRACKET] = 0; - bindingPower[TOK_RPAREN] = 0; - bindingPower[TOK_COMMA] = 0; - bindingPower[TOK_RBRACE] = 0; - bindingPower[TOK_NUMBER] = 0; - bindingPower[TOK_CURRENT] = 0; - bindingPower[TOK_EXPREF] = 0; - bindingPower[TOK_PIPE] = 1; - bindingPower[TOK_OR] = 2; - bindingPower[TOK_AND] = 3; - bindingPower[TOK_EQ] = 5; - bindingPower[TOK_GT] = 5; - bindingPower[TOK_LT] = 5; - bindingPower[TOK_GTE] = 5; - bindingPower[TOK_LTE] = 5; - bindingPower[TOK_NE] = 5; - bindingPower[TOK_FLATTEN] = 9; - bindingPower[TOK_STAR] = 20; - bindingPower[TOK_FILTER] = 21; - bindingPower[TOK_DOT] = 40; - bindingPower[TOK_NOT] = 45; - bindingPower[TOK_LBRACE] = 50; - bindingPower[TOK_LBRACKET] = 55; - bindingPower[TOK_LPAREN] = 60; - - function Parser() { - } - - Parser.prototype = { - parse: function(expression) { - this._loadTokens(expression); - this.index = 0; - var ast = this.expression(0); - if (this._lookahead(0) !== TOK_EOF) { - var t = this._lookaheadToken(0); - var error = new Error( - "Unexpected token type: " + t.type + ", value: " + t.value); - error.name = "ParserError"; - throw error; - } - return ast; - }, - - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, - - expression: function(rbp) { - var leftToken = this._lookaheadToken(0); - this._advance(); - var left = this.nud(leftToken); - var currentToken = this._lookahead(0); - while (rbp < bindingPower[currentToken]) { - this._advance(); - left = this.led(currentToken, left); - currentToken = this._lookahead(0); - } - return left; - }, - - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, - - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, - - _advance: function() { - this.index++; - }, - - nud: function(token) { - var left; - var right; - var expression; - switch (token.type) { - case TOK_LITERAL: - return {type: "Literal", value: token.value}; - case TOK_UNQUOTEDIDENTIFIER: - return {type: "Field", name: token.value}; - case TOK_QUOTEDIDENTIFIER: - var node = {type: "Field", name: token.value}; - if (this._lookahead(0) === TOK_LPAREN) { - throw new Error("Quoted identifier not allowed for function names."); - } else { - return node; - } - break; - case TOK_NOT: - right = this.expression(bindingPower.Not); - return {type: "NotExpression", children: [right]}; - case TOK_STAR: - left = {type: "Identity"}; - right = null; - if (this._lookahead(0) === TOK_RBRACKET) { - // This can happen in a multiselect, - // [a, b, *] - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Star); - } - return {type: "ValueProjection", children: [left, right]}; - case TOK_FILTER: - return this.led(token.type, {type: "Identity"}); - case TOK_LBRACE: - return this._parseMultiselectHash(); - case TOK_FLATTEN: - left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; - right = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [left, right]}; - case TOK_LBRACKET: - if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice({type: "Identity"}, right); - } else if (this._lookahead(0) === TOK_STAR && - this._lookahead(1) === TOK_RBRACKET) { - this._advance(); - this._advance(); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", - children: [{type: "Identity"}, right]}; - } else { - return this._parseMultiselectList(); - } - break; - case TOK_CURRENT: - return {type: TOK_CURRENT}; - case TOK_EXPREF: - expression = this.expression(bindingPower.Expref); - return {type: "ExpressionReference", children: [expression]}; - case TOK_LPAREN: - var args = []; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - args.push(expression); - } - this._match(TOK_RPAREN); - return args[0]; - default: - this._errorToken(token); - } - }, - - led: function(tokenName, left) { - var right; - switch(tokenName) { - case TOK_DOT: - var rbp = bindingPower.Dot; - if (this._lookahead(0) !== TOK_STAR) { - right = this._parseDotRHS(rbp); - return {type: "Subexpression", children: [left, right]}; - } else { - // Creating a projection. - this._advance(); - right = this._parseProjectionRHS(rbp); - return {type: "ValueProjection", children: [left, right]}; - } - break; - case TOK_PIPE: - right = this.expression(bindingPower.Pipe); - return {type: TOK_PIPE, children: [left, right]}; - case TOK_OR: - right = this.expression(bindingPower.Or); - return {type: "OrExpression", children: [left, right]}; - case TOK_AND: - right = this.expression(bindingPower.And); - return {type: "AndExpression", children: [left, right]}; - case TOK_LPAREN: - var name = left.name; - var args = []; - var expression, node; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } - args.push(expression); - } - this._match(TOK_RPAREN); - node = {type: "Function", name: name, children: args}; - return node; - case TOK_FILTER: - var condition = this.expression(0); - this._match(TOK_RBRACKET); - if (this._lookahead(0) === TOK_FLATTEN) { - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Filter); - } - return {type: "FilterProjection", children: [left, right, condition]}; - case TOK_FLATTEN: - var leftNode = {type: TOK_FLATTEN, children: [left]}; - var rightNode = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [leftNode, rightNode]}; - case TOK_EQ: - case TOK_NE: - case TOK_GT: - case TOK_GTE: - case TOK_LT: - case TOK_LTE: - return this._parseComparator(left, tokenName); - case TOK_LBRACKET: - var token = this._lookaheadToken(0); - if (token.type === TOK_NUMBER || token.type === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice(left, right); - } else { - this._match(TOK_STAR); - this._match(TOK_RBRACKET); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", children: [left, right]}; - } - break; - default: - this._errorToken(this._lookaheadToken(0)); - } - }, - - _match: function(tokenType) { - if (this._lookahead(0) === tokenType) { - this._advance(); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Expected " + tokenType + ", got: " + t.type); - error.name = "ParserError"; - throw error; - } - }, - - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, - - - _parseIndexExpression: function() { - if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { - return this._parseSliceExpression(); - } else { - var node = { - type: "Index", - value: this._lookaheadToken(0).value}; - this._advance(); - this._match(TOK_RBRACKET); - return node; - } - }, - - _projectIfSlice: function(left, right) { - var indexExpr = {type: "IndexExpression", children: [left, right]}; - if (right.type === "Slice") { - return { - type: "Projection", - children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] - }; - } else { - return indexExpr; - } - }, - - _parseSliceExpression: function() { - // [start:end:step] where each part is optional, as well as the last - // colon. - var parts = [null, null, null]; - var index = 0; - var currentToken = this._lookahead(0); - while (currentToken !== TOK_RBRACKET && index < 3) { - if (currentToken === TOK_COLON) { - index++; - this._advance(); - } else if (currentToken === TOK_NUMBER) { - parts[index] = this._lookaheadToken(0).value; - this._advance(); - } else { - var t = this._lookahead(0); - var error = new Error("Syntax error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "Parsererror"; - throw error; - } - currentToken = this._lookahead(0); - } - this._match(TOK_RBRACKET); - return { - type: "Slice", - children: parts - }; - }, - - _parseComparator: function(left, comparator) { - var right = this.expression(bindingPower[comparator]); - return {type: "Comparator", name: comparator, children: [left, right]}; - }, - - _parseDotRHS: function(rbp) { - var lookahead = this._lookahead(0); - var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; - if (exprTokens.indexOf(lookahead) >= 0) { - return this.expression(rbp); - } else if (lookahead === TOK_LBRACKET) { - this._match(TOK_LBRACKET); - return this._parseMultiselectList(); - } else if (lookahead === TOK_LBRACE) { - this._match(TOK_LBRACE); - return this._parseMultiselectHash(); - } - }, - - _parseProjectionRHS: function(rbp) { - var right; - if (bindingPower[this._lookahead(0)] < 10) { - right = {type: "Identity"}; - } else if (this._lookahead(0) === TOK_LBRACKET) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_FILTER) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_DOT) { - this._match(TOK_DOT); - right = this._parseDotRHS(rbp); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Sytanx error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "ParserError"; - throw error; - } - return right; - }, - - _parseMultiselectList: function() { - var expressions = []; - while (this._lookahead(0) !== TOK_RBRACKET) { - var expression = this.expression(0); - expressions.push(expression); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - if (this._lookahead(0) === TOK_RBRACKET) { - throw new Error("Unexpected token Rbracket"); - } - } - } - this._match(TOK_RBRACKET); - return {type: "MultiSelectList", children: expressions}; - }, - - _parseMultiselectHash: function() { - var pairs = []; - var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; - var keyToken, keyName, value, node; - for (;;) { - keyToken = this._lookaheadToken(0); - if (identifierTypes.indexOf(keyToken.type) < 0) { - throw new Error("Expecting an identifier token, got: " + - keyToken.type); - } - keyName = keyToken.value; - this._advance(); - this._match(TOK_COLON); - value = this.expression(0); - node = {type: "KeyValuePair", name: keyName, value: value}; - pairs.push(node); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } else if (this._lookahead(0) === TOK_RBRACE) { - this._match(TOK_RBRACE); - break; - } - } - return {type: "MultiSelectHash", children: pairs}; - } - }; - - - function TreeInterpreter(runtime) { - this.runtime = runtime; - } - - TreeInterpreter.prototype = { - search: function(node, value) { - return this.visit(node, value); - }, - - visit: function(node, value) { - var matched, current, result, first, second, field, left, right, collected, i; - switch (node.type) { - case "Field": - if (value === null ) { - return null; - } else if (isObject(value)) { - field = value[node.name]; - if (field === undefined) { - return null; - } else { - return field; - } - } else { - return null; - } - break; - case "Subexpression": - result = this.visit(node.children[0], value); - for (i = 1; i < node.children.length; i++) { - result = this.visit(node.children[1], result); - if (result === null) { - return null; - } - } - return result; - case "IndexExpression": - left = this.visit(node.children[0], value); - right = this.visit(node.children[1], left); - return right; - case "Index": - if (!isArray(value)) { - return null; - } - var index = node.value; - if (index < 0) { - index = value.length + index; - } - result = value[index]; - if (result === undefined) { - result = null; - } - return result; - case "Slice": - if (!isArray(value)) { - return null; - } - var sliceParams = node.children.slice(0); - var computed = this.computeSliceParams(value.length, sliceParams); - var start = computed[0]; - var stop = computed[1]; - var step = computed[2]; - result = []; - if (step > 0) { - for (i = start; i < stop; i += step) { - result.push(value[i]); - } - } else { - for (i = start; i > stop; i += step) { - result.push(value[i]); - } - } - return result; - case "Projection": - // Evaluate left child. - var base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - collected = []; - for (i = 0; i < base.length; i++) { - current = this.visit(node.children[1], base[i]); - if (current !== null) { - collected.push(current); - } - } - return collected; - case "ValueProjection": - // Evaluate left child. - base = this.visit(node.children[0], value); - if (!isObject(base)) { - return null; - } - collected = []; - var values = objValues(base); - for (i = 0; i < values.length; i++) { - current = this.visit(node.children[1], values[i]); - if (current !== null) { - collected.push(current); - } - } - return collected; - case "FilterProjection": - base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - var filtered = []; - var finalResults = []; - for (i = 0; i < base.length; i++) { - matched = this.visit(node.children[2], base[i]); - if (!isFalse(matched)) { - filtered.push(base[i]); - } - } - for (var j = 0; j < filtered.length; j++) { - current = this.visit(node.children[1], filtered[j]); - if (current !== null) { - finalResults.push(current); - } - } - return finalResults; - case "Comparator": - first = this.visit(node.children[0], value); - second = this.visit(node.children[1], value); - switch(node.name) { - case TOK_EQ: - result = strictDeepEqual(first, second); - break; - case TOK_NE: - result = !strictDeepEqual(first, second); - break; - case TOK_GT: - result = first > second; - break; - case TOK_GTE: - result = first >= second; - break; - case TOK_LT: - result = first < second; - break; - case TOK_LTE: - result = first <= second; - break; - default: - throw new Error("Unknown comparator: " + node.name); - } - return result; - case TOK_FLATTEN: - var original = this.visit(node.children[0], value); - if (!isArray(original)) { - return null; - } - var merged = []; - for (i = 0; i < original.length; i++) { - current = original[i]; - if (isArray(current)) { - merged.push.apply(merged, current); - } else { - merged.push(current); - } - } - return merged; - case "Identity": - return value; - case "MultiSelectList": - if (value === null) { - return null; - } - collected = []; - for (i = 0; i < node.children.length; i++) { - collected.push(this.visit(node.children[i], value)); - } - return collected; - case "MultiSelectHash": - if (value === null) { - return null; - } - collected = {}; - var child; - for (i = 0; i < node.children.length; i++) { - child = node.children[i]; - collected[child.name] = this.visit(child.value, value); - } - return collected; - case "OrExpression": - matched = this.visit(node.children[0], value); - if (isFalse(matched)) { - matched = this.visit(node.children[1], value); - } - return matched; - case "AndExpression": - first = this.visit(node.children[0], value); - - if (isFalse(first) === true) { - return first; - } - return this.visit(node.children[1], value); - case "NotExpression": - first = this.visit(node.children[0], value); - return isFalse(first); - case "Literal": - return node.value; - case TOK_PIPE: - left = this.visit(node.children[0], value); - return this.visit(node.children[1], left); - case TOK_CURRENT: - return value; - case "Function": - var resolvedArgs = []; - for (i = 0; i < node.children.length; i++) { - resolvedArgs.push(this.visit(node.children[i], value)); - } - return this.runtime.callFunction(node.name, resolvedArgs); - case "ExpressionReference": - var refNode = node.children[0]; - // Tag the node with a specific attribute so the type - // checker verify the type. - refNode.jmespathType = TOK_EXPREF; - return refNode; - default: - throw new Error("Unknown node type: " + node.type); - } - }, - - computeSliceParams: function(arrayLength, sliceParams) { - var start = sliceParams[0]; - var stop = sliceParams[1]; - var step = sliceParams[2]; - var computed = [null, null, null]; - if (step === null) { - step = 1; - } else if (step === 0) { - var error = new Error("Invalid slice, step cannot be 0"); - error.name = "RuntimeError"; - throw error; - } - var stepValueNegative = step < 0 ? true : false; - - if (start === null) { - start = stepValueNegative ? arrayLength - 1 : 0; - } else { - start = this.capSliceRange(arrayLength, start, step); - } - - if (stop === null) { - stop = stepValueNegative ? -1 : arrayLength; - } else { - stop = this.capSliceRange(arrayLength, stop, step); - } - computed[0] = start; - computed[1] = stop; - computed[2] = step; - return computed; - }, - - capSliceRange: function(arrayLength, actualValue, step) { - if (actualValue < 0) { - actualValue += arrayLength; - if (actualValue < 0) { - actualValue = step < 0 ? -1 : 0; - } - } else if (actualValue >= arrayLength) { - actualValue = step < 0 ? arrayLength - 1 : arrayLength; - } - return actualValue; - } - - }; - - function Runtime(interpreter) { - this._interpreter = interpreter; - this.functionTable = { - // name: [function, ] - // The can be: - // - // { - // args: [[type1, type2], [type1, type2]], - // variadic: true|false - // } - // - // Each arg in the arg list is a list of valid types - // (if the function is overloaded and supports multiple - // types. If the type is "any" then no type checking - // occurs on the argument. Variadic is optional - // and if not provided is assumed to be false. - abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, - avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, - contains: { - _func: this._functionContains, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, - {types: [TYPE_ANY]}]}, - "ends_with": { - _func: this._functionEndsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, - length: { - _func: this._functionLength, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, - map: { - _func: this._functionMap, - _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, - max: { - _func: this._functionMax, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "merge": { - _func: this._functionMerge, - _signature: [{types: [TYPE_OBJECT], variadic: true}] - }, - "max_by": { - _func: this._functionMaxBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - "starts_with": { - _func: this._functionStartsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - min: { - _func: this._functionMin, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "min_by": { - _func: this._functionMinBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, - keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, - values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, - sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, - "sort_by": { - _func: this._functionSortBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - join: { - _func: this._functionJoin, - _signature: [ - {types: [TYPE_STRING]}, - {types: [TYPE_ARRAY_STRING]} - ] - }, - reverse: { - _func: this._functionReverse, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, - "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, - "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, - "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, - "not_null": { - _func: this._functionNotNull, - _signature: [{types: [TYPE_ANY], variadic: true}] - } - }; - } - - Runtime.prototype = { - callFunction: function(name, resolvedArgs) { - var functionEntry = this.functionTable[name]; - if (functionEntry === undefined) { - throw new Error("Unknown function: " + name + "()"); - } - this._validateArgs(name, resolvedArgs, functionEntry._signature); - return functionEntry._func.call(this, resolvedArgs); - }, - - _validateArgs: function(name, args, signature) { - // Validating the args requires validating - // the correct arity and the correct type of each arg. - // If the last argument is declared as variadic, then we need - // a minimum number of args to be required. Otherwise it has to - // be an exact amount. - var pluralized; - if (signature[signature.length - 1].variadic) { - if (args.length < signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes at least" + signature.length + pluralized + - " but received " + args.length); - } - } else if (args.length !== signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes " + signature.length + pluralized + - " but received " + args.length); - } - var currentSpec; - var actualType; - var typeMatched; - for (var i = 0; i < signature.length; i++) { - typeMatched = false; - currentSpec = signature[i].types; - actualType = this._getTypeName(args[i]); - for (var j = 0; j < currentSpec.length; j++) { - if (this._typeMatches(actualType, currentSpec[j], args[i])) { - typeMatched = true; - break; - } - } - if (!typeMatched) { - throw new Error("TypeError: " + name + "() " + - "expected argument " + (i + 1) + - " to be type " + currentSpec + - " but received type " + actualType + - " instead."); - } - } - }, - - _typeMatches: function(actual, expected, argValue) { - if (expected === TYPE_ANY) { - return true; - } - if (expected === TYPE_ARRAY_STRING || - expected === TYPE_ARRAY_NUMBER || - expected === TYPE_ARRAY) { - // The expected type can either just be array, - // or it can require a specific subtype (array of numbers). - // - // The simplest case is if "array" with no subtype is specified. - if (expected === TYPE_ARRAY) { - return actual === TYPE_ARRAY; - } else if (actual === TYPE_ARRAY) { - // Otherwise we need to check subtypes. - // I think this has potential to be improved. - var subtype; - if (expected === TYPE_ARRAY_NUMBER) { - subtype = TYPE_NUMBER; - } else if (expected === TYPE_ARRAY_STRING) { - subtype = TYPE_STRING; - } - for (var i = 0; i < argValue.length; i++) { - if (!this._typeMatches( - this._getTypeName(argValue[i]), subtype, - argValue[i])) { - return false; - } - } - return true; - } - } else { - return actual === expected; - } - }, - _getTypeName: function(obj) { - switch (Object.prototype.toString.call(obj)) { - case "[object String]": - return TYPE_STRING; - case "[object Number]": - return TYPE_NUMBER; - case "[object Array]": - return TYPE_ARRAY; - case "[object Boolean]": - return TYPE_BOOLEAN; - case "[object Null]": - return TYPE_NULL; - case "[object Object]": - // Check if it's an expref. If it has, it's been - // tagged with a jmespathType attr of 'Expref'; - if (obj.jmespathType === TOK_EXPREF) { - return TYPE_EXPREF; - } else { - return TYPE_OBJECT; - } - } - }, - - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, - - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, - - _functionReverse: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - if (typeName === TYPE_STRING) { - var originalStr = resolvedArgs[0]; - var reversedStr = ""; - for (var i = originalStr.length - 1; i >= 0; i--) { - reversedStr += originalStr[i]; - } - return reversedStr; - } else { - var reversedArray = resolvedArgs[0].slice(0); - reversedArray.reverse(); - return reversedArray; - } - }, - - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, - - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, - - _functionAvg: function(resolvedArgs) { - var sum = 0; - var inputArray = resolvedArgs[0]; - for (var i = 0; i < inputArray.length; i++) { - sum += inputArray[i]; - } - return sum / inputArray.length; - }, - - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, - - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[0]); - }, - - _functionLength: function(resolvedArgs) { - if (!isObject(resolvedArgs[0])) { - return resolvedArgs[0].length; - } else { - // As far as I can tell, there's no way to get the length - // of an object without O(n) iteration through the object. - return Object.keys(resolvedArgs[0]).length; - } - }, - - _functionMap: function(resolvedArgs) { - var mapped = []; - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[0]; - var elements = resolvedArgs[1]; - for (var i = 0; i < elements.length; i++) { - mapped.push(interpreter.visit(exprefNode, elements[i])); - } - return mapped; - }, - - _functionMerge: function(resolvedArgs) { - var merged = {}; - for (var i = 0; i < resolvedArgs.length; i++) { - var current = resolvedArgs[i]; - for (var key in current) { - merged[key] = current[key]; - } - } - return merged; - }, - - _functionMax: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.max.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var maxElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (maxElement.localeCompare(elements[i]) < 0) { - maxElement = elements[i]; - } - } - return maxElement; - } - } else { - return null; - } - }, - - _functionMin: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.min.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var minElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (elements[i].localeCompare(minElement) < 0) { - minElement = elements[i]; - } - } - return minElement; - } - } else { - return null; - } - }, - - _functionSum: function(resolvedArgs) { - var sum = 0; - var listToSum = resolvedArgs[0]; - for (var i = 0; i < listToSum.length; i++) { - sum += listToSum[i]; - } - return sum; - }, - - _functionType: function(resolvedArgs) { - switch (this._getTypeName(resolvedArgs[0])) { - case TYPE_NUMBER: - return "number"; - case TYPE_STRING: - return "string"; - case TYPE_ARRAY: - return "array"; - case TYPE_OBJECT: - return "object"; - case TYPE_BOOLEAN: - return "boolean"; - case TYPE_EXPREF: - return "expref"; - case TYPE_NULL: - return "null"; - } - }, - - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, - - _functionValues: function(resolvedArgs) { - var obj = resolvedArgs[0]; - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); - } - return values; - }, - - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, - - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; - } - }, - - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); - } - }, - - _functionToNumber: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - var convertedValue; - if (typeName === TYPE_NUMBER) { - return resolvedArgs[0]; - } else if (typeName === TYPE_STRING) { - convertedValue = +resolvedArgs[0]; - if (!isNaN(convertedValue)) { - return convertedValue; - } - } - return null; - }, - - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; - } - } - return null; - }, - - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, - - _functionSortBy: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - if (sortedArray.length === 0) { - return sortedArray; - } - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[1]; - var requiredType = this._getTypeName( - interpreter.visit(exprefNode, sortedArray[0])); - if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { - throw new Error("TypeError"); - } - var that = this; - // In order to get a stable sort out of an unstable - // sort algorithm, we decorate/sort/undecorate (DSU) - // by creating a new list of [index, element] pairs. - // In the cmp function, if the evaluated elements are - // equal, then the index will be used as the tiebreaker. - // After the decorated list has been sorted, it will be - // undecorated to extract the original elements. - var decorated = []; - for (var i = 0; i < sortedArray.length; i++) { - decorated.push([i, sortedArray[i]]); - } - decorated.sort(function(a, b) { - var exprA = interpreter.visit(exprefNode, a[1]); - var exprB = interpreter.visit(exprefNode, b[1]); - if (that._getTypeName(exprA) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprA)); - } else if (that._getTypeName(exprB) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprB)); - } - if (exprA > exprB) { - return 1; - } else if (exprA < exprB) { - return -1; - } else { - // If they're equal compare the items by their - // order to maintain relative order of equal keys - // (i.e. to get a stable sort). - return a[0] - b[0]; - } - }); - // Undecorate: extract out the original list elements. - for (var j = 0; j < decorated.length; j++) { - sortedArray[j] = decorated[j][1]; - } - return sortedArray; - }, - - _functionMaxBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var maxNumber = -Infinity; - var maxRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current > maxNumber) { - maxNumber = current; - maxRecord = resolvedArray[i]; - } - } - return maxRecord; - }, - - _functionMinBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var minNumber = Infinity; - var minRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current < minNumber) { - minNumber = current; - minRecord = resolvedArray[i]; - } - } - return minRecord; - }, - - createKeyFunction: function(exprefNode, allowedTypes) { - var that = this; - var interpreter = this._interpreter; - var keyFunc = function(x) { - var current = interpreter.visit(exprefNode, x); - if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { - var msg = "TypeError: expected one of " + allowedTypes + - ", received " + that._getTypeName(current); - throw new Error(msg); - } - return current; - }; - return keyFunc; - } - - }; - - function compile(stream) { - var parser = new Parser(); - var ast = parser.parse(stream); - return ast; - } - - function tokenize(stream) { - var lexer = new Lexer(); - return lexer.tokenize(stream); - } - - function search(data, expression) { - var parser = new Parser(); - // This needs to be improved. Both the interpreter and runtime depend on - // each other. The runtime needs the interpreter to support exprefs. - // There's likely a clean way to avoid the cyclic dependency. - var runtime = new Runtime(); - var interpreter = new TreeInterpreter(runtime); - runtime._interpreter = interpreter; - var node = parser.parse(expression); - return interpreter.search(node, data); - } - - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})(typeof exports === "undefined" ? this.jmespath = {} : exports); - -},{}],86:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],87:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{}],88:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -function map (xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; -} - -var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; -}; - -},{}],89:[function(require,module,exports){ -'use strict'; - -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); - -},{"./decode":87,"./encode":88}],90:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (Array.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; -}; - -},{}],91:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return Object.keys(obj).map(function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (Array.isArray(obj[k])) { - return obj[k].map(function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - -},{}],92:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"./decode":90,"./encode":91,"dup":89}],93:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":86,"timers":93}],94:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var punycode = require('punycode'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { - 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; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = require('querystring'); - -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && isObject(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a puny coded representation of "domain". - // It only converts the part of the domain name that - // has non ASCII characters. I.e. it dosent matter if - // you call it with a domain that already is in ASCII. - var domainArray = this.hostname.split('.'); - var newOut = []; - for (var i = 0; i < domainArray.length; ++i) { - var s = domainArray[i]; - newOut.push(s.match(/[^A-Za-z0-9_-]/) ? - 'xn--' + punycode.encode(s) : s); - } - this.hostname = newOut.join('.'); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } - - if (this.query && - isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { - if (isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - Object.keys(this).forEach(function(k) { - result[k] = this[k]; - }, this); - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - Object.keys(relative).forEach(function(k) { - if (k !== 'protocol') - result[k] = relative[k]; - }); - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - Object.keys(relative).forEach(function(k) { - result[k] = relative[k]; - }); - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host) && (last === '.' || last === '..') || - last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last == '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -}; - -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) this.hostname = host; -}; - -function isString(arg) { - return typeof arg === "string"; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isNull(arg) { - return arg === null; -} -function isNullOrUndefined(arg) { - return arg == null; -} - -},{"punycode":80,"querystring":89}],95:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],96:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],97:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.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] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":96,"_process":86,"inherits":95}],98:[function(require,module,exports){ -var v1 = require('./v1'); -var v4 = require('./v4'); - -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; - -module.exports = uuid; - -},{"./v1":101,"./v4":102}],99:[function(require,module,exports){ -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); -} - -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]]]).join(''); -} - -module.exports = bytesToUuid; - -},{}],100:[function(require,module,exports){ -// Unique ID creation requires a high quality random # generator. In the -// browser this is a little complicated due to unknown quality of Math.random() -// and inconsistent support for the `crypto` API. We do the best we can via -// feature-detection - -// getRandomValues needs to be invoked in a context where "this" is a Crypto -// implementation. Also, find the complete implementation of crypto on IE11. -var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || - (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); - -if (getRandomValues) { - // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto - var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef - - module.exports = function whatwgRNG() { - getRandomValues(rnds8); - return rnds8; - }; -} else { - // Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var rnds = new Array(16); - - module.exports = function mathRNG() { - for (var i = 0, r; i < 16; i++) { - if ((i & 0x03) === 0) r = Math.random() * 0x100000000; - rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; - } - - return rnds; - }; -} - -},{}],101:[function(require,module,exports){ -var rng = require('./lib/rng'); -var bytesToUuid = require('./lib/bytesToUuid'); - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -var _nodeId; -var _clockseq; - -// Previous uuid creation time -var _lastMSecs = 0; -var _lastNSecs = 0; - -// See https://github.com/broofa/node-uuid for API details -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - - // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - if (node == null || clockseq == null) { - var seedBytes = rng(); - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [ - seedBytes[0] | 0x01, - seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] - ]; - } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } - - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf ? buf : bytesToUuid(b); -} - -module.exports = v1; - -},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(require,module,exports){ -var rng = require('./lib/rng'); -var bytesToUuid = require('./lib/bytesToUuid'); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - -},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var LRU_1 = require("./utils/LRU"); -var CACHE_SIZE = 1000; -/** - * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache] - */ -var EndpointCache = /** @class */ (function () { - function EndpointCache(maxSize) { - if (maxSize === void 0) { maxSize = CACHE_SIZE; } - this.maxSize = maxSize; - this.cache = new LRU_1.LRUCache(maxSize); - } - ; - Object.defineProperty(EndpointCache.prototype, "size", { - get: function () { - return this.cache.length; - }, - enumerable: true, - configurable: true - }); - EndpointCache.prototype.put = function (key, value) { - var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; - var endpointRecord = this.populateValue(value); - this.cache.put(keyString, endpointRecord); - }; - EndpointCache.prototype.get = function (key) { - var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; - var now = Date.now(); - var records = this.cache.get(keyString); - if (records) { - for (var i = 0; i < records.length; i++) { - var record = records[i]; - if (record.Expire < now) { - this.cache.remove(keyString); - return undefined; - } - } - } - return records; - }; - EndpointCache.getKeyString = function (key) { - var identifiers = []; - var identifierNames = Object.keys(key).sort(); - for (var i = 0; i < identifierNames.length; i++) { - var identifierName = identifierNames[i]; - if (key[identifierName] === undefined) - continue; - identifiers.push(key[identifierName]); - } - return identifiers.join(' '); - }; - EndpointCache.prototype.populateValue = function (endpoints) { - var now = Date.now(); - return endpoints.map(function (endpoint) { return ({ - Address: endpoint.Address || '', - Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000 - }); }); - }; - EndpointCache.prototype.empty = function () { - this.cache.empty(); - }; - EndpointCache.prototype.remove = function (key) { - var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; - this.cache.remove(keyString); - }; - return EndpointCache; -}()); -exports.EndpointCache = EndpointCache; -},{"./utils/LRU":104}],104:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var LinkedListNode = /** @class */ (function () { - function LinkedListNode(key, value) { - this.key = key; - this.value = value; - } - return LinkedListNode; -}()); -var LRUCache = /** @class */ (function () { - function LRUCache(size) { - this.nodeMap = {}; - this.size = 0; - if (typeof size !== 'number' || size < 1) { - throw new Error('Cache size can only be positive number'); - } - this.sizeLimit = size; - } - Object.defineProperty(LRUCache.prototype, "length", { - get: function () { - return this.size; - }, - enumerable: true, - configurable: true - }); - LRUCache.prototype.prependToList = function (node) { - if (!this.headerNode) { - this.tailNode = node; - } - else { - this.headerNode.prev = node; - node.next = this.headerNode; - } - this.headerNode = node; - this.size++; - }; - LRUCache.prototype.removeFromTail = function () { - if (!this.tailNode) { - return undefined; - } - var node = this.tailNode; - var prevNode = node.prev; - if (prevNode) { - prevNode.next = undefined; - } - node.prev = undefined; - this.tailNode = prevNode; - this.size--; - return node; - }; - LRUCache.prototype.detachFromList = function (node) { - if (this.headerNode === node) { - this.headerNode = node.next; - } - if (this.tailNode === node) { - this.tailNode = node.prev; - } - if (node.prev) { - node.prev.next = node.next; - } - if (node.next) { - node.next.prev = node.prev; - } - node.next = undefined; - node.prev = undefined; - this.size--; - }; - LRUCache.prototype.get = function (key) { - if (this.nodeMap[key]) { - var node = this.nodeMap[key]; - this.detachFromList(node); - this.prependToList(node); - return node.value; - } - }; - LRUCache.prototype.remove = function (key) { - if (this.nodeMap[key]) { - var node = this.nodeMap[key]; - this.detachFromList(node); - delete this.nodeMap[key]; - } - }; - LRUCache.prototype.put = function (key, value) { - if (this.nodeMap[key]) { - this.remove(key); - } - else if (this.size === this.sizeLimit) { - var tailNode = this.removeFromTail(); - var key_1 = tailNode.key; - delete this.nodeMap[key_1]; - } - var newNode = new LinkedListNode(key, value); - this.nodeMap[key] = newNode; - this.prependToList(newNode); - }; - LRUCache.prototype.empty = function () { - var keys = Object.keys(this.nodeMap); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var node = this.nodeMap[key]; - this.detachFromList(node); - delete this.nodeMap[key]; - } - }; - return LRUCache; -}()); -exports.LRUCache = LRUCache; -},{}],105:[function(require,module,exports){ -// AWS SDK for JavaScript v2.553.0 -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt -require('./browser_loader'); - -var AWS = require('./core'); - -if (typeof window !== 'undefined') window.AWS = AWS; -if (typeof module !== 'undefined') { - /** - * @api private - */ - module.exports = AWS; -} -if (typeof self !== 'undefined') self.AWS = AWS; - -/** - * @private - * DO NOT REMOVE - * browser builder will strip out this line if services are supplied on the command line. - */if (!Object.prototype.hasOwnProperty.call(AWS, 'Connect')) { - AWS.apiLoader.services['connect'] = {}; - AWS.Connect = AWS.Service.defineService('connect', [ '2017-02-15' ]); -} -AWS.apiLoader.services['connect']['2017-02-15'] = require('../apis/connect-2017-02-15.min'); - -if (!Object.prototype.hasOwnProperty.call(AWS, 'STS')) { - AWS.apiLoader.services['sts'] = {}; - AWS.STS = AWS.Service.defineService('sts', [ '2011-06-15' ]); - require('./services/sts'); -} -AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.min'); - - -},{"../apis/connect-2017-02-15.min":3,"../apis/sts-2011-06-15.min":5,"./browser_loader":16,"./core":18,"./services/sts":61}]},{},[105]); - - -/*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ - -(function() { - var ctx = this; - - var sprintf = function() { - if (!sprintf.cache.hasOwnProperty(arguments[0])) { - sprintf.cache[arguments[0]] = sprintf.parse(arguments[0]); - } - return sprintf.format.call(null, sprintf.cache[arguments[0]], arguments); - }; - - sprintf.format = function(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]); - if (node_type === 'string') { - output.push(parse_tree[i]); - } - else if (node_type === 'array') { - match = parse_tree[i]; // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor]; - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw(sprintf('[sprintf] property "%s" does not exist', match[2][k])); - } - arg = arg[match[2][k]]; - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]]; - } - else { // positional argument (implicit) - arg = argv[cursor++]; - } - - if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { - throw(sprintf('[sprintf] expecting number but found %s', get_type(arg))); - } - switch (match[8]) { - case 'b': arg = arg.toString(2); break; - case 'c': arg = String.fromCharCode(arg); break; - case 'd': arg = parseInt(arg, 10); break; - case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; - case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; - case 'o': arg = arg.toString(8); break; - case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; - case 'u': arg = arg >>> 0; break; - case 'x': arg = arg.toString(16); break; - case 'X': arg = arg.toString(16).toUpperCase(); break; - } - arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); - pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; - pad_length = match[6] - String(arg).length; - pad = match[6] ? str_repeat(pad_character, pad_length) : ''; - output.push(match[5] ? arg + pad : pad + arg); - } - } - return output.join(''); - }; - - sprintf.cache = {}; - - sprintf.parse = function(fmt) { - var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; - while (_fmt) { - if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { - parse_tree.push(match[0]); - } - else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { - parse_tree.push('%'); - } - else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1; - var field_list = [], replacement_field = match[2], field_match = []; - if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - } - else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - } - else { - throw('[sprintf] huh?'); - } - } - } - else { - throw('[sprintf] huh?'); - } - match[2] = field_list; - } - else { - arg_names |= 2; - } - if (arg_names === 3) { - throw('[sprintf] mixing positional and named placeholders is not (yet) supported'); - } - parse_tree.push(match); - } - else { - throw('[sprintf] huh?'); - } - _fmt = _fmt.substring(match[0].length); - } - return parse_tree; - }; - - var vsprintf = function(fmt, argv, _argv) { - _argv = argv.slice(0); - _argv.splice(0, 0, fmt); - return sprintf.apply(null, _argv); - }; - - /** - * helpers - */ - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); - } - - function str_repeat(input, multiplier) { - for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} - return output.join(''); - } - - /** - * export to either browser or node.js - */ - ctx.sprintf = sprintf; - ctx.vsprintf = vsprintf; -})(); - - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - // How frequently softphone logs should be collected and reported to shared worker. - var SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS = 5000; - - // How frequently logs should be collected and sent downstream - var LOGS_REPORT_INTERVAL_MILLIS = 5000; - - // The default log roll interval (30min) - var DEFAULT_LOG_ROLL_INTERVAL = 1800000; - - /** - * An enumeration of common logging levels. - */ - var LogLevel = { - TEST: "TEST", - TRACE: "TRACE", - DEBUG: "DEBUG", - INFO: "INFO", - LOG: "LOG", - WARN: "WARN", - ERROR: "ERROR", - CRITICAL: "CRITICAL" - }; - - /** - * An enumeration of common logging components. - */ - var LogComponent = { - CCP: "ccp", - SOFTPHONE: "softphone", - CHAT: "chat", - TASK: "task" - }; - - /** - * The numeric order of the logging levels above. - * They are spaced to allow the addition of other log - * levels at a later time. - */ - var LogLevelOrder = { - TEST: 0, - TRACE: 10, - DEBUG: 20, - INFO: 30, - LOG: 40, - WARN: 50, - ERROR: 100, - CRITICAL: 200 - - }; - - /** - * A map from log level to console logger function. - */ - var CONSOLE_LOGGER_MAP = { - TRACE: function (text) { console.info(text); }, - DEBUG: function (text) { console.info(text); }, - INFO: function (text) { console.info(text); }, - LOG: function (text) { console.log(text); }, - TEST: function (text) { console.log(text); }, - WARN: function (text) { console.warn(text); }, - ERROR: function (text) { console.error(text); }, - CRITICAL: function (text) { console.error(text); } - }; - - /** - * Checks if it is a valid log component enum - */ - - var isValidLogComponent = function (component) { - return Object.values(LogComponent).indexOf(component) !== -1; - }; - - /** - * Extract the custom arguments as required by the logger - */ - var extractLoggerArgs = function (loggerArgs) { - var args = Array.prototype.slice.call(loggerArgs, 0); - var firstArg = args.shift(); - var format; - var component; - - if (isValidLogComponent(firstArg)) { - component = firstArg; - format = args.shift(); - } else { - //default to CCP component - format = firstArg; - component = LogComponent.CCP; - } - - return { - format: format, - component: component, - args: args - }; - }; - - /** - * A log entry. - * - * @param component The logging component. - * @param level The log level of this log entry. - * @param text The text contained in the log entry. - * @param loggerId The root logger id. - * - * Log entries are aware of their timestamp, order, - * and can contain objects and exception stack traces. - */ - var LogEntry = function (component, level, text, loggerId) { - this.component = component; - this.level = level; - this.text = text; - this.time = new Date(); - this.exception = null; - this.objects = []; - this.line = 0; - this.agentResourceId = null; - try { - if (connect.agent.initialized){ - this.agentResourceId = new connect.Agent()._getResourceId(); - } - } catch(e) { - console.log("Issue finding agentResourceId: ", e); //can't use our logger here as we might infinitely attempt to log this error. - } - this.loggerId = loggerId; - }; - - LogEntry.fromObject = function (obj) { - var entry = new LogEntry(LogComponent.CCP, obj.level, obj.text, obj.loggerId); - - // Required to check for Date objects sent across frame boundaries - if (Object.prototype.toString.call(obj.time) === '[object Date]') { - entry.time = new Date(obj.time.getTime()); - } else if (typeof obj.time === 'number') { - entry.time = new Date(obj.time); - } else if (typeof obj.time === 'string') { - entry.time = Date.parse(obj.time); - } else { - entry.time = new Date(); - } - entry.exception = obj.exception; - entry.objects = obj.objects; - return entry; - }; - - /** - * Private method to remove sensitive info from client log - */ - var redactSensitiveInfo = function(data) { - var regex = /AuthToken.*\=/g; - if(data && typeof data === 'object') { - Object.keys(data).forEach(function(key) { - if (typeof data[key] === 'object') { - redactSensitiveInfo(data[key]) - } else if(typeof data[key] === 'string') { - if (key === "url" || key === "text") { - data[key] = data[key].replace(regex, "[redacted]"); - } else if (key === "quickConnectName") { - data[key] = "[redacted]"; - } - } - }); - } - } - - /** - * Pulls the type, message, and stack trace - * out of the given exception for JSON serialization. - */ - 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') : []; - }; - - /** - * Minimally stringify this log entry for printing - * to the console. - */ - LogEntry.prototype.toString = function () { - return connect.sprintf("[%s] [%s] [%s]: %s", - this.getTime() && this.getTime().toISOString ? this.getTime().toISOString() : "???", - this.getLevel(), - this.getAgentResourceId(), - this.getText()); - }; - - /** - * Get the log entry timestamp. - */ - LogEntry.prototype.getTime = function () { - return this.time; - }; - - LogEntry.prototype.getAgentResourceId = function () { - return this.agentResourceId; - } - - /** - * Get the level of the log entry. - */ - LogEntry.prototype.getLevel = function () { - return this.level; - }; - - /** - * Get the log entry text. - */ - LogEntry.prototype.getText = function () { - return this.text; - }; - - /** - * Get the log entry component. - */ - LogEntry.prototype.getComponent = function () { - return this.component; - }; - - /** - * Add an exception stack trace to this log entry. - * A log entry may contain only one exception stack trace. - */ - LogEntry.prototype.withException = function (e) { - this.exception = new LoggedException(e); - return this; - }; - - /** - * Add an arbitrary object to the log entry. A log entry - * may contain any number of objects. - */ - LogEntry.prototype.withObject = function (obj) { - var copiedObj = connect.deepcopy(obj); - redactSensitiveInfo(copiedObj); - this.objects.push(copiedObj); - return this; - }; - - /** - * Add a cross origin event object to the log entry. A log entry - * may contain any number of objects. - */ - LogEntry.prototype.withCrossOriginEventObject = function (obj) { - var copiedObj = connect.deepcopyCrossOriginEvent(obj); - redactSensitiveInfo(copiedObj); - this.objects.push(copiedObj); - return this; - }; - - /** - * Indicate that this log entry should be sent to the server - * NOTE: This should be used for internal logs only - */ - LogEntry.prototype.sendInternalLogToServer = function () { - connect.getLog()._serverBoundInternalLogs.push(this); - return this; - }; - - /** - * The logger instance. - */ - var Logger = function () { - this._logs = []; - this._rolledLogs = []; - this._logsToPush = []; - this._serverBoundInternalLogs = []; - this._echoLevel = LogLevelOrder.INFO; - this._logLevel = LogLevelOrder.INFO; - this._lineCount = 0; - this._logRollInterval = 0; - this._logRollTimer = null; - this._loggerId = new Date().getTime() + "-" + Math.random().toString(36).slice(2); - this.setLogRollInterval(DEFAULT_LOG_ROLL_INTERVAL); - this._startLogIndexToPush = 0; - }; - - /** - * Sets the interval in milliseconds that the logs will be rotated. - * Logs are rotated out completely at the end of the second roll - * and will eventually be garbage collected. - */ - Logger.prototype.setLogRollInterval = function (interval) { - var self = this; - - if (!(this._logRollTimer) || interval !== this._logRollInterval) { - if (this._logRollTimer) { - global.clearInterval(this._logRollTimer); - } - this._logRollInterval = interval; - this._logRollTimer = global.setInterval(function () { - this._rolledLogs = this._logs; - this._logs = []; - this._startLogIndexToPush = 0; - self.info("Log roll interval occurred."); - }, this._logRollInterval); - } else { - this.warn("Logger is already set to the given interval: %d", this._logRollInterval); - } - }; - - /** - * Set the log level. This is the minimum level at which logs will - * be kept for later archiving. - */ - Logger.prototype.setLogLevel = function (level) { - if (level in LogLevelOrder) { - this._logLevel = LogLevelOrder[level]; - } else { - throw new Error("Unknown logging level: " + level); - } - }; - - /** - * Set the echo level. This is the minimum level at which logs will - * be printed to the javascript console. - */ - Logger.prototype.setEchoLevel = function (level) { - if (level in LogLevelOrder) { - this._echoLevel = LogLevelOrder[level]; - } else { - throw new Error("Unknown logging level: " + level); - } - }; - - /** - * Write a particular log entry. - * - * @param level The logging level of the entry. - * @param text The text contents of the entry. - * - * @returns The new log entry. - */ - Logger.prototype.write = function (component, level, text) { - var logEntry = new LogEntry(component, level, text, this.getLoggerId()); - redactSensitiveInfo(logEntry); - this.addLogEntry(logEntry); - return logEntry; - }; - - Logger.prototype.addLogEntry = function (logEntry) { - // Call this second time as in some places this function is called directly - redactSensitiveInfo(logEntry); - this._logs.push(logEntry); - - //For now only send softphone logs only. - //TODO add CCP logs once we are sure that no sensitive data is being logged. - if (LogComponent.SOFTPHONE === logEntry.component) { - this._logsToPush.push(logEntry); - } - - if (logEntry.level in LogLevelOrder && - LogLevelOrder[logEntry.level] >= this._logLevel) { - - if (LogLevelOrder[logEntry.level] >= this._echoLevel) { - CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); - } - - logEntry.line = this._lineCount++; - } - }; - - Logger.prototype.sendInternalLogEntryToServer = function (logEntry) { - this._serverBoundInternalLogs.push(logEntry); - - if (logEntry.level in LogLevelOrder && - LogLevelOrder[logEntry.level] >= this._logLevel) { - - if (LogLevelOrder[logEntry.level] >= this._echoLevel) { - CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); - } - - logEntry.line = this._lineCount++; - } - }; - - /** - * Remove all objects from all log entries. - */ - Logger.prototype.clearObjects = function () { - for (var x = 0; x < this._logs.length; x++) { - if (this._logs[x].objects) { - delete this._logs[x].objects; - } - } - }; - - /** - * Remove all exception stack traces from the log entries. - */ - Logger.prototype.clearExceptions = function () { - for (var x = 0; x < this._logs.length; x++) { - if (this._logs[x].exception) { - delete this._logs[x].exception; - } - } - }; - - Logger.prototype.trace = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.TRACE, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.debug = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.DEBUG, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.info = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.INFO, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.log = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.LOG, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.test = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.TEST, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.warn = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.WARN, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.error = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - Logger.prototype.critical = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - /** - * Create a string representation of the logger contents. - */ - Logger.prototype.toString = function () { - var lines = []; - for (var x = 0; x < this._logs.length; x++) { - lines.push(this._logs[x].toString()); - } - - return lines.join("\n"); - }; - - /** - * Download/Archive logs to a file, - * By default, it returns all logs. - * To filter logs by the minimum log level set by setLogLevel or the default set in _logLevel, - * pass in filterByLogLevel to true in options - * - * @param options download options [Object|String]. - * - of type Object: - * { logName: 'my-log-name', - * filterByLogLevel: false, //download all logs - * } - * - of type String (for backward compatibility), the file's name - */ - Logger.prototype.download = function(options) { - var logName = 'agent-log'; - var filterByLogLevel = false; - - if (typeof options === 'object') { - logName = options.logName || logName; - filterByLogLevel = options.filterByLogLevel || filterByLogLevel; - } - else if (typeof options === 'string') { - logName = options || logName; - } - - var self = this; - var logs = this._rolledLogs.concat(this._logs); - if (filterByLogLevel) { - logs = logs.filter(function(entry) { - return LogLevelOrder[entry.level] >= self._logLevel; - }); - } - - var logBlob = new global.Blob([JSON.stringify(logs, undefined, 4)], ['text/plain']); - var downloadLink = document.createElement('a'); - var logName = logName || 'agent-log'; - downloadLink.href = global.URL.createObjectURL(logBlob); - downloadLink.download = logName + '.txt'; - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }; - - Logger.prototype.scheduleUpstreamLogPush = function (conduit) { - if (!connect.upstreamLogPushScheduled) { - connect.upstreamLogPushScheduled = true; - /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to LARS*/ - global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); - } - }; - - Logger.prototype.reportMasterLogsUpStream = function (conduit) { - var logsToPush = this._logsToPush.slice(); - this._logsToPush = []; - connect.ifMaster(connect.MasterTopics.SEND_LOGS, function () { - if (logsToPush.length > 0) { - conduit.sendUpstream(connect.EventType.SEND_LOGS, logsToPush); - } - }); - }; - - Logger.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush = function(conduit) { - global.setInterval(connect.hitch(this, this.pushOuterContextCCPserverBoundLogsUpstream, conduit), 1000); - } - - Logger.prototype.scheduleUpstreamOuterContextCCPLogsPush = function(conduit) { - global.setInterval(connect.hitch(this, this.pushOuterContextCCPLogsUpstream, conduit), 1000); - } - - Logger.prototype.pushOuterContextCCPserverBoundLogsUpstream = function(conduit) { - if (this._serverBoundInternalLogs.length > 0) { - for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { - this._serverBoundInternalLogs[i].text = this._serverBoundInternalLogs[i].text; - } - - conduit.sendUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs); - this._serverBoundInternalLogs = []; - } - } - - Logger.prototype.pushOuterContextCCPLogsUpstream = function(conduit) { - for (var i = this._startLogIndexToPush; i < this._logs.length; i++) { - if (this._logs[i].loggerId !== this._loggerId) { - continue; - } - conduit.sendUpstream(connect.EventType.LOG, this._logs[i]); - } - this._startLogIndexToPush = this._logs.length; - } - - Logger.prototype.getLoggerId = function () { - return this._loggerId; - }; - - Logger.prototype.scheduleDownstreamClientSideLogsPush = function () { - global.setInterval(connect.hitch(this, this.pushClientSideLogsDownstream), LOGS_REPORT_INTERVAL_MILLIS); - } - - Logger.prototype.pushClientSideLogsDownstream = function () { - var logs = []; - - // We do not send a request if we have less than 50 records so that we minimize the number of - // requests per second. - // 500 is the max we accept on the server. - // We chose 500 because this is the limit imposed by Firehose for a put batch request - if (this._serverBoundInternalLogs.length < 50) { - return; - } else if (this._serverBoundInternalLogs.length > 500) { - logs = this._serverBoundInternalLogs.splice(0, 500); - } else { - logs = this._serverBoundInternalLogs; - this._serverBoundInternalLogs = []; - } - - connect.publishClientSideLogs(logs); - } - - var DownstreamConduitLogger = function (conduit) { - Logger.call(this); - this.conduit = conduit; - - global.setInterval(connect.hitch(this, this._pushLogsDownstream), - DownstreamConduitLogger.LOG_PUSH_INTERVAL); - - // Disable log rolling, we will purge our own logs once they have - // been pushed downstream. - global.clearInterval(this._logRollTimer); - this._logRollTimer = null; - }; - // How frequently logs should be collected and delivered downstream. - DownstreamConduitLogger.LOG_PUSH_INTERVAL = 1000; - DownstreamConduitLogger.prototype = Object.create(Logger.prototype); - DownstreamConduitLogger.prototype.constructor = DownstreamConduitLogger; - - DownstreamConduitLogger.prototype.pushLogsDownstream = function (logs) { - var self = this; - logs.forEach(function (log) { - self.conduit.sendDownstream(connect.EventType.LOG, log); - }); - }; - - DownstreamConduitLogger.prototype._pushLogsDownstream = function () { - var self = this; - - this._logs.forEach(function (log) { - self.conduit.sendDownstream(connect.EventType.LOG, log); - }); - this._logs = []; - - for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { - this.conduit.sendDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs[i]); - } - - this._serverBoundInternalLogs = []; - }; - - /** - * Wrap a function with try catch block - */ - var tryCatchWrapperMethod = function (fn) { - var wrappedfunction = function() { - try { - return fn.apply(this, arguments); - } catch (e) { - // Since this wraps Logger class, we can only print it in the console and eat it. - CONSOLE_LOGGER_MAP.ERROR(e); - } - } - return wrappedfunction; - } - /** - * This is a wrapper method to wrap each function - * in an object with try catch block. - */ - var tryCatchWrapperObject = function (obj) { - for (var method in obj) { - if (typeof(obj[method]) === 'function') { - obj[method] = tryCatchWrapperMethod(obj[method]); - } - } - } - - /** Create the singleton logger instance. */ - connect.rootLogger = new Logger(); - tryCatchWrapperObject(connect.rootLogger); - - - /** Fetch the singleton logger instance. */ - var getLog = function () { - return connect.rootLogger; - }; - - connect = connect || {}; - connect.getLog = getLog; - connect.LogEntry = LogEntry; - connect.Logger = Logger; - connect.LogLevel = LogLevel; - connect.LogComponent = LogComponent; - connect.DownstreamConduitLogger = DownstreamConduitLogger; -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - var userAgent = navigator.userAgent; - var ONE_DAY_MILLIS = 24 * 60 * 60 * 1000; - var DEFAULT_POPUP_HEIGHT = 578; - var DEFAULT_POPUP_WIDTH = 433; - var COPYABLE_EVENT_FIELDS = ["bubbles", "cancelBubble", "cancelable", "composed", "data", "defaultPrevented", "eventPhase", "isTrusted", "lastEventId", "origin", "returnValue", "timeStamp", "type"]; - - /** - * Unpollute sprintf functions from the global namespace. - */ - connect.sprintf = global.sprintf; - connect.vsprintf = global.vsprintf; - delete global.sprintf; - delete global.vsprintf; - - connect.HTTP_STATUS_CODES = { - SUCCESS: 200, - TOO_MANY_REQUESTS: 429, - INTERNAL_SERVER_ERROR: 500 - }; - - connect.TRANSPORT_TYPES = { - CHAT_TOKEN: "chat_token", - WEB_SOCKET: "web_socket" - }; - - /** - * Binds the given instance object as the context for - * the method provided. - * - * @param scope The instance object to be set as the scope - * of the function. - * @param method The method to be encapsulated. - * - * All other arguments, if any, are bound to the method - * invocation inside the closure. - * - * @return A closure encapsulating the invocation of the - * method provided in context of the given instance. - */ - connect.hitch = function () { - var args = Array.prototype.slice.call(arguments); - var scope = args.shift(); - var method = args.shift(); - - connect.assertNotNull(scope, 'scope'); - connect.assertNotNull(method, 'method'); - connect.assertTrue(connect.isFunction(method), 'method must be a function'); - - return function () { - var closureArgs = Array.prototype.slice.call(arguments); - return method.apply(scope, args.concat(closureArgs)); - }; - }; - - /** - * Determine if the given value is a callable function type. - * Borrowed from Underscore.js. - */ - connect.isFunction = function (obj) { - return !!(obj && obj.constructor && obj.call && obj.apply); - }; - - /** - * Determine if the given value is an array. - */ - connect.isArray = function (obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; - }; - - /** - * Get a list of keys from a Javascript object used - * as a hash map. - */ - connect.keys = function (map) { - var keys = []; - - connect.assertNotNull(map, 'map'); - - for (var k in map) { - keys.push(k); - } - - return keys; - }; - - /** - * Get a list of values from a Javascript object used - * as a hash map. - */ - connect.values = function (map) { - var values = []; - - connect.assertNotNull(map, 'map'); - - for (var k in map) { - values.push(map[k]); - } - - return values; - }; - - /** - * Get a list of key/value pairs from the given map. - */ - connect.entries = function (map) { - var entries = []; - - for (var k in map) { - entries.push({ key: k, value: map[k] }); - } - - return entries; - }; - - /** - * Merge two or more maps together into a new map, - * or simply copy a single map. - */ - connect.merge = function () { - var argMaps = Array.prototype.slice.call(arguments, 0); - var resultMap = {}; - - argMaps.forEach(function (map) { - connect.entries(map).forEach(function (kv) { - resultMap[kv.key] = kv.value; - }); - }); - - return resultMap; - }; - - connect.now = function () { - return new Date().getTime(); - }; - - connect.find = function (array, predicate) { - for (var x = 0; x < array.length; x++) { - if (predicate(array[x])) { - return array[x]; - } - } - - return null; - }; - - connect.contains = function (obj, value) { - if (obj instanceof Array) { - return connect.find(obj, function (v) { return v === value; }) != null; - - } else { - return (value in obj); - } - }; - - connect.containsValue = function (obj, value) { - if (obj instanceof Array) { - return connect.find(obj, function (v) { return v === value; }) != null; - - } else { - return connect.find(connect.values(obj), function (v) { return v === value; }) != null; - } - }; - - /** - * Generate a random ID consisting of the current timestamp - * and a random base-36 number based on Math.random(). - */ - connect.randomId = function () { - return connect.sprintf("%s-%s", connect.now(), Math.random().toString(36).slice(2)); - }; - - /** - * Generate an enum from the given list of lower-case enum values, - * where the enum keys will be upper case. - * - * Conversion from pascal case based on code from here: - * http://stackoverflow.com/questions/30521224 - */ - connect.makeEnum = function (values) { - var enumObj = {}; - - values.forEach(function (value) { - var key = value.replace(/\.?([a-z]+)_?/g, function (x, y) { return y.toUpperCase() + "_"; }) - .replace(/_$/, ""); - - enumObj[key] = value; - }); - - return enumObj; - }; - - connect.makeNamespacedEnum = function (prefix, values) { - var enumObj = connect.makeEnum(values); - connect.keys(enumObj).forEach(function (key) { - enumObj[key] = connect.sprintf("%s::%s", prefix, enumObj[key]); - }); - return enumObj; - }; - - connect.makeGenericNamespacedEnum = function (prefix, values, delimiter) { - var enumObj = connect.makeEnum(values); - connect.keys(enumObj).forEach(function (key) { - enumObj[key] = connect.sprintf("%s"+delimiter+"%s", prefix, enumObj[key]); - }); - return enumObj; - }; - - /** - * Methods to determine browser type and versions, used for softphone initialization. - */ - connect.isChromeBrowser = function () { - return userAgent.indexOf("Chrome") !== -1; - }; - - connect.isFirefoxBrowser = function () { - return userAgent.indexOf("Firefox") !== -1; - }; - - connect.isOperaBrowser = function () { - return userAgent.indexOf("Opera") !== -1; - }; - - connect.getChromeBrowserVersion = function () { - var chromeVersion = userAgent.substring(userAgent.indexOf("Chrome") + 7); - if (chromeVersion) { - return parseFloat(chromeVersion); - } else { - return -1; - } - }; - - connect.getFirefoxBrowserVersion = function () { - var firefoxVersion = userAgent.substring(userAgent.indexOf("Firefox") + 8); - if (firefoxVersion) { - return parseFloat(firefoxVersion); - } else { - return -1; - } - }; - - connect.isValidLocale = function (locale) { - var languages = [ - { - id: 'en_US', - label: 'English' - }, - { - id: 'de_DE', - label: 'Deutsch' - }, - { - id: 'es_ES', - label: 'Español' - }, - { - id: 'fr_FR', - label: 'Français' - }, - { - id: 'ja_JP', - label: '日本語' - }, - { - id: 'it_IT', - label: 'Italiano' - }, - { - id: 'ko_KR', - label: '한국어' - }, - { - id: 'pt_BR', - label: 'Português' - }, - { - id: 'zh_CN', - label: '中文(简体)' - }, - { - id: 'zh_TW', - label: '中文(繁體)' - } - ]; - return languages.map(function(language){ return language.id}).includes(locale); - } - - connect.getOperaBrowserVersion = function () { - var versionOffset = userAgent.indexOf("Opera"); - var operaVersion = (userAgent.indexOf("Version") !== -1) ? userAgent.substring(versionOffset + 8) : userAgent.substring(versionOffset + 6); - if (operaVersion) { - return parseFloat(operaVersion); - } else { - return -1; - } - }; - - /** - * Return a map of items in the given list indexed by - * keys determined by the closure provided. - * - * @param iterable A list-like object. - * @param closure A closure to determine the index for the - * items in the iterable. - * @return A map from index to item for each item in the iterable. - */ - connect.index = function (iterable, closure) { - var map = {}; - - iterable.forEach(function (item) { - map[closure(item)] = item; - }); - - return map; - }; - - /** - * Converts the given array into a map as a set, - * where elements in the array are mapped to 1. - */ - connect.set = function (arrayIn) { - var setMap = {}; - - arrayIn.forEach(function (key) { - setMap[key] = 1; - }); - - return setMap; - }; - - /** - * Returns a map for each key in mapB which - * is NOT in mapA. - */ - connect.relativeComplement = function (mapA, mapB) { - var compMap = {}; - - connect.keys(mapB).forEach(function (key) { - if (!(key in mapA)) { - compMap[key] = mapB[key]; - } - }); - - return compMap; - }; - - /** - * Asserts that a premise is true. - */ - connect.assertTrue = function (premise, message) { - if (!premise) { - throw new connect.ValueError(message); - } - }; - - /** - * Asserts that a value is not null or undefined. - */ - connect.assertNotNull = function (value, name) { - connect.assertTrue(value != null && typeof value !== undefined, - connect.sprintf("%s must be provided", name || 'A value')); - return value; - }; - - connect.deepcopy = function (src) { - return JSON.parse(JSON.stringify(src)); - }; - - connect.deepcopyCrossOriginEvent = function(event) { - const obj = {}; - const listOfAcceptableKeys = COPYABLE_EVENT_FIELDS; - listOfAcceptableKeys.forEach((key) => { - try { - obj[key] = event[key]; - } - catch(e) { - connect.getLog().info("deepcopyCrossOriginEvent failed on key: ", key).sendInternalLogToServer(); - } - }); - return connect.deepcopy(obj); - } - - /** - * Get the current base url of the open page, e.g. if the page is - * https://example.com:9494/oranges, this will be "https://example.com:9494". - */ - connect.getBaseUrl = function () { - var location = global.location; - return connect.sprintf("%s//%s:%s", location.protocol, location.hostname, location.port); - }; - - connect.getUrlWithProtocol = function(url) { - var protocol = global.location.protocol; - if (url.substr(0, protocol.length) !== protocol) { - return connect.sprintf("%s//%s", protocol, url); - } - return url; - } - - /** - * Determine if the current window is in an iframe. - * Courtesy: http://stackoverflow.com/questions/326069/ - */ - connect.isFramed = function () { - try { - return window.self !== window.top; - } catch (e) { - return true; - } - }; - - connect.hasOtherConnectedCCPs = function () { - return connect.numberOfConnectedCCPs > 1; - } - - connect.fetch = function (endpoint, options, milliInterval, maxRetry) { - maxRetry = maxRetry || 5; - milliInterval = milliInterval || 1000; - options = options || {}; - return new Promise(function (resolve, reject) { - function fetchData(maxRetry) { - fetch(endpoint, options).then(function (res) { - if (res.status === connect.HTTP_STATUS_CODES.SUCCESS) { - res.json().then(json => resolve(json)).catch(() => resolve({})); - } else if (maxRetry !== 1 && (res.status >= connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR || res.status === connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)) { - setTimeout(function () { - fetchData(--maxRetry); - }, milliInterval); - } else { - reject(res); - } - }).catch(function (e) { - reject(e); - }); - } - fetchData(maxRetry); - }); - }; - - /** - * Calling a function with exponential backoff with full jitter retry strategy - * It will retry calling the function for maximum maxRetry times if it fails. - * Success callback will be called if the function succeeded. - * Failure callback will be called only if the last try failed. - */ - connect.backoff = function (func, milliInterval, maxRetry, callbacks) { - connect.assertTrue(connect.isFunction(func), "func must be a Function"); - var self = this; - var ratio = 2; - - func({ - success: function (data) { - if (callbacks && callbacks.success) { - callbacks.success(data); - } - }, - failure: function (err, data) { - if (maxRetry > 0) { - var interval = milliInterval * 2 * Math.random(); - global.setTimeout(function () { - self.backoff(func, interval * ratio, --maxRetry, callbacks); - }, interval); - } else { - if (callbacks && callbacks.failure) { - callbacks.failure(err, data); - } - } - } - }); - }; - - connect.publishMetric = function (metricData) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.CLIENT_METRIC, - data: metricData - }); - }; - - connect.publishSoftphoneStats = function(stats) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.SOFTPHONE_STATS, - data: stats - }); - }; - - connect.publishSoftphoneReport = function(report) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.SOFTPHONE_REPORT, - data: report - }); - }; - - connect.publishClientSideLogs = function(logs) { - var bus = connect.core.getEventBus(); - bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); - }; - - /** - * A wrapper around Window.open() for managing single instance popups. - */ - connect.PopupManager = function () { }; - - connect.PopupManager.prototype.open = function (url, name, options) { - var then = this._getLastOpenedTimestamp(name); - var now = new Date().getTime(); - var win = null; - if (now - then > ONE_DAY_MILLIS) { - if (options) { - // default values are chosen to provide a minimum height without scrolling - // and a uniform margin based on the css of the ccp login page - var height = options.height || DEFAULT_POPUP_HEIGHT; - var width = options.width || DEFAULT_POPUP_WIDTH; - var top = options.top || 0; - var left = options.left || 0; - win = window.open('', name, "width="+width+", height="+height+", top="+top+", left="+left); - if (win.location !== url) { - win = window.open(url, name, "width="+width+", height="+height+", top="+top+", left="+left); - } - } else { - win = window.open('', name); - if (win.location !== url) { - win = window.open(url, name); - } - } - this._setLastOpenedTimestamp(name, now); - } - return win; - }; - - connect.PopupManager.prototype.clear = function (name) { - var key = this._getLocalStorageKey(name); - global.localStorage.removeItem(key); - }; - - connect.PopupManager.prototype._getLastOpenedTimestamp = function (name) { - var key = this._getLocalStorageKey(name); - var value = global.localStorage.getItem(key); - - if (value) { - return parseInt(value, 10); - - } else { - return 0; - } - }; - - connect.PopupManager.prototype._setLastOpenedTimestamp = function (name, ts) { - var key = this._getLocalStorageKey(name); - global.localStorage.setItem(key, '' + ts); - }; - - connect.PopupManager.prototype._getLocalStorageKey = function (name) { - return "connectPopupManager::" + name; - }; - - /** - * An enumeration of the HTML5 notification permission values. - */ - var NotificationPermission = connect.makeEnum([ - 'granted', - 'denied', - 'default' - ]); - - /** - * A simple engine for showing notification popups. - */ - connect.NotificationManager = function () { - this.queue = []; - this.permission = NotificationPermission.DEFAULT; - }; - - connect.NotificationManager.prototype.requestPermission = function () { - var self = this; - if (!("Notification" in global)) { - connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(); - this.permission = NotificationPermission.DENIED; - - } else if (global.Notification.permission === NotificationPermission.DENIED) { - connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(); - this.permission = NotificationPermission.DENIED; - - } else if (this.permission !== NotificationPermission.GRANTED) { - global.Notification.requestPermission().then(function (permission) { - self.permission = permission; - if (permission === NotificationPermission.GRANTED) { - self._showQueued(); - - } else { - self.queue = []; - } - }); - } - }; - - connect.NotificationManager.prototype.show = function (title, options) { - if (this.permission === NotificationPermission.GRANTED) { - return this._showImpl({ title: title, options: options }); - - } else if (this.permission === NotificationPermission.DENIED) { - connect.getLog().warn("Unable to show notification.") - .sendInternalLogToServer() - .withObject({ - title: title, - options: options - }); - - } else { - var params = { title: title, options: options }; - connect.getLog().warn("Deferring notification until user decides to allow or deny.") - .withObject(params) - .sendInternalLogToServer(); - this.queue.push(params); - } - }; - - connect.NotificationManager.prototype._showQueued = function () { - var self = this; - var notifications = this.queue.map(function (params) { - return self._showImpl(params); - }); - this.queue = []; - return notifications; - }; - - connect.NotificationManager.prototype._showImpl = function (params) { - var notification = new global.Notification(params.title, params.options); - if (params.options.clicked) { - notification.onclick = function () { - params.options.clicked.call(notification); - }; - } - return notification; - }; - - connect.BaseError = function (format, args) { - global.Error.call(this, connect.vsprintf(format, args)); - }; - connect.BaseError.prototype = Object.create(Error.prototype); - connect.BaseError.prototype.constructor = connect.BaseError; - - connect.ValueError = function () { - var args = Array.prototype.slice.call(arguments, 0); - var format = args.shift(); - connect.BaseError.call(this, format, args); - }; - connect.ValueError.prototype = Object.create(connect.BaseError.prototype); - connect.ValueError.prototype.constructor = connect.ValueError; - - connect.NotImplementedError = function () { - var args = Array.prototype.slice.call(arguments, 0); - var format = args.shift(); - connect.BaseError.call(this, format, args); - }; - connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype); - connect.NotImplementedError.prototype.constructor = connect.NotImplementedError; - - connect.StateError = function () { - var args = Array.prototype.slice.call(arguments, 0); - var format = args.shift(); - connect.BaseError.call(this, format, args); - }; - connect.StateError.prototype = Object.create(connect.BaseError.prototype); - connect.StateError.prototype.constructor = connect.StateError; - - connect.VoiceIdError = function(type, message, err){ - var error = {}; - error.type = type; - error.message = message; - error.stack = Error(message).stack; - error.err = err; - return error; - } - - // internal use only - connect.isCCP = function () { - var conduit = connect.core.getUpstream(); - return conduit.name === 'ConnectSharedWorkerConduit'; - } -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - var ALL_EVENTS = '<>'; - - /**--------------------------------------------------------------- - * enum EventType - */ - var EventType = connect.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", - "update_connected_ccps", - "outer_context_info", - "media_device_request", - "media_device_response" - ]); - - /**--------------------------------------------------------------- - * enum MasterTopics - */ - var MasterTopics = connect.makeNamespacedEnum('connect', [ - 'loginPopup', - 'sendLogs', - 'softphone', - 'ringtone', - 'metrics' - ]); - - /**--------------------------------------------------------------- - * enum AgentEvents - */ - var AgentEvents = connect.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' - ]); - - /**--------------------------------------------------------------- - * enum WebSocketEvents - */ - var WebSocketEvents = connect.makeNamespacedEnum('webSocket', [ - 'init_failure', - 'connection_open', - 'connection_close', - 'connection_error', - 'connection_gain', - 'connection_lost', - 'subscription_update', - 'subscription_failure', - 'all_message', - 'send', - 'subscribe' - ]); - - /**--------------------------------------------------------------- - * enum ContactEvents - */ - var ContactEvents = connect.makeNamespacedEnum('contact', [ - 'init', - 'refresh', - 'destroyed', - 'incoming', - 'pending', - 'connecting', - 'connected', - 'missed', - 'acw', - 'view', - 'ended', - 'error', - 'accepted' - ]); - - var ChannelViewEvents = connect.makeNamespacedEnum('taskList', [ - 'activate_channel_with_view_type' - ]); - - var TaskEvents = connect.makeNamespacedEnum('task', [ - 'created' - ]); - - - /**--------------------------------------------------------------- - * enum ConnectionEvents - */ - var ConnectionEvents = connect.makeNamespacedEnum('connection', [ - 'session_init', - 'ready_to_start_session' - ]); - - /**--------------------------------------------------------------- - * enum Configuration Events - */ - var ConfigurationEvents = connect.makeNamespacedEnum('configuration', [ - 'configure', - 'set_speaker_device', - 'set_microphone_device', - 'set_ringer_device', - 'speaker_device_changed', - 'microphone_device_changed', - 'ringer_device_changed' - ]); - - /**--------------------------------------------------------------- - * enum VoiceId Events - */ - var VoiceIdEvents = connect.makeNamespacedEnum('voiceId', [ - 'update_domain_id' - ]); - - /**--------------------------------------------------------------- - * class EventFactory - */ - var EventFactory = function () { }; - EventFactory.createRequest = function (type, method, params) { - return { - event: type, - requestId: connect.randomId(), - method: method, - params: params - }; - }; - - EventFactory.createResponse = function (type, request, data, err) { - return { - event: type, - requestId: request.requestId, - data: data, - err: err || null - }; - }; - - /** - * An object representing an event subscription in an EventBus. - */ - var Subscription = function (subMap, eventName, f) { - this.subMap = subMap; - this.id = connect.randomId(); - this.eventName = eventName; - this.f = f; - }; - - /** - * Unsubscribe the handler of this subscription from the EventBus - * from which it was created. - */ - Subscription.prototype.unsubscribe = function () { - this.subMap.unsubscribe(this.eventName, this.id); - }; - - /** - * A map of event subscriptions, used by the EventBus. - */ - var SubscriptionMap = function () { - this.subIdMap = {}; - this.subEventNameMap = {}; - }; - - /** - * Add a subscription for the named event. Creates a new Subscription - * object and returns it. This object can be used to unsubscribe. - */ - SubscriptionMap.prototype.subscribe = function (eventName, f) { - var sub = new Subscription(this, eventName, f); - - this.subIdMap[sub.id] = sub; - var subList = this.subEventNameMap[eventName] || []; - subList.push(sub); - this.subEventNameMap[eventName] = subList; - return sub; - }; - - /** - * Unsubscribe a subscription matching the given event name and id. - */ - SubscriptionMap.prototype.unsubscribe = function (eventName, subId) { - if (connect.contains(this.subEventNameMap, eventName)) { - this.subEventNameMap[eventName] = this.subEventNameMap[eventName].filter(function (s) { return s.id !== subId; }); - - if (this.subEventNameMap[eventName].length < 1) { - delete this.subEventNameMap[eventName]; - } - } - - if (connect.contains(this.subIdMap, subId)) { - delete this.subIdMap[subId]; - } - }; - - /** - * Get a list of all subscriptions in the subscription map. - */ - SubscriptionMap.prototype.getAllSubscriptions = function () { - return connect.values(this.subEventNameMap).reduce(function (a, b) { - return a.concat(b); - }, []); - }; - - /** - * Get a list of subscriptions for the given event name, or an empty - * list if there are no subscriptions. - */ - SubscriptionMap.prototype.getSubscriptions = function (eventName) { - return this.subEventNameMap[eventName] || []; - }; - - /** - * An object which maintains a map of subscriptions and serves as the - * mechanism for triggering events to be handled by subscribers. - */ - var EventBus = function (paramsIn) { - var params = paramsIn || {}; - - this.subMap = new SubscriptionMap(); - this.logEvents = params.logEvents || false; - }; - - /** - * Subscribe to the named event. Returns a new Subscription object - * which can be used to unsubscribe. - */ - EventBus.prototype.subscribe = function (eventName, f) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.subMap.subscribe(eventName, f); - }; - - /** - * Subscribe a function to be called on all events. - */ - EventBus.prototype.subscribeAll = function (f) { - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.subMap.subscribe(ALL_EVENTS, f); - }; - - /** - * Get a list of subscriptions for the given event name, or an empty - * list if there are no subscriptions. - */ - EventBus.prototype.getSubscriptions = function (eventName) { - return this.subMap.getSubscriptions(eventName); - }; - - /** - * Trigger the given event with the given data. All methods subscribed - * to this event will be called and are provided with the given arbitrary - * data object and the name of the event, in that order. - */ - EventBus.prototype.trigger = function (eventName, data) { - connect.assertNotNull(eventName, 'eventName'); - var self = this; - var allEventSubs = this.subMap.getSubscriptions(ALL_EVENTS); - var eventSubs = this.subMap.getSubscriptions(eventName); - - if (this.logEvents && - eventName !== connect.EventType.LOG && - eventName !== connect.EventType.MASTER_RESPONSE && - eventName !== connect.EventType.API_METRIC && - eventName !== connect.EventType.SERVER_BOUND_INTERNAL_LOG - ) { - connect.getLog().trace("Publishing event: %s", eventName).sendInternalLogToServer(); - } - - if ( - eventName.startsWith(connect.ContactEvents.ACCEPTED) && - data && - data.contactId && - !(data instanceof connect.Contact) - ) { - data = new connect.Contact(data.contactId); - } - - allEventSubs.concat(eventSubs).forEach(function (sub) { - try { - sub.f(data || null, eventName, self); - } catch (e) { - connect.getLog().error("'%s' event handler failed.", eventName).withException(e).sendInternalLogToServer(); - } - }); - }; - - /** - * Returns a closure which bridges an event from another EventBus to this bus. + * credentials into your process for subsequent requests to AWS resources, + * you should use {AWS.TemporaryCredentials} instead. + * @param data [map] data retrieved from a call to {getFederatedToken}, + * {getSessionToken}, {assumeRole}, or {assumeRoleWithWebIdentity}. + * @param credentials [AWS.Credentials] an optional credentials object to + * fill instead of creating a new object. Useful when modifying an + * existing credentials object from a refresh call. + * @return [AWS.TemporaryCredentials] the set of temporary credentials + * loaded from a raw STS operation response. + * @example Using credentialsFrom to load global AWS credentials + * var sts = new AWS.STS(); + * sts.getSessionToken(function (err, data) { + * if (err) console.log("Error getting credentials"); + * else { + * AWS.config.credentials = sts.credentialsFrom(data); + * } + * }); + * @see AWS.TemporaryCredentials + */credentialsFrom:function credentialsFrom(data,credentials){if(!data)return null;if(!credentials)credentials=new AWS.TemporaryCredentials();credentials.expired=false;credentials.accessKeyId=data.Credentials.AccessKeyId;credentials.secretAccessKey=data.Credentials.SecretAccessKey;credentials.sessionToken=data.Credentials.SessionToken;credentials.expireTime=data.Credentials.Expiration;return credentials;},assumeRoleWithWebIdentity:function assumeRoleWithWebIdentity(params,callback){return this.makeUnauthenticatedRequest('assumeRoleWithWebIdentity',params,callback);},assumeRoleWithSAML:function assumeRoleWithSAML(params,callback){return this.makeUnauthenticatedRequest('assumeRoleWithSAML',params,callback);},/** + * @api private + */validateRegionalEndpointsFlagValue:function validateRegionalEndpointsFlagValue(configValue,errorOptions){if(typeof configValue==='string'&&['legacy','regional'].indexOf(configValue.toLowerCase())>=0){this.config.stsRegionalEndpoints=configValue.toLowerCase();return;}else{throw AWS.util.error(new Error(),errorOptions);}},/** + * @api private + */validateRegionalEndpointsFlag:function validateRegionalEndpointsFlag(){//validate config value +var config=this.config;if(config.stsRegionalEndpoints){this.validateRegionalEndpointsFlagValue(config.stsRegionalEndpoints,{code:'InvalidConfiguration',message:'invalid "stsRegionalEndpoints" configuration. Expect "legacy" '+' or "regional". Got "'+config.stsRegionalEndpoints+'".'});}if(!AWS.util.isNode())return;//validate environmental variable +if(Object.prototype.hasOwnProperty.call(process.env,ENV_REGIONAL_ENDPOINT_ENABLED)){var envFlag=process.env[ENV_REGIONAL_ENDPOINT_ENABLED];this.validateRegionalEndpointsFlagValue(envFlag,{code:'InvalidEnvironmentalVariable',message:'invalid '+ENV_REGIONAL_ENDPOINT_ENABLED+' environmental variable. Expect "legacy" '+' or "regional". Got "'+process.env[ENV_REGIONAL_ENDPOINT_ENABLED]+'".'});}//validate shared config file +var profile={};try{var profiles=AWS.util.getProfilesFromSharedConfig(AWS.util.iniLoader);profile=profiles[process.env.AWS_PROFILE||AWS.util.defaultProfile];}catch(e){};if(profile&&Object.prototype.hasOwnProperty.call(profile,CONFIG_REGIONAL_ENDPOINT_ENABLED)){var fileFlag=profile[CONFIG_REGIONAL_ENDPOINT_ENABLED];this.validateRegionalEndpointsFlagValue(fileFlag,{code:'InvalidConfiguration',message:'invalid '+CONFIG_REGIONAL_ENDPOINT_ENABLED+' profile config. Expect "legacy" '+' or "regional". Got "'+profile[CONFIG_REGIONAL_ENDPOINT_ENABLED]+'".'});}},/** + * @api private + */optInRegionalEndpoint:function optInRegionalEndpoint(){this.validateRegionalEndpointsFlag();var config=this.config;if(config.stsRegionalEndpoints==='regional'){regionConfig(this);if(!this.isGlobalEndpoint)return;this.isGlobalEndpoint=false;//client will throw if region is not supplied; request will be signed with specified region +if(!config.region){throw AWS.util.error(new Error(),{code:'ConfigError',message:'Missing region in config'});}var insertPoint=config.endpoint.indexOf('.amazonaws.com');config.endpoint=config.endpoint.substring(0,insertPoint)+'.'+config.region+config.endpoint.substring(insertPoint);}},validateService:function validateService(){this.optInRegionalEndpoint();}});}).call(this);}).call(this,require('_process'));},{"../core":18,"../region_config":53,"_process":86}],62:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** + * @api private + */var expiresHeader='presigned-expires';/** + * @api private + */function signedUrlBuilder(request){var expires=request.httpRequest.headers[expiresHeader];var signerClass=request.service.getSignerClass(request);delete request.httpRequest.headers['User-Agent'];delete request.httpRequest.headers['X-Amz-User-Agent'];if(signerClass===AWS.Signers.V4){if(expires>604800){// one week expiry is invalid +var message='Presigning does not support expiry time greater '+'than a week with SigV4 signing.';throw AWS.util.error(new Error(),{code:'InvalidExpiryTime',message:message,retryable:false});}request.httpRequest.headers[expiresHeader]=expires;}else if(signerClass===AWS.Signers.S3){var now=request.service?request.service.getSkewCorrectedDate():AWS.util.date.getDate();request.httpRequest.headers[expiresHeader]=parseInt(AWS.util.date.unixTimestamp(now)+expires,10).toString();}else{throw AWS.util.error(new Error(),{message:'Presigning only supports S3 or SigV4 signing.',code:'UnsupportedSigner',retryable:false});}}/** + * @api private + */function signedUrlSigner(request){var endpoint=request.httpRequest.endpoint;var parsedUrl=AWS.util.urlParse(request.httpRequest.path);var queryParams={};if(parsedUrl.search){queryParams=AWS.util.queryStringParse(parsedUrl.search.substr(1));}var auth=request.httpRequest.headers['Authorization'].split(' ');if(auth[0]==='AWS'){auth=auth[1].split(':');queryParams['AWSAccessKeyId']=auth[0];queryParams['Signature']=auth[1];AWS.util.each(request.httpRequest.headers,function(key,value){if(key===expiresHeader)key='Expires';if(key.indexOf('x-amz-meta-')===0){// Delete existing, potentially not normalized key +delete queryParams[key];key=key.toLowerCase();}queryParams[key]=value;});delete request.httpRequest.headers[expiresHeader];delete queryParams['Authorization'];delete queryParams['Host'];}else if(auth[0]==='AWS4-HMAC-SHA256'){// SigV4 signing +auth.shift();var rest=auth.join(' ');var signature=rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];queryParams['X-Amz-Signature']=signature;delete queryParams['Expires'];}// build URL +endpoint.pathname=parsedUrl.pathname;endpoint.search=AWS.util.queryParamsToString(queryParams);}/** + * @api private + */AWS.Signers.Presign=inherit({/** + * @api private + */sign:function sign(request,expireTime,callback){request.httpRequest.headers[expiresHeader]=expireTime||3600;request.on('build',signedUrlBuilder);request.on('sign',signedUrlSigner);request.removeListener('afterBuild',AWS.EventListeners.Core.SET_CONTENT_LENGTH);request.removeListener('afterBuild',AWS.EventListeners.Core.COMPUTE_SHA256);request.emit('beforePresign',[request]);if(callback){request.build(function(){if(this.response.error)callback(this.response.error);else{callback(null,AWS.util.urlFormat(request.httpRequest.endpoint));}});}else{request.build();if(request.response.error)throw request.response.error;return AWS.util.urlFormat(request.httpRequest.endpoint);}}});/** + * @api private + */module.exports=AWS.Signers.Presign;},{"../core":18}],63:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** + * @api private + */AWS.Signers.RequestSigner=inherit({constructor:function RequestSigner(request){this.request=request;},setServiceClientId:function setServiceClientId(id){this.serviceClientId=id;},getServiceClientId:function getServiceClientId(){return this.serviceClientId;}});AWS.Signers.RequestSigner.getVersion=function getVersion(version){switch(version){case'v2':return AWS.Signers.V2;case'v3':return AWS.Signers.V3;case's3v4':return AWS.Signers.V4;case'v4':return AWS.Signers.V4;case's3':return AWS.Signers.S3;case'v3https':return AWS.Signers.V3Https;}throw new Error('Unknown signing version '+version);};require('./v2');require('./v3');require('./v3https');require('./v4');require('./s3');require('./presign');},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** + * @api private + */AWS.Signers.S3=inherit(AWS.Signers.RequestSigner,{/** + * When building the stringToSign, these sub resource params should be + * part of the canonical resource string with their NON-decoded values + */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},// when building the stringToSign, these querystring params should be +// part of the canonical resource string with their NON-encoded values +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 addAuthorization(credentials,date){if(!this.request.headers['presigned-expires']){this.request.headers['X-Amz-Date']=AWS.util.date.rfc822(date);}if(credentials.sessionToken){// presigned URLs require this header to be lowercased +this.request.headers['x-amz-security-token']=credentials.sessionToken;}var signature=this.sign(credentials.secretAccessKey,this.stringToSign());var auth='AWS '+credentials.accessKeyId+':'+signature;this.request.headers['Authorization']=auth;},stringToSign:function stringToSign(){var r=this.request;var parts=[];parts.push(r.method);parts.push(r.headers['Content-MD5']||'');parts.push(r.headers['Content-Type']||'');// This is the "Date" header, but we use X-Amz-Date. +// The S3 signing mechanism requires us to pass an empty +// string for this Date header regardless. +parts.push(r.headers['presigned-expires']||'');var headers=this.canonicalizedAmzHeaders();if(headers)parts.push(headers);parts.push(this.canonicalizedResource());return parts.join('\n');},canonicalizedAmzHeaders:function canonicalizedAmzHeaders(){var amzHeaders=[];AWS.util.each(this.request.headers,function(name){if(name.match(/^x-amz-/i))amzHeaders.push(name);});amzHeaders.sort(function(a,b){return a.toLowerCase()=0?'&':'?';this.request.path+=sep+AWS.util.queryParamsToString(qs);},authorization:function authorization(credentials,datetime){var parts=[];var credString=this.credentialString(datetime);parts.push(this.algorithm+' Credential='+credentials.accessKeyId+'/'+credString);parts.push('SignedHeaders='+this.signedHeaders());parts.push('Signature='+this.signature(credentials,datetime));return parts.join(', ');},signature:function signature(credentials,datetime){var signingKey=v4Credentials.getSigningKey(credentials,datetime.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return AWS.util.crypto.hmac(signingKey,this.stringToSign(datetime),'hex');},stringToSign:function stringToSign(datetime){var parts=[];parts.push('AWS4-HMAC-SHA256');parts.push(datetime);parts.push(this.credentialString(datetime));parts.push(this.hexEncodedHash(this.canonicalString()));return parts.join('\n');},canonicalString:function canonicalString(){var parts=[],pathname=this.request.pathname();if(this.serviceName!=='s3'&&this.signatureVersion!=='s3v4')pathname=AWS.util.uriEscapePath(pathname);parts.push(this.request.method);parts.push(pathname);parts.push(this.request.search());parts.push(this.canonicalHeaders()+'\n');parts.push(this.signedHeaders());parts.push(this.hexEncodedBodyHash());return parts.join('\n');},canonicalHeaders:function canonicalHeaders(){var headers=[];AWS.util.each.call(this,this.request.headers,function(key,item){headers.push([key,item]);});headers.sort(function(a,b){return a[0].toLowerCase()maxCacheEntries){// remove the oldest entry (not the least recently used) +delete cachedSecret[cacheQueue.shift()];}}return signingKey;},/** + * @api private + * + * Empties the derived signing key cache. Made available for testing purposes + * only. + */emptyCache:function emptyCache(){cachedSecret={};cacheQueue=[];}};},{"../core":18}],70:[function(require,module,exports){function AcceptorStateMachine(states,state){this.currentState=state||null;this.states=states||{};}AcceptorStateMachine.prototype.runTo=function runTo(finalState,done,bindObject,inputError){if(typeof finalState==='function'){inputError=bindObject;bindObject=done;done=finalState;finalState=null;}var self=this;var state=self.states[self.currentState];state.fn.call(bindObject||self,inputError,function(err){if(err){if(state.fail)self.currentState=state.fail;else return done?done.call(bindObject,err):null;}else{if(state.accept)self.currentState=state.accept;else return done?done.call(bindObject):null;}if(self.currentState===finalState){return done?done.call(bindObject,err):null;}self.runTo(finalState,done,bindObject,err);});};AcceptorStateMachine.prototype.addState=function addState(name,acceptState,failState,fn){if(typeof acceptState==='function'){fn=acceptState;acceptState=null;failState=null;}else if(typeof failState==='function'){fn=failState;failState=null;}if(!this.currentState)this.currentState=name;this.states[name]={accept:acceptState,fail:failState,fn:fn};return this;};/** + * @api private + */module.exports=AcceptorStateMachine;},{}],71:[function(require,module,exports){(function(process,setImmediate){(function(){/* eslint guard-for-in:0 */var AWS;/** + * A set of utility methods for use with the AWS SDK. + * + * @!attribute abort + * Return this value from an iterator function {each} or {arrayEach} + * to break out of the iteration. + * @example Breaking out of an iterator function + * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) { + * if (key == 'b') return AWS.util.abort; + * }); + * @see each + * @see arrayEach + * @api private + */var util={environment:'nodejs',engine:function engine(){if(util.isBrowser()&&typeof navigator!=='undefined'){return navigator.userAgent;}else{var engine=process.platform+'/'+process.version;if(process.env.AWS_EXECUTION_ENV){engine+=' exec-env/'+process.env.AWS_EXECUTION_ENV;}return engine;}},userAgent:function userAgent(){var name=util.environment;var agent='aws-sdk-'+name+'/'+require('./core').VERSION;if(name==='nodejs')agent+=' '+util.engine();return agent;},uriEscape:function uriEscape(string){var output=encodeURIComponent(string);output=output.replace(/[^A-Za-z0-9_.~\-%]+/g,escape);// AWS percent-encodes some extra non-standard characters in a URI +output=output.replace(/[*]/g,function(ch){return'%'+ch.charCodeAt(0).toString(16).toUpperCase();});return output;},uriEscapePath:function uriEscapePath(string){var parts=[];util.arrayEach(string.split('/'),function(part){parts.push(util.uriEscape(part));});return parts.join('/');},urlParse:function urlParse(url){return util.url.parse(url);},urlFormat:function urlFormat(url){return util.url.format(url);},queryStringParse:function queryStringParse(qs){return util.querystring.parse(qs);},queryParamsToString:function queryParamsToString(params){var items=[];var escape=util.uriEscape;var sortedKeys=Object.keys(params).sort();util.arrayEach(sortedKeys,function(name){var value=params[name];var ename=escape(name);var result=ename+'=';if(Array.isArray(value)){var vals=[];util.arrayEach(value,function(item){vals.push(escape(item));});result=ename+'='+vals.sort().join('&'+ename+'=');}else if(value!==undefined&&value!==null){result=ename+'='+escape(value);}items.push(result);});return items.join('&');},readFileSync:function readFileSync(path){if(util.isBrowser())return null;return require('fs').readFileSync(path,'utf-8');},base64:{encode:function encode64(string){if(typeof string==='number'){throw util.error(new Error('Cannot base64 encode number '+string));}if(string===null||typeof string==='undefined'){return string;}var buf=util.buffer.toBuffer(string);return buf.toString('base64');},decode:function decode64(string){if(typeof string==='number'){throw util.error(new Error('Cannot base64 decode number '+string));}if(string===null||typeof string==='undefined'){return string;}return util.buffer.toBuffer(string,'base64');}},buffer:{/** + * Buffer constructor for Node buffer and buffer pollyfill + */toBuffer:function toBuffer(data,encoding){return typeof util.Buffer.from==='function'&&util.Buffer.from!==Uint8Array.from?util.Buffer.from(data,encoding):new util.Buffer(data,encoding);},alloc:function alloc(size,fill,encoding){if(typeof size!=='number'){throw new Error('size passed to alloc must be a number.');}if(typeof util.Buffer.alloc==='function'){return util.Buffer.alloc(size,fill,encoding);}else{var buf=new util.Buffer(size);if(fill!==undefined&&typeof buf.fill==='function'){buf.fill(fill,undefined,undefined,encoding);}return buf;}},toStream:function toStream(buffer){if(!util.Buffer.isBuffer(buffer))buffer=util.buffer.toBuffer(buffer);var readable=new util.stream.Readable();var pos=0;readable._read=function(size){if(pos>=buffer.length)return readable.push(null);var end=pos+size;if(end>buffer.length)end=buffer.length;readable.push(buffer.slice(pos,end));pos=end;};return readable;},/** + * Concatenates a list of Buffer objects. + */concat:function concat(buffers){var length=0,offset=0,buffer=null,i;for(i=0;i>>8^tbl[(crc^code)&0xFF];}return(crc^-1)>>>0;},hmac:function hmac(key,string,digest,fn){if(!digest)digest='binary';if(digest==='buffer'){digest=undefined;}if(!fn)fn='sha256';if(typeof string==='string')string=util.buffer.toBuffer(string);return util.crypto.lib.createHmac(fn,key).update(string).digest(digest);},md5:function md5(data,digest,callback){return util.crypto.hash('md5',data,digest,callback);},sha256:function sha256(data,digest,callback){return util.crypto.hash('sha256',data,digest,callback);},hash:function hash(algorithm,data,digest,callback){var hash=util.crypto.createHash(algorithm);if(!digest){digest='binary';}if(digest==='buffer'){digest=undefined;}if(typeof data==='string')data=util.buffer.toBuffer(data);var sliceFn=util.arraySliceFn(data);var isBuffer=util.Buffer.isBuffer(data);//Identifying objects with an ArrayBuffer as buffers +if(util.isBrowser()&&typeof ArrayBuffer!=='undefined'&&data&&data.buffer instanceof ArrayBuffer)isBuffer=true;if(callback&&_typeof(data)==='object'&&typeof data.on==='function'&&!isBuffer){data.on('data',function(chunk){hash.update(chunk);});data.on('error',function(err){callback(err);});data.on('end',function(){callback(null,hash.digest(digest));});}else if(callback&&sliceFn&&!isBuffer&&typeof FileReader!=='undefined'){// this might be a File/Blob +var index=0,size=1024*512;var reader=new FileReader();reader.onerror=function(){callback(new Error('Failed to read data.'));};reader.onload=function(){var buf=new util.Buffer(new Uint8Array(reader.result));hash.update(buf);index+=buf.length;reader._continueReading();};reader._continueReading=function(){if(index>=data.size){callback(null,hash.digest(digest));return;}var back=index+size;if(back>data.size)back=data.size;reader.readAsArrayBuffer(sliceFn.call(data,index,back));};reader._continueReading();}else{if(util.isBrowser()&&_typeof(data)==='object'&&!isBuffer){data=new util.Buffer(new Uint8Array(data));}var out=hash.update(data).digest(digest);if(callback)callback(null,out);return out;}},toHex:function toHex(data){var out=[];for(var i=0;i=300000,false);return AWS.config.isClockSkewed;}},applyClockOffset:function applyClockOffset(serverTime){if(serverTime)AWS.config.systemClockOffset=serverTime-new Date().getTime();},/** + * @api private + */extractRequestId:function extractRequestId(resp){var requestId=resp.httpResponse.headers['x-amz-request-id']||resp.httpResponse.headers['x-amzn-requestid'];if(!requestId&&resp.data&&resp.data.ResponseMetadata){requestId=resp.data.ResponseMetadata.RequestId;}if(requestId){resp.requestId=requestId;}if(resp.error){resp.error.requestId=requestId;}},/** + * @api private + */addPromises:function addPromises(constructors,PromiseDependency){var deletePromises=false;if(PromiseDependency===undefined&&AWS&&AWS.config){PromiseDependency=AWS.config.getPromisesDependency();}if(PromiseDependency===undefined&&typeof Promise!=='undefined'){PromiseDependency=Promise;}if(typeof PromiseDependency!=='function')deletePromises=true;if(!Array.isArray(constructors))constructors=[constructors];for(var ind=0;ind=500||statusCode===429});if(retryAfter&&err.retryable)err.retryAfter=retryAfter;errCallback(err);}});},errCallback);};AWS.util.defer(sendRequest);},/** + * @api private + */uuid:{v4:function uuidV4(){return require('uuid').v4();}},/** + * @api private + */convertPayloadToString:function convertPayloadToString(resp){var req=resp.request;var operation=req.operation;var rules=req.service.api.operations[operation].output||{};if(rules.payload&&resp.data[rules.payload]){resp.data[rules.payload]=resp.data[rules.payload].toString();}},/** + * @api private + */defer:function defer(callback){if(_typeof(process)==='object'&&typeof process.nextTick==='function'){process.nextTick(callback);}else if(typeof setImmediate==='function'){setImmediate(callback);}else{setTimeout(callback,0);}},/** + * @api private + */getRequestPayloadShape:function getRequestPayloadShape(req){var operations=req.service.api.operations;if(!operations)return undefined;var operation=(operations||{})[req.operation];if(!operation||!operation.input||!operation.input.payload)return undefined;return operation.input.members[operation.input.payload];},getProfilesFromSharedConfig:function getProfilesFromSharedConfig(iniLoader,filename){var profiles={};var profilesFromConfig={};if(process.env[util.configOptInEnv]){var profilesFromConfig=iniLoader.loadFrom({isConfig:true,filename:process.env[util.sharedConfigFileEnv]});}var profilesFromCreds=iniLoader.loadFrom({filename:filename||process.env[util.configOptInEnv]&&process.env[util.sharedCredentialsFileEnv]});for(var i=0,profileNames=Object.keys(profilesFromConfig);i0||noEmpty?xml.toString():'';};function serialize(xml,value,shape){switch(shape.type){case'structure':return serializeStructure(xml,value,shape);case'map':return serializeMap(xml,value,shape);case'list':return serializeList(xml,value,shape);default:return serializeScalar(xml,value,shape);}}function serializeStructure(xml,params,shape){util.arrayEach(shape.memberNames,function(memberName){var memberShape=shape.members[memberName];if(memberShape.location!=='body')return;var value=params[memberName];var name=memberShape.name;if(value!==undefined&&value!==null){if(memberShape.isXmlAttribute){xml.addAttribute(name,value);}else if(memberShape.flattened){serialize(xml,value,memberShape);}else{var element=new XmlNode(name);xml.addChildNode(element);applyNamespaces(element,memberShape);serialize(element,value,memberShape);}}});}function serializeMap(xml,map,shape){var xmlKey=shape.key.name||'key';var xmlValue=shape.value.name||'value';util.each(map,function(key,value){var entry=new XmlNode(shape.flattened?shape.name:'entry');xml.addChildNode(entry);var entryKey=new XmlNode(xmlKey);var entryValue=new XmlNode(xmlValue);entry.addChildNode(entryKey);entry.addChildNode(entryValue);serialize(entryKey,key,shape.key);serialize(entryValue,value,shape.value);});}function serializeList(xml,list,shape){if(shape.flattened){util.arrayEach(list,function(value){var name=shape.member.name||shape.name;var element=new XmlNode(name);xml.addChildNode(element);serialize(element,value,shape.member);});}else{util.arrayEach(list,function(value){var name=shape.member.name||'member';var element=new XmlNode(name);xml.addChildNode(element);serialize(element,value,shape.member);});}}function serializeScalar(xml,value,shape){xml.addChildNode(new XmlText(shape.toWireFormat(value)));}function applyNamespaces(xml,shape,isRoot){var uri,prefix='xmlns';if(shape.xmlNamespaceUri){uri=shape.xmlNamespaceUri;if(shape.xmlNamespacePrefix)prefix+=':'+shape.xmlNamespacePrefix;}else if(isRoot&&shape.api.xmlNamespaceUri){uri=shape.api.xmlNamespaceUri;}if(uri)xml.addAttribute(prefix,uri);}/** + * @api private + */module.exports=XmlBuilder;},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(require,module,exports){/** + * Escapes characters that can not be in an XML attribute. + */function escapeAttribute(value){return value.replace(/&/g,'&').replace(/'/g,''').replace(//g,'>').replace(/"/g,'"');}/** + * @api private + */module.exports={escapeAttribute:escapeAttribute};},{}],75:[function(require,module,exports){/** + * Escapes characters that can not be in an XML element. + */function escapeElement(value){return value.replace(/&/g,'&').replace(//g,'>');}/** + * @api private + */module.exports={escapeElement:escapeElement};},{}],76:[function(require,module,exports){var escapeAttribute=require('./escape-attribute').escapeAttribute;/** + * Represents an XML node. + * @api private + */function XmlNode(name,children){if(children===void 0){children=[];}this.name=name;this.children=children;this.attributes={};}XmlNode.prototype.addAttribute=function(name,value){this.attributes[name]=value;return this;};XmlNode.prototype.addChildNode=function(child){this.children.push(child);return this;};XmlNode.prototype.removeAttribute=function(name){delete this.attributes[name];return this;};XmlNode.prototype.toString=function(){var hasChildren=Boolean(this.children.length);var xmlText='<'+this.name;// add attributes +var attributes=this.attributes;for(var i=0,attributeNames=Object.keys(attributes);i':'>'+this.children.map(function(c){return c.toString();}).join('')+'';};/** + * @api private + */module.exports={XmlNode:XmlNode};},{"./escape-attribute":74}],77:[function(require,module,exports){var escapeElement=require('./escape-element').escapeElement;/** + * Represents an XML text value. + * @api private + */function XmlText(value){this.value=value;}XmlText.prototype.toString=function(){return escapeElement(''+this.value);};/** + * @api private + */module.exports={XmlText:XmlText};},{"./escape-element":75}],78:[function(require,module,exports){'use strict';exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=='undefined'?Uint8Array:Array;var code='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';for(var i=0,len=code.length;i0){throw new Error('Invalid string. Length must be a multiple of 4');}// Trim off extra bytes after placeholder bytes are found +// See: https://github.com/beatgammit/base64-js/issues/42 +var validLen=b64.indexOf('=');if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen];}// base64 is 4/3 + up to two characters of the original data +function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;// if there are placeholders, only get up to the last complete 4 chars +var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&0xFF;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}return arr;}function tripletToBase64(num){return lookup[num>>18&0x3F]+lookup[num>>12&0x3F]+lookup[num>>6&0x3F]+lookup[num&0x3F];}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength));}// pad the end with zeros, but make sure to not forget the extra bytes +if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&0x3F]+'==');}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&0x3F]+lookup[tmp<<2&0x3F]+'=');}return parts.join('');}},{}],79:[function(require,module,exports){},{}],80:[function(require,module,exports){(function(global){(function(){/*! https://mths.be/punycode v1.3.2 by @mathias */;(function(root){/** Detect free variables */var freeExports=_typeof(exports)=='object'&&exports&&!exports.nodeType&&exports;var freeModule=_typeof(module)=='object'&&module&&!module.nodeType&&module;var freeGlobal=_typeof(global)=='object'&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal){root=freeGlobal;}/** + * The `punycode` object. + * @name punycode + * @type Object + */var punycode,/** Highest positive signed 32-bit float value */maxInt=2147483647,// aka. 0x7FFFFFFF or 2^31-1 +/** Bootstring parameters */base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,// 0x80 +delimiter='-',// '\x2D' +/** Regular expressions */regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,// unprintable ASCII chars + non-ASCII chars +regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,// RFC 3490 separators +/** Error messages */errors={'overflow':'Overflow: input needs wider integers to process','not-basic':'Illegal input >= 0x80 (not a basic code point)','invalid-input':'Invalid input'},/** Convenience shortcuts */baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*/ /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */function error(type){throw RangeError(errors[type]);}/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length]);}return result;}/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */function mapDomain(string,fn){var parts=string.split('@');var result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave +// the local part (i.e. everything up to `@`) intact. +result=parts[0]+'@';string=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17. +string=string.replace(regexSeparators,'\x2E');var labels=string.split('.');var encoded=map(labels,fn).join('.');return result+encoded;}/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=0xD800&&value<=0xDBFF&&counter0xFFFF){value-=0x10000;output+=stringFromCharCode(value>>>10&0x3FF|0xD800);value=0xDC00|value&0x3FF;}output+=stringFromCharCode(value);return output;}).join('');}/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22;}if(codePoint-65<26){return codePoint-65;}if(codePoint-97<26){return codePoint-97;}return base;}/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */function digitToBasic(digit,flag){// 0..25 map to ASCII a..z or A..Z +// 26..35 map to ASCII 0..9 +return digit+22+75*(digit<26)-((flag!=0)<<5);}/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for/* no initialization */(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */function decode(input){// Don't use UCS-2 +var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code +// points before the last delimiter, or `0` if there is none, then copy +// the first basic code points to the output. +basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(j=0;j=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code +// points were copied; start at the beginning otherwise. +for/* no final expression */(index=basic>0?basic+1:0;index=inputLength){error('invalid-input');}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`, +// incrementing `n` each time, so we'll fix that now: +if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output +output.splice(i++,0,n);}return ucs2encode(output);}/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicode +input=ucs2decode(input);// Cache the length +inputLength=input.length;// Initialize the state +n=initialN;delta=0;bias=initialBias;// Handle the basic code points +for(j=0;j=n&¤tValue state to , +// but guard against overflow +handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error('overflow');}if(currentValue==n){// Represent delta as a generalized variable-length integer +for/* no condition */(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q + * @memberOf punycode + * @type Object + */'ucs2':{'decode':ucs2decode,'encode':ucs2encode},'decode':decode,'encode':encode,'toASCII':toASCII,'toUnicode':toUnicode};/** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns +// like the following: +if( true&&_typeof(__webpack_require__.amdO)=='object'&&__webpack_require__.amdO){!(__WEBPACK_AMD_DEFINE_RESULT__ = (function(){return punycode;}).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));}else if(freeExports&&freeModule){if(module.exports==freeExports){// in Node.js or RingoJS v0.8.0+ +freeModule.exports=punycode;}else{// in Narwhal or RingoJS v0.7.0- +for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);}}}else{// in Rhino or a web browser +root.punycode=punycode;}})(this);}).call(this);}).call(this,typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{}],81:[function(require,module,exports){(function(global,Buffer){(function(){/*! + * The buffer module from node.js, for the browser. * - * SPDX-License-Identifier: Apache-2.0 - */ -(function() { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /**--------------------------------------------------------------- - * class Stream - * - * Represents an object from which messages can be read and to which - * messages can be sent. - */ - var Stream = function() {}; - - /** - * Send a message to the stream. This method must be implemented by subclasses. - */ - Stream.prototype.send = function(message) { - throw new connect.NotImplementedError(); - }; - - /** - * Provide a method to be called when messages are received from this stream. - * This method must be implemented by subclasses. - */ - Stream.prototype.onMessage = function(f) { - throw new connect.NotImplementedError(); - }; - - /**--------------------------------------------------------------- - * class NullStream extends Stream - * - * A null stream which provides no message sending or receiving facilities. - */ - var NullStream = function() { - Stream.call(this); - }; - NullStream.prototype = Object.create(Stream.prototype); - NullStream.prototype.constructor = NullStream; - - NullStream.prototype.onMessage = function(f) {}; - NullStream.prototype.send = function(message) {}; - - /**--------------------------------------------------------------- - * class WindowStream extends Stream - * - * A stream for communicating with a window object. The domain provided - * must match the allowed message domains of the downstream receiver - * or messages will be rejected, see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage - * for more info. - */ - var WindowStream = function(win, domain) { - Stream.call(this); - this.window = win; - this.domain = domain || '*'; - }; - WindowStream.prototype = Object.create(Stream.prototype); - WindowStream.prototype.constructor = WindowStream; - - WindowStream.prototype.send = function(message) { - this.window.postMessage(message, this.domain); - }; - - WindowStream.prototype.onMessage = function(f) { - this.window.addEventListener("message", f); - }; - - /**--------------------------------------------------------------- - * class WindowIOStream extends Stream - * - * A stream used by IFrame/popup windows to communicate with their parents - * and vise versa. - * - * This object encapsulates the fact that incoming and outgoing messages - * arrive on different windows and allows this to be managed as a single - * Stream object. - */ - var WindowIOStream = function(inputwin, outputwin, domain) { - Stream.call(this); - this.input = inputwin; - this.output = outputwin; - this.domain = domain || '*'; - }; - WindowIOStream.prototype = Object.create(Stream.prototype); - WindowIOStream.prototype.constructor = WindowIOStream; - - WindowIOStream.prototype.send = function(message) { - this.output.postMessage(message, this.domain); - }; - - WindowIOStream.prototype.onMessage = function(f) { - this.input.addEventListener("message", (message) => { - if (message.source === this.output) { - f(message); - } - }); - }; - - /**--------------------------------------------------------------- - * class PortStream extends Stream - * - * A stream wrapping an HTML5 Worker port. This could be the port - * used to connect to a Worker or one of the multitude of ports - * made available to a SharedWorker for communication back to - * its connected clients. - */ - var PortStream = function(port) { - Stream.call(this); - this.port = port; - this.id = connect.randomId(); - }; - PortStream.prototype = Object.create(Stream.prototype); - PortStream.prototype.constructor = PortStream; - - PortStream.prototype.send = function(message) { - this.port.postMessage(message); - }; - - PortStream.prototype.onMessage = function(f) { - this.port.addEventListener("message", f); - }; - - PortStream.prototype.getId = function() { - return this.id; - }; - - /**--------------------------------------------------------------- - * class StreamMultiplexer extends Stream - * - * A wrapper for multiplexed downstream communication with - * multiple streams at once. Mainly useful for the SharedWorker to - * broadcast events to many PortStream objects at once. - */ - var StreamMultiplexer = function(streams) { - Stream.call(this); - this.streamMap = streams ? - connect.index(streams, function(s) { return s.getId(); }) : {}; - this.messageListeners = []; - }; - StreamMultiplexer.prototype = Object.create(Stream.prototype); - StreamMultiplexer.prototype.constructor = StreamMultiplexer; - - /** - * Send a message to all ports in the multiplexer. - */ - StreamMultiplexer.prototype.send = function(message) { - this.getStreams().forEach(function(stream) { - try { - stream.send(message); - - } catch (e) { - // Couldn't send message to one of the downstreams for some reason... - // No reliable logging possible without further failures, - // no recovery, just eat it. - } - }); - }; - - /** - * Register a method which will be called when a message is received from - * any of the downstreams. - */ - StreamMultiplexer.prototype.onMessage = function(f) { - this.messageListeners.push(f); - - // Update existing streams with the new listener. - this.getStreams().forEach(function(stream) { - stream.onMessage(f); - }); - }; - - /** - * Add a stream to the multiplexer. - */ - StreamMultiplexer.prototype.addStream = function(stream) { - var self = this; - this.streamMap[stream.getId()] = stream; - - // Update stream with existing listeners. - this.messageListeners.forEach(function(messageListener) { - stream.onMessage(messageListener); - }); - }; - - /** - * Remove the given downstream. This is typically used in response - * to the SharedWorker's onclose event, indicating that a consumer - * tab has been closed. - */ - StreamMultiplexer.prototype.removeStream = function(stream) { - delete this.streamMap[stream.getId()]; - }; - - /** - * Get a list of streams in the multiplexer. - */ - StreamMultiplexer.prototype.getStreams = function(stream) { - return connect.values(this.streamMap); - }; - - /** - * Get the stream matching the given port. - */ - StreamMultiplexer.prototype.getStreamForPort = function(port) { - return connect.find(this.getStreams(), function(s) { - return s.port === port; - }); - }; - - /**--------------------------------------------------------------- - * class Conduit - * - * An object which bridges an upstream and a downstream, allowing messages - * to be passed to and from each and providing an event bus for event - * subscriptions to be made upstream and downstream. - */ - var Conduit = function(name, upstream, downstream) { - this.name = name; - this.upstream = upstream || new NullStream(); - this.downstream = downstream || new NullStream(); - this.downstreamBus = new connect.EventBus(); - this.upstreamBus = new connect.EventBus(); - - this.upstream.onMessage(connect.hitch(this, this._dispatchEvent, this.upstreamBus)); - this.downstream.onMessage(connect.hitch(this, this._dispatchEvent, this.downstreamBus)); - }; - - Conduit.prototype.onUpstream = function(eventName, f) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.upstreamBus.subscribe(eventName, f); - }; - - Conduit.prototype.onAllUpstream = function(f) { - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.upstreamBus.subscribeAll(f); - }; - - Conduit.prototype.onDownstream = function(eventName, f) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.downstreamBus.subscribe(eventName, f); - }; - - Conduit.prototype.onAllDownstream = function(f) { - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.downstreamBus.subscribeAll(f); - }; - - Conduit.prototype.sendUpstream = function(eventName, data) { - connect.assertNotNull(eventName, 'eventName'); - this.upstream.send({event: eventName, data: data}); - }; - - Conduit.prototype.sendDownstream = function(eventName, data) { - connect.assertNotNull(eventName, 'eventName'); - this.downstream.send({event: eventName, data: data}); - }; - - Conduit.prototype._dispatchEvent = function(bus, messageEvent) { - var message = messageEvent.data; - if (message.event) { - bus.trigger(message.event, message.data); - } - }; - - /** - * Returns a closure which passes events upstream. - * - * Usage: - * conduit.onDownstream("MyEvent", conduit.passUpstream()); - */ - Conduit.prototype.passUpstream = function() { - var self = this; - return function(data, eventName) { - self.upstream.send({event: eventName, data: data}); - }; - }; - - /** - * Returns a closure which passes events downstream. - * - * Usage: - * conduit.onUpstream("MyEvent", conduit.passDownstream()); - */ - Conduit.prototype.passDownstream = function() { - var self = this; - return function(data, eventName) { - self.downstream.send({event: eventName, data: data}); - }; - }; - - /** - * Shutdown the conduit's event busses and remove all subscriptions. - */ - Conduit.prototype.shutdown = function() { - this.upstreamBus.unsubscribeAll(); - this.downstreamBus.unsubscribeAll(); - }; - - /**--------------------------------------------------------------- - * class IFrameConduit extends Conduit - * - * Creates a conduit for the given IFrame element. - */ - var IFrameConduit = function(name, window, iframe, domain) { - Conduit.call(this, name, new WindowIOStream(window, iframe.contentWindow, domain || '*'), null); - }; - IFrameConduit.prototype = Object.create(Conduit.prototype); - IFrameConduit.prototype.constructor = IFrameConduit; - - connect.Stream = Stream; - connect.NullStream = NullStream; - connect.WindowStream = WindowStream; - connect.WindowIOStream = WindowIOStream; - connect.PortStream = PortStream; - connect.StreamMultiplexer = StreamMultiplexer; - connect.Conduit = Conduit; - connect.IFrameConduit = IFrameConduit; -})(); + * @author Feross Aboukhadijeh + * @license MIT + */ /* eslint-disable no-proto */'use strict';var base64=require('base64-js');var ieee754=require('ieee754');var isArray=require('isarray');exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();/* + * Export kMaxLength after typed array support is determined. + */exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function foo(){return 42;}};return arr.foo()===42&&// typed array instances can be augmented +typeof arr.subarray==='function'&&// chrome 9-10 lack `subarray` +arr.subarray(1,1).byteLength===0;// ie10 has broken `subarray` +}catch(e){return false;}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?0x7fffffff:0x3fffffff;}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError('Attempt to allocate Buffer larger than maximum '+'size: 0x'+kMaxLength().toString(16)+' bytes');}return length|0;}function SlowBuffer(length){if(+length!=length){// eslint-disable-line eqeqeq +length=0;}return Buffer.alloc(+length);}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer);};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('Arguments must be Buffers');}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case'base64':return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;// assume utf8 +encoding=(''+encoding).toLowerCase();loweredCase=true;}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;// No need to verify that "this.length <= MAX_UINT32" since it's a read-only +// property of a typed array. +// This behaves neither like String nor Uint8Array in that we set start/end +// to their upper/lower bounds if the value passed is out of range. +// undefined is handled specially as per ECMA-262 6th Edition, +// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. +if(start===undefined||start<0){start=0;}// Return early if start > this.length. Done here to prevent potential uint32 +// coercion fail below. +if(start>this.length){return'';}if(end===undefined||end>this.length){end=this.length;}if(end<=0){return'';}// Force coersion to uint32. This will also coerce falsey/NaN values to 0. +end>>>=0;start>>>=0;if(end<=start){return'';}if(!encoding)encoding='utf8';while(true){switch(encoding){case'hex':return hexSlice(this,start,end);case'utf8':case'utf-8':return utf8Slice(this,start,end);case'ascii':return asciiSlice(this,start,end);case'latin1':case'binary':return latin1Slice(this,start,end);case'base64':return base64Slice(this,start,end);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(encoding+'').toLowerCase();loweredCase=true;}}}// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i;}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError('Buffer size must be a multiple of 16-bits');}for(var i=0;i0){str=this.toString('hex',0,max).match(/.{2}/g).join(' ');if(this.length>max)str+=' ... ';}return'';};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError('Argument must be a Buffer');}if(start===undefined){start=0;}if(end===undefined){end=target?target.length:0;}if(thisStart===undefined){thisStart=0;}if(thisEnd===undefined){thisEnd=this.length;}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError('out of range index');}if(thisStart>=thisEnd&&start>=end){return 0;}if(thisStart>=thisEnd){return-1;}if(start>=end){return 1;}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){// Empty buffer means no match +if(buffer.length===0)return-1;// Normalize byteOffset +if(typeof byteOffset==='string'){encoding=byteOffset;byteOffset=0;}else if(byteOffset>0x7fffffff){byteOffset=0x7fffffff;}else if(byteOffset<-0x80000000){byteOffset=-0x80000000;}byteOffset=+byteOffset;// Coerce to Number. +if(isNaN(byteOffset)){// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer +byteOffset=dir?0:buffer.length-1;}// Normalize byteOffset: negative offsets start from the end of the buffer +if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1;}else if(byteOffset<0){if(dir)byteOffset=0;else return-1;}// Normalize val +if(typeof val==='string'){val=Buffer.from(val,encoding);}// Finally, search either indexOf (if dir is true) or lastIndexOf +if(Buffer.isBuffer(val)){// Special case: looking for empty string/buffer always fails +if(val.length===0){return-1;}return arrayIndexOf(buffer,val,byteOffset,encoding,dir);}else if(typeof val==='number'){val=val&0xFF;// Search for a byte value [0-255] +if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==='function'){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset);}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset);}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir);}throw new TypeError('val must be string, number or Buffer');}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==='ucs2'||encoding==='ucs-2'||encoding==='utf16le'||encoding==='utf-16le'){if(arr.length<2||val.length<2){return-1;}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2;}}function read(buf,i){if(indexSize===1){return buf[i];}else{return buf.readUInt16BE(i*indexSize);}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining;}}// must be an even number of digits +var strLen=string.length;if(strLen%2!==0)throw new TypeError('Invalid hex string');if(length>strLen/2){length=strLen/2;}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError('Attempt to write outside buffer bounds');}if(!encoding)encoding='utf8';var loweredCase=false;for(;;){switch(encoding){case'hex':return hexWrite(this,string,offset,length);case'utf8':case'utf-8':return utf8Write(this,string,offset,length);case'ascii':return asciiWrite(this,string,offset,length);case'latin1':case'binary':return latin1Write(this,string,offset,length);case'base64':// Warning: maxLength not taken into account in base64Write +return base64Write(this,string,offset,length);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(''+encoding).toLowerCase();loweredCase=true;}}};Buffer.prototype.toJSON=function toJSON(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)};};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf);}else{return base64.fromByteArray(buf.slice(start,end));}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i0xEF?4:firstByte>0xDF?3:firstByte>0xBF?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<0x80){codePoint=firstByte;}break;case 2:secondByte=buf[i+1];if((secondByte&0xC0)===0x80){tempCodePoint=(firstByte&0x1F)<<0x6|secondByte&0x3F;if(tempCodePoint>0x7F){codePoint=tempCodePoint;}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0xC|(secondByte&0x3F)<<0x6|thirdByte&0x3F;if(tempCodePoint>0x7FF&&(tempCodePoint<0xD800||tempCodePoint>0xDFFF)){codePoint=tempCodePoint;}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80&&(fourthByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0x12|(secondByte&0x3F)<<0xC|(thirdByte&0x3F)<<0x6|fourthByte&0x3F;if(tempCodePoint>0xFFFF&&tempCodePoint<0x110000){codePoint=tempCodePoint;}}}}if(codePoint===null){// we did not generate a valid codePoint so insert a +// replacement char (U+FFFD) and advance only 1 byte +codePoint=0xFFFD;bytesPerSequence=1;}else if(codePoint>0xFFFF){// encode to utf16 (surrogate pair dance) +codePoint-=0x10000;res.push(codePoint>>>10&0x3FF|0xD800);codePoint=0xDC00|codePoint&0x3FF;}res.push(codePoint);i+=bytesPerSequence;}return decodeCodePointsArray(res);}// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH=0x1000;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints);// avoid extra slice() +}// Decode in chunks to avoid "call stack size exceeded". +var res='';var i=0;while(ilen)end=len;var out='';for(var i=start;ilen){start=len;}if(end<0){end+=len;if(end<0)end=0;}else if(end>len){end=len;}if(endlength)throw new RangeError('Trying to access beyond buffer length');}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=0x100)){val+=this[offset+--byteLength]*mul;}return val;};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset];};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8;};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1];};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*0x1000000;};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*0x1000000+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3]);};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=0x100)){val+=this[offset+--i]*mul;}mul*=0x80;if(val>=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&0x80))return this[offset];return(0xff-this[offset]+1)*-1;};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24;};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3];};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4);};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4);};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8);};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8);};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError('Index out of range');}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0);}var mul=1;var i=0;this[offset]=value&0xFF;while(++i=0&&(mul*=0x100)){this[offset+i]=value/mul&0xFF;}return offset+byteLength;};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0xff,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&0xff;return offset+1;};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=0xffff+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8;}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=0xffffffff+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&0xff;}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&0xff;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=0;var mul=1;var sub=0;this[offset]=value&0xFF;while(++i>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1;}this[offset+i]=(value/mul>>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0x7f,-0x80);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=0xff+value+1;this[offset]=value&0xff;return offset+1;};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(value<0)value=0xffffffff+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError('Index out of range');if(offset<0)throw new RangeError('Index out of range');}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e+38,-3.4028234663852886e+38);}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4;}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert);};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert);};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157E+308,-1.7976931348623157E+308);}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8;}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert);};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert);};// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError('sourceStart out of bounds');if(end<0)throw new RangeError('sourceEnd out of bounds');// Are we oob? +if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start];}}else if(len<1000||!Buffer.TYPED_ARRAY_SUPPORT){// ascending copy from start +for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==='number'){for(i=start;i0xD7FF&&codePoint<0xE000){// last char was a lead +if(!leadSurrogate){// no lead yet +if(codePoint>0xDBFF){// unexpected trail +if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}else if(i+1===length){// unpaired lead +if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}// valid lead +leadSurrogate=codePoint;continue;}// 2 leads in a row +if(codePoint<0xDC00){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);leadSurrogate=codePoint;continue;}// valid surrogate pair +codePoint=(leadSurrogate-0xD800<<10|codePoint-0xDC00)+0x10000;}else if(leadSurrogate){// valid bmp char, but last char was a lead +if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);}leadSurrogate=null;// encode utf8 +if(codePoint<0x80){if((units-=1)<0)break;bytes.push(codePoint);}else if(codePoint<0x800){if((units-=2)<0)break;bytes.push(codePoint>>0x6|0xC0,codePoint&0x3F|0x80);}else if(codePoint<0x10000){if((units-=3)<0)break;bytes.push(codePoint>>0xC|0xE0,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else if(codePoint<0x110000){if((units-=4)<0)break;bytes.push(codePoint>>0x12|0xF0,codePoint>>0xC&0x3F|0x80,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else{throw new Error('Invalid code point');}}return bytes;}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi);}return byteArray;}function base64ToBytes(str){return base64.toByteArray(base64clean(str));}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i];}return i;}function isnan(val){return val!==val;// eslint-disable-line no-self-compare +}}).call(this);}).call(this,typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer);},{"base64-js":78,"buffer":81,"ieee754":83,"isarray":84}],82:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined;}module.exports=EventEmitter;// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners=10;// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError('n must be a positive number');this._maxListeners=n;return this;};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};// If there is no 'error' event listener then throw. +if(type==='error'){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er;// Unhandled 'error' event +}else{// At least give some kind of context to the user +var err=new Error('Uncaught, unspecified "error" event. ('+er+')');err.context=er;throw err;}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){// fast cases +case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;// slower +default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args);}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error('(node) warning: possible EventEmitter memory '+'leak detected. %d listeners added. '+'Use emitter.setMaxListeners() to increase limit.',this._events[type].length);if(typeof console.trace==='function'){// not supported in IE 10 +console.trace();}}}return this;};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError('listener must be a function');var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments);}}g.listener=listener;this.on(type,g);return this;};// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError('listener must be a function');if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit('removeListener',type,listener);}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break;}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type];}else{list.splice(position,1);}if(this._events.removeListener)this.emit('removeListener',type,listener);}return this;};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;// not listening for removeListener, no need to emit +if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this;}// emit removeListener for all listeners on all events +if(arguments.length===0){for(key in this._events){if(key==='removeListener')continue;this.removeAllListeners(key);}this.removeAllListeners('removeListener');this._events={};return this;}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners);}else if(listeners){// LIFO order +while(listeners.length)this.removeListener(type,listeners[listeners.length-1]);}delete this._events[type];return this;};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret;};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length;}return 0;};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type);};function isFunction(arg){return typeof arg==='function';}function isNumber(arg){return typeof arg==='number';}function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}function isUndefined(arg){return arg===void 0;}},{}],83:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias;}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity;}else{m=m+Math.pow(2,mLen);e=e-eBias;}return(s?-1:1)*m*Math.pow(2,e-mLen);};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax;}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2;}if(e+eBias>=1){value+=rt/c;}else{value+=rt*Math.pow(2,1-eBias);}if(value*c>=2){e++;c/=2;}if(e+eBias>=eMax){m=0;e=eMax;}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias;}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0;}}for(;mLen>=8;buffer[offset+i]=m&0xff,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&0xff,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128;};},{}],84:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=='[object Array]';};},{}],85:[function(require,module,exports){(function(exports){"use strict";function isArray(obj){if(obj!==null){return Object.prototype.toString.call(obj)==="[object Array]";}else{return false;}}function isObject(obj){if(obj!==null){return Object.prototype.toString.call(obj)==="[object Object]";}else{return false;}}function strictDeepEqual(first,second){// Check the scalar case first. +if(first===second){return true;}// Check if they are the same type. +var firstType=Object.prototype.toString.call(first);if(firstType!==Object.prototype.toString.call(second)){return false;}// We know that first and second have the same type so we can just check the +// first type from now on. +if(isArray(first)===true){// Short circuit if they're not the same length; +if(first.length!==second.length){return false;}for(var i=0;i" tokens +// are not in basicToken because +// there are two token variants +// ("&&", "[?", "<=", ">="). This is specially handled +// below. +var basicTokens={".":TOK_DOT,"*":TOK_STAR,",":TOK_COMMA,":":TOK_COLON,"{":TOK_LBRACE,"}":TOK_RBRACE,"]":TOK_RBRACKET,"(":TOK_LPAREN,")":TOK_RPAREN,"@":TOK_CURRENT};var operatorStartToken={"<":true,">":true,"=":true,"!":true};var skipChars={" ":true,"\t":true,"\n":true};function isAlpha(ch){return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="_";}function isNum(ch){return ch>="0"&&ch<="9"||ch==="-";}function isAlphaNum(ch){return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch>="0"&&ch<="9"||ch==="_";}function Lexer(){}Lexer.prototype={tokenize:function tokenize(stream){var tokens=[];this._current=0;var start;var identifier;var token;while(this._current"){if(stream[this._current]==="="){this._current++;return{type:TOK_GTE,value:">=",start:start};}else{return{type:TOK_GT,value:">",start:start};}}else if(startingChar==="="){if(stream[this._current]==="="){this._current++;return{type:TOK_EQ,value:"==",start:start};}}},_consumeLiteral:function _consumeLiteral(stream){this._current++;var start=this._current;var maxLength=stream.length;var literal;while(stream[this._current]!=="`"&&this._current" +literal=JSON.parse("\""+literalString+"\"");}// +1 gets us to the ending "`", +1 to move on to the next char. +this._current++;return literal;},_looksLikeJSON:function _looksLikeJSON(literalString){var startingChars="[{\"";var jsonLiterals=["true","false","null"];var numberLooking="-0123456789";if(literalString===""){return false;}else if(startingChars.indexOf(literalString[0])>=0){return true;}else if(jsonLiterals.indexOf(literalString)>=0){return true;}else if(numberLooking.indexOf(literalString[0])>=0){try{JSON.parse(literalString);return true;}catch(ex){return false;}}else{return false;}}};var bindingPower={};bindingPower[TOK_EOF]=0;bindingPower[TOK_UNQUOTEDIDENTIFIER]=0;bindingPower[TOK_QUOTEDIDENTIFIER]=0;bindingPower[TOK_RBRACKET]=0;bindingPower[TOK_RPAREN]=0;bindingPower[TOK_COMMA]=0;bindingPower[TOK_RBRACE]=0;bindingPower[TOK_NUMBER]=0;bindingPower[TOK_CURRENT]=0;bindingPower[TOK_EXPREF]=0;bindingPower[TOK_PIPE]=1;bindingPower[TOK_OR]=2;bindingPower[TOK_AND]=3;bindingPower[TOK_EQ]=5;bindingPower[TOK_GT]=5;bindingPower[TOK_LT]=5;bindingPower[TOK_GTE]=5;bindingPower[TOK_LTE]=5;bindingPower[TOK_NE]=5;bindingPower[TOK_FLATTEN]=9;bindingPower[TOK_STAR]=20;bindingPower[TOK_FILTER]=21;bindingPower[TOK_DOT]=40;bindingPower[TOK_NOT]=45;bindingPower[TOK_LBRACE]=50;bindingPower[TOK_LBRACKET]=55;bindingPower[TOK_LPAREN]=60;function Parser(){}Parser.prototype={parse:function parse(expression){this._loadTokens(expression);this.index=0;var ast=this.expression(0);if(this._lookahead(0)!==TOK_EOF){var t=this._lookaheadToken(0);var error=new Error("Unexpected token type: "+t.type+", value: "+t.value);error.name="ParserError";throw error;}return ast;},_loadTokens:function _loadTokens(expression){var lexer=new Lexer();var tokens=lexer.tokenize(expression);tokens.push({type:TOK_EOF,value:"",start:expression.length});this.tokens=tokens;},expression:function expression(rbp){var leftToken=this._lookaheadToken(0);this._advance();var left=this.nud(leftToken);var currentToken=this._lookahead(0);while(rbp=0){return this.expression(rbp);}else if(lookahead===TOK_LBRACKET){this._match(TOK_LBRACKET);return this._parseMultiselectList();}else if(lookahead===TOK_LBRACE){this._match(TOK_LBRACE);return this._parseMultiselectHash();}},_parseProjectionRHS:function _parseProjectionRHS(rbp){var right;if(bindingPower[this._lookahead(0)]<10){right={type:"Identity"};}else if(this._lookahead(0)===TOK_LBRACKET){right=this.expression(rbp);}else if(this._lookahead(0)===TOK_FILTER){right=this.expression(rbp);}else if(this._lookahead(0)===TOK_DOT){this._match(TOK_DOT);right=this._parseDotRHS(rbp);}else{var t=this._lookaheadToken(0);var error=new Error("Sytanx error, unexpected token: "+t.value+"("+t.type+")");error.name="ParserError";throw error;}return right;},_parseMultiselectList:function _parseMultiselectList(){var expressions=[];while(this._lookahead(0)!==TOK_RBRACKET){var expression=this.expression(0);expressions.push(expression);if(this._lookahead(0)===TOK_COMMA){this._match(TOK_COMMA);if(this._lookahead(0)===TOK_RBRACKET){throw new Error("Unexpected token Rbracket");}}}this._match(TOK_RBRACKET);return{type:"MultiSelectList",children:expressions};},_parseMultiselectHash:function _parseMultiselectHash(){var pairs=[];var identifierTypes=[TOK_UNQUOTEDIDENTIFIER,TOK_QUOTEDIDENTIFIER];var keyToken,keyName,value,node;for(;;){keyToken=this._lookaheadToken(0);if(identifierTypes.indexOf(keyToken.type)<0){throw new Error("Expecting an identifier token, got: "+keyToken.type);}keyName=keyToken.value;this._advance();this._match(TOK_COLON);value=this.expression(0);node={type:"KeyValuePair",name:keyName,value:value};pairs.push(node);if(this._lookahead(0)===TOK_COMMA){this._match(TOK_COMMA);}else if(this._lookahead(0)===TOK_RBRACE){this._match(TOK_RBRACE);break;}}return{type:"MultiSelectHash",children:pairs};}};function TreeInterpreter(runtime){this.runtime=runtime;}TreeInterpreter.prototype={search:function search(node,value){return this.visit(node,value);},visit:function visit(node,value){var matched,current,result,first,second,field,left,right,collected,i;switch(node.type){case"Field":if(value===null){return null;}else if(isObject(value)){field=value[node.name];if(field===undefined){return null;}else{return field;}}else{return null;}break;case"Subexpression":result=this.visit(node.children[0],value);for(i=1;i0){for(i=start;istop;i+=step){result.push(value[i]);}}return result;case"Projection":// Evaluate left child. +var base=this.visit(node.children[0],value);if(!isArray(base)){return null;}collected=[];for(i=0;isecond;break;case TOK_GTE:result=first>=second;break;case TOK_LT:result=first=arrayLength){actualValue=step<0?arrayLength-1:arrayLength;}return actualValue;}};function Runtime(interpreter){this._interpreter=interpreter;this.functionTable={// name: [function, ] +// The can be: +// +// { +// args: [[type1, type2], [type1, type2]], +// variadic: true|false +// } +// +// Each arg in the arg list is a list of valid types +// (if the function is overloaded and supports multiple +// types. If the type is "any" then no type checking +// occurs on the argument. Variadic is optional +// and if not provided is assumed to be false. +abs:{_func:this._functionAbs,_signature:[{types:[TYPE_NUMBER]}]},avg:{_func:this._functionAvg,_signature:[{types:[TYPE_ARRAY_NUMBER]}]},ceil:{_func:this._functionCeil,_signature:[{types:[TYPE_NUMBER]}]},contains:{_func:this._functionContains,_signature:[{types:[TYPE_STRING,TYPE_ARRAY]},{types:[TYPE_ANY]}]},"ends_with":{_func:this._functionEndsWith,_signature:[{types:[TYPE_STRING]},{types:[TYPE_STRING]}]},floor:{_func:this._functionFloor,_signature:[{types:[TYPE_NUMBER]}]},length:{_func:this._functionLength,_signature:[{types:[TYPE_STRING,TYPE_ARRAY,TYPE_OBJECT]}]},map:{_func:this._functionMap,_signature:[{types:[TYPE_EXPREF]},{types:[TYPE_ARRAY]}]},max:{_func:this._functionMax,_signature:[{types:[TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING]}]},"merge":{_func:this._functionMerge,_signature:[{types:[TYPE_OBJECT],variadic:true}]},"max_by":{_func:this._functionMaxBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},sum:{_func:this._functionSum,_signature:[{types:[TYPE_ARRAY_NUMBER]}]},"starts_with":{_func:this._functionStartsWith,_signature:[{types:[TYPE_STRING]},{types:[TYPE_STRING]}]},min:{_func:this._functionMin,_signature:[{types:[TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING]}]},"min_by":{_func:this._functionMinBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},type:{_func:this._functionType,_signature:[{types:[TYPE_ANY]}]},keys:{_func:this._functionKeys,_signature:[{types:[TYPE_OBJECT]}]},values:{_func:this._functionValues,_signature:[{types:[TYPE_OBJECT]}]},sort:{_func:this._functionSort,_signature:[{types:[TYPE_ARRAY_STRING,TYPE_ARRAY_NUMBER]}]},"sort_by":{_func:this._functionSortBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},join:{_func:this._functionJoin,_signature:[{types:[TYPE_STRING]},{types:[TYPE_ARRAY_STRING]}]},reverse:{_func:this._functionReverse,_signature:[{types:[TYPE_STRING,TYPE_ARRAY]}]},"to_array":{_func:this._functionToArray,_signature:[{types:[TYPE_ANY]}]},"to_string":{_func:this._functionToString,_signature:[{types:[TYPE_ANY]}]},"to_number":{_func:this._functionToNumber,_signature:[{types:[TYPE_ANY]}]},"not_null":{_func:this._functionNotNull,_signature:[{types:[TYPE_ANY],variadic:true}]}};}Runtime.prototype={callFunction:function callFunction(name,resolvedArgs){var functionEntry=this.functionTable[name];if(functionEntry===undefined){throw new Error("Unknown function: "+name+"()");}this._validateArgs(name,resolvedArgs,functionEntry._signature);return functionEntry._func.call(this,resolvedArgs);},_validateArgs:function _validateArgs(name,args,signature){// Validating the args requires validating +// the correct arity and the correct type of each arg. +// If the last argument is declared as variadic, then we need +// a minimum number of args to be required. Otherwise it has to +// be an exact amount. +var pluralized;if(signature[signature.length-1].variadic){if(args.length=0;i--){reversedStr+=originalStr[i];}return reversedStr;}else{var reversedArray=resolvedArgs[0].slice(0);reversedArray.reverse();return reversedArray;}},_functionAbs:function _functionAbs(resolvedArgs){return Math.abs(resolvedArgs[0]);},_functionCeil:function _functionCeil(resolvedArgs){return Math.ceil(resolvedArgs[0]);},_functionAvg:function _functionAvg(resolvedArgs){var sum=0;var inputArray=resolvedArgs[0];for(var i=0;i=0;},_functionFloor:function _functionFloor(resolvedArgs){return Math.floor(resolvedArgs[0]);},_functionLength:function _functionLength(resolvedArgs){if(!isObject(resolvedArgs[0])){return resolvedArgs[0].length;}else{// As far as I can tell, there's no way to get the length +// of an object without O(n) iteration through the object. +return Object.keys(resolvedArgs[0]).length;}},_functionMap:function _functionMap(resolvedArgs){var mapped=[];var interpreter=this._interpreter;var exprefNode=resolvedArgs[0];var elements=resolvedArgs[1];for(var i=0;i0){var typeName=this._getTypeName(resolvedArgs[0][0]);if(typeName===TYPE_NUMBER){return Math.max.apply(Math,resolvedArgs[0]);}else{var elements=resolvedArgs[0];var maxElement=elements[0];for(var i=1;i0){var typeName=this._getTypeName(resolvedArgs[0][0]);if(typeName===TYPE_NUMBER){return Math.min.apply(Math,resolvedArgs[0]);}else{var elements=resolvedArgs[0];var minElement=elements[0];for(var i=1;iexprB){return 1;}else if(exprAmaxNumber){maxNumber=current;maxRecord=resolvedArray[i];}}return maxRecord;},_functionMinBy:function _functionMinBy(resolvedArgs){var exprefNode=resolvedArgs[1];var resolvedArray=resolvedArgs[0];var keyFunction=this.createKeyFunction(exprefNode,[TYPE_NUMBER,TYPE_STRING]);var minNumber=Infinity;var minRecord;var current;for(var i=0;i1){for(var i=1;i0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};},{}],88:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if(_typeof(obj)==='object'){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(Array.isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};},{}],91:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if(_typeof(obj)==='object'){return Object.keys(obj).map(function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(Array.isArray(obj[k])){return obj[k].map(function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};},{}],92:[function(require,module,exports){arguments[4][89][0].apply(exports,arguments);},{"./decode":90,"./encode":91,"dup":89}],93:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require('process/browser.js').nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;// DOM APIs, for completeness +exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout);};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval);};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close();};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn;}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id);};// Does not start the time, just sets up the members needed. +exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs;};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1;};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout();},msecs);}};// That's not how node.js implements it but the exposed api is the same. +exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){// fn.call() is faster so we optimize for the common use-case +// @see http://jsperf.com/call-apply-segu +if(args){fn.apply(null,args);}else{fn.call(null);}// Prevent ids from leaking +exports.clearImmediate(id);}});return id;};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id];};}).call(this);}).call(this,require("timers").setImmediate,require("timers").clearImmediate);},{"process/browser.js":86,"timers":93}],94:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var punycode=require('punycode');exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){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;}// Reference: RFC 3986, RFC 1808, RFC 2396 +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,// RFC 2396: characters reserved for delimiting URLs. +// We actually just auto-escape these. +delims=['<','>','"','`',' ','\r','\n','\t'],// RFC 2396: characters not allowed for various reasons. +unwise=['{','}','|','\\','^','`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks. Always escape these. +autoEscape=['\''].concat(unwise),// Characters that are never ever allowed in a hostname. +// Note that any invalid chars are also handled, but these +// are the ones that are *expected* to be seen, so we fast-path +// them. +nonHostChars=['%','/','?',';','#'].concat(autoEscape),hostEndingChars=['/','?','#'],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars. +unsafeProtocol={'javascript':true,'javascript:':true},// protocols that never have a hostname. +hostlessProtocol={'javascript':true,'javascript:':true},// protocols that always contain a // bit. +slashedProtocol={'http':true,'https':true,'ftp':true,'gopher':true,'file':true,'http:':true,'https:':true,'ftp:':true,'gopher:':true,'file:':true},querystring=require('querystring');function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&isObject(url)&&url instanceof Url)return url;var u=new Url();u.parse(url,parseQueryString,slashesDenoteHost);return u;}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+_typeof(url));}var rest=url;// trim before proceeding. +// This is to support parse stuff like " http://foo.com \n" +rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length);}// figure out if it's got a host +// user@server is *always* interpreted as a hostname, and url +// resolution will treat //foo/bar as host=foo,path=bar because that's +// how the browser resolves relative URLs. +if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==='//';if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true;}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){// there's a hostname. +// the first instance of /, ?, ;, or # ends the host. +// +// If there is an @ in the hostname, then non-host chars *are* allowed +// to the left of the last @ sign, unless some host-ending character +// comes *before* the @-sign. +// URLs are obnoxious. +// +// ex: +// http://a@b@c/ => user:a@b host:c +// http://a@b?@c => user:a host:c path:/?@c +// v0.12 TODO(isaacs): This is not quite how Chrome does things. +// Review our test case against browsers more comprehensively. +// find the first instance of any hostEndingChars +var hostEnd=-1;for(var i=0;i host:b auth:a path:/c@d +atSign=rest.lastIndexOf('@',hostEnd);}// Now we have a portion which is definitely the auth. +// Pull that off. +if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth);}// the host is the remaining to the left of the first non-host char +hostEnd=-1;for(var i=0;i127){// we replace non-ASCII char with a temporary placeholder +// we need this to make sure size of hostname is not +// broken by replacing non-ASCII by nothing +newpart+='x';}else{newpart+=part[j];}}// we test again with ASCII char only +if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2]);}if(notHost.length){rest='/'+notHost.join('.')+rest;}this.hostname=validParts.join('.');break;}}}}if(this.hostname.length>hostnameMaxLen){this.hostname='';}else{// hostnames are always lower case. +this.hostname=this.hostname.toLowerCase();}if(!ipv6Hostname){// IDNA Support: Returns a puny coded representation of "domain". +// It only converts the part of the domain name that +// has non ASCII characters. I.e. it dosent matter if +// you call it with a domain that already is in ASCII. +var domainArray=this.hostname.split('.');var newOut=[];for(var i=0;i0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}result.search=relative.search;result.query=relative.query;//to support http.request +if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.href=result.format();return result;}if(!srcPath.length){// no path at all. easy. +// we've already handled the other stuff above. +result.pathname=null;//to support http.request +if(result.search){result.path='/'+result.search;}else{result.path=null;}result.href=result.format();return result;}// if a url ENDs in . or .., then it must get a trailing slash. +// however, if it ends in anything else non-slashy, +// then it must NOT get a trailing slash. +var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host)&&(last==='.'||last==='..')||last==='';// strip single dots, resolve double dots to parent dir +// if the path tries to go above the root, `up` ends up > 0 +var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last=='.'){srcPath.splice(i,1);}else if(last==='..'){srcPath.splice(i,1);up++;}else if(up){srcPath.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s +if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift('..');}}if(mustEndAbs&&srcPath[0]!==''&&(!srcPath[0]||srcPath[0].charAt(0)!=='/')){srcPath.unshift('');}if(hasTrailingSlash&&srcPath.join('/').substr(-1)!=='/'){srcPath.push('');}var isAbsolute=srcPath[0]===''||srcPath[0]&&srcPath[0].charAt(0)==='/';// put the host back +if(psychotic){result.hostname=result.host=isAbsolute?'':srcPath.length?srcPath.shift():'';//occationaly the auth can get stuck only in host +//this especialy happens in cases like +//url.resolveObject('mailto:local1@domain1', 'local2@domain2') +var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift('');}if(!srcPath.length){result.pathname=null;result.path=null;}else{result.pathname=srcPath.join('/');}//to support request.http +if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==':'){this.port=port.substr(1);}host=host.substr(0,host.length-port.length);}if(host)this.hostname=host;};function isString(arg){return typeof arg==="string";}function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}function isNull(arg){return arg===null;}function isNullOrUndefined(arg){return arg==null;}},{"punycode":80,"querystring":89}],95:[function(require,module,exports){if(typeof Object.create==='function'){// implementation from standard node.js 'util' module +module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}});};}else{// old school shim for old browsers +module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function TempCtor(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor();ctor.prototype.constructor=ctor;};}},{}],96:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&_typeof(arg)==='object'&&typeof arg.copy==='function'&&typeof arg.fill==='function'&&typeof arg.readUInt8==='function';};},{}],97:[function(require,module,exports){(function(process,global){(function(){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case'%s':return String(args[i++]);case'%d':return Number(args[i++]);case'%j':try{return JSON.stringify(args[i++]);}catch(_){return'[Circular]';}default:return x;}});for(var x=args[i];i Calling operation '%s'", method).sendInternalLogToServer(); - - this.client[method](params) - .on('build', function(request) { - request.httpRequest.headers['X-Amz-Bearer'] = self.authToken; - }) - .send(function(err, data) { - try { - if (err) { - if (err.code === connect.CTIExceptions.UNAUTHORIZED_EXCEPTION) { - callbacks.authFailure(); - } else if (callbacks.accessDenied && (err.code === connect.CTIExceptions.ACCESS_DENIED_EXCEPTION || err.statusCode === 403)) { - callbacks.accessDenied(); - } else { - // Can't pass err directly to postMessage - // postMessage() tries to clone the err object and failed. - // Refer to https://github.com/goatslacker/alt-devtool/issues/5 - var error = {}; - error.type = err.code; - error.message = err.message; - error.stack = err.stack ? err.stack.split('\n') : []; - callbacks.failure(error, data); - } - - log.trace("AWSClient: <-- Operation '%s' failed: %s", method, JSON.stringify(err)).sendInternalLogToServer(); - - } else { - log.trace("AWSClient: <-- Operation '%s' succeeded.", method).withObject(data).sendInternalLogToServer(); - callbacks.success(data); - } - } catch (e) { - connect.getLog().error("Failed to handle AWS API request for method %s", method) - .withException(e).sendInternalLogToServer(); - } - }); - } - }; - - AWSClient.prototype._requiresAuthenticationParam = function (method) { - return method !== connect.ClientMethods.COMPLETE_CONTACT && - method !== connect.ClientMethods.CLEAR_CONTACT && - method !== connect.ClientMethods.REJECT_CONTACT && - method !== connect.ClientMethods.CREATE_TASK_CONTACT; - }; - - AWSClient.prototype._translateParams = function(method, params) { - switch (method) { - case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION: - params.configuration = this._translateAgentConfiguration(params.configuration); - break; - - case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS: - params.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics( - params.softphoneStreamStatistics); - break; - - case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT: - params.report = this._translateSoftphoneCallReport(params.report); - break; - - default: - break; - } - - if (this._requiresAuthenticationParam(method)) { - params.authentication = { - authToken: this.authToken - }; - } - - return params; - }; - - AWSClient.prototype._translateAgentConfiguration = function(config) { - return { - name: config.name, - softphoneEnabled: config.softphoneEnabled, - softphoneAutoAccept: config.softphoneAutoAccept, - extension: config.extension, - routingProfile: this._translateRoutingProfile(config.routingProfile), - agentPreferences: config.agentPreferences - }; - }; - - AWSClient.prototype._translateRoutingProfile = function(profile) { - return { - name: profile.name, - routingProfileARN: profile.routingProfileARN, - defaultOutboundQueue: this._translateQueue(profile.defaultOutboundQueue) - }; - }; - - AWSClient.prototype._translateQueue = function(queue) { - return { - queueARN: queue.queueARN, - name: queue.name - }; - }; - - AWSClient.prototype._translateSoftphoneStreamStatistics = function(stats) { - stats.forEach(function(stat) { - if ('packetsCount' in stat) { - stat.packetCount = stat.packetsCount; - delete stat.packetsCount; - } - }); - - return stats; - }; - - AWSClient.prototype._translateSoftphoneCallReport = function(report) { - if ('handshakingTimeMillis' in report) { - report.handshakeTimeMillis = report.handshakingTimeMillis; - delete report.handshakingTimeMillis; - } - - if ('preTalkingTimeMillis' in report) { - report.preTalkTimeMillis = report.preTalkingTimeMillis; - delete report.preTalkingTimeMillis; - } - - if ('handshakingFailure' in report) { - report.handshakeFailure = report.handshakingFailure; - delete report.handshakingFailure; - } - - if ('talkingTimeMillis' in report) { - report.talkTimeMillis = report.talkingTimeMillis; - delete report.talkingTimeMillis; - } - - report.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics( - report.softphoneStreamStatistics); - - return report; - }; - - connect.ClientBase = ClientBase; - connect.NullClient = NullClient; - connect.UpstreamConduitClient = UpstreamConduitClient; - connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; - connect.AWSClient = AWSClient; - connect.AgentAppClient = AgentAppClient; - -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ /* legacy: obj, showHidden, depth, colors*/function inspect(obj,opts){// default options +var ctx={seen:[],stylize:stylizeNoColor};// legacy... +if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){// legacy... +ctx.showHidden=opts;}else if(opts){// got an "options" object +exports._extend(ctx,opts);}// set default options +if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth);}exports.inspect=inspect;// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.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]};// Don't use 'blue' not visible on cmd.exe +inspect.styles={'special':'cyan','number':'yellow','boolean':'yellow','undefined':'grey','null':'bold','string':'green','date':'magenta',// "name": intentionally not styling +'regexp':'red'};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"\x1B["+inspect.colors[style][0]+'m'+str+"\x1B["+inspect.colors[style][1]+'m';}else{return str;}}function stylizeNoColor(str,styleType){return str;}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true;});return hash;}function formatValue(ctx,value,recurseTimes){// Provide a hook for user-specified inspect functions. +// Check that value is an object with an inspect function on it +if(ctx.customInspect&&value&&isFunction(value.inspect)&&// Filter out the util module, it's inspect function is special +value.inspect!==exports.inspect&&// Also filter out any prototype objects using the circular check. +!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes);}return ret;}// Primitive types cannot have properties +var primitive=formatPrimitive(ctx,value);if(primitive){return primitive;}// Look up the keys of the object. +var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value);}// IE doesn't make error fields non-enumerable +// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx +if(isError(value)&&(keys.indexOf('message')>=0||keys.indexOf('description')>=0)){return formatError(value);}// Some type of object without properties can be shortcutted. +if(keys.length===0){if(isFunction(value)){var name=value.name?': '+value.name:'';return ctx.stylize('[Function'+name+']','special');}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),'date');}if(isError(value)){return formatError(value);}}var base='',array=false,braces=['{','}'];// Make Array say that they are Array +if(isArray(value)){array=true;braces=['[',']'];}// Make functions say that they are functions +if(isFunction(value)){var n=value.name?': '+value.name:'';base=' [Function'+n+']';}// Make RegExps say that they are RegExps +if(isRegExp(value)){base=' '+RegExp.prototype.toString.call(value);}// Make dates with properties first say the date +if(isDate(value)){base=' '+Date.prototype.toUTCString.call(value);}// Make error with message first say the error +if(isError(value)){base=' '+formatError(value);}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1];}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}else{return ctx.stylize('[Object]','special');}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array);});}ctx.seen.pop();return reduceToSingleString(output,base,braces);}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize('undefined','undefined');if(isString(value)){var simple='\''+JSON.stringify(value).replace(/^"|"$/g,'').replace(/'/g,"\\'").replace(/\\"/g,'"')+'\'';return ctx.stylize(simple,'string');}if(isNumber(value))return ctx.stylize(''+value,'number');if(isBoolean(value))return ctx.stylize(''+value,'boolean');// For some reason typeof null is "object", so special case here. +if(isNull(value))return ctx.stylize('null','null');}function formatError(value){return'['+Error.prototype.toString.call(value)+']';}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split('\n').map(function(line){return' '+line;}).join('\n').substr(2);}else{str='\n'+str.split('\n').map(function(line){return' '+line;}).join('\n');}}}else{str=ctx.stylize('[Circular]','special');}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str;}name=JSON.stringify(''+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,'name');}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,'string');}}return name+': '+str;}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf('\n')>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,'').length+1;},0);if(length>60){return braces[0]+(base===''?'':base+'\n ')+' '+output.join(',\n ')+' '+braces[1];}return braces[0]+base+' '+output.join(', ')+' '+braces[1];}// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar){return Array.isArray(ar);}exports.isArray=isArray;function isBoolean(arg){return typeof arg==='boolean';}exports.isBoolean=isBoolean;function isNull(arg){return arg===null;}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null;}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==='number';}exports.isNumber=isNumber;function isString(arg){return typeof arg==='string';}exports.isString=isString;function isSymbol(arg){return _typeof(arg)==='symbol';}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0;}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==='[object RegExp]';}exports.isRegExp=isRegExp;function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==='[object Date]';}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==='[object Error]'||e instanceof Error);}exports.isError=isError;function isFunction(arg){return typeof arg==='function';}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==='boolean'||typeof arg==='number'||typeof arg==='string'||_typeof(arg)==='symbol'||// ES6 symbol +typeof arg==='undefined';}exports.isPrimitive=isPrimitive;exports.isBuffer=require('./support/isBuffer');function objectToString(o){return Object.prototype.toString.call(o);}function pad(n){return n<10?'0'+n.toString(10):n.toString(10);}var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];// 26 Feb 16:19:34 +function timestamp(){var d=new Date();var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(':');return[d.getDate(),months[d.getMonth()],time].join(' ');}// log is just a thin wrapper to console.log that prepends a timestamp +exports.log=function(){console.log('%s - %s',timestamp(),exports.format.apply(exports,arguments));};/** + * Inherit the prototype methods from one constructor into another. * - * SPDX-License-Identifier: Apache-2.0 - */ -(function() { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /**------------------------------------------------------------------------- - * GraphLink <> - * - * Represents the association of one or more attributes to a state transition. - */ - var GraphLink = function(fromState, toState) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - this.fromState = fromState; - this.toState = toState; - }; - - GraphLink.prototype.getAssociations = function(context) { - throw connect.NotImplementedError(); - }; - - GraphLink.prototype.getFromState = function() { - return this.fromState; - }; - - GraphLink.prototype.getToState = function() { - return this.toState; - }; - - /**------------------------------------------------------------------------- - * DirectGraphLink <> extends GraphLink - * - * Represents the by-value representation of one or more attributes to a - * state transition. - */ - var DirectGraphLink = function(fromState, toState, associations) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - connect.assertNotNull(associations, 'associations'); - GraphLink.call(this, fromState, toState); - this.associations = associations; - }; - DirectGraphLink.prototype = Object.create(GraphLink.prototype); - DirectGraphLink.prototype.constructor = DirectGraphLink; - - DirectGraphLink.prototype.getAssociations = function(context) { - return this.associations; - }; - - /** - * FunctionalGraphLink <> extends GraphLink - * - * Represents a functional association of one or more attributes to a - * state transition. - */ - var FunctionalGraphLink = function(fromState, toState, closure) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - connect.assertNotNull(closure, 'closure'); - connect.assertTrue(connect.isFunction(closure), 'closure must be a function'); - GraphLink.call(this, fromState, toState); - this.closure = closure; - }; - FunctionalGraphLink.prototype = Object.create(GraphLink.prototype); - FunctionalGraphLink.prototype.constructor = FunctionalGraphLink; - - FunctionalGraphLink.prototype.getAssociations = function(context) { - return this.closure(context, this.getFromState(), this.getToState()); - }; - - /**------------------------------------------------------------------------- - * EventGraph <> - * - * Builds a map of associations from one state to another in context of a - * particular object. The associations can be direct (one or more values) - * or functional (a method returning one or more values), and are used to - * provide additional contextual event hooks for the UI to consume. - */ - var EventGraph = function() { - this.fromMap = {}; - }; - EventGraph.ANY = "<>"; - - EventGraph.prototype.assoc = function(fromStateObj, toStateObj, assocObj) { - var self = this; - - if (! fromStateObj) { - throw new Error("fromStateObj is not defined."); - } - - if (! toStateObj) { - throw new Error("toStateObj is not defined."); - } - - if (! assocObj) { - throw new Error("assocObj is not defined."); - } - - if (fromStateObj instanceof Array) { - fromStateObj.forEach(function(fromState) { - self.assoc(fromState, toStateObj, assocObj); - }); - } else if (toStateObj instanceof Array) { - toStateObj.forEach(function(toState) { - self.assoc(fromStateObj, toState, assocObj); - }); - } else { - if (typeof assocObj === "function") { - this._addAssociation(new FunctionalGraphLink(fromStateObj, toStateObj, assocObj)); - } else if (assocObj instanceof Array) { - this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, assocObj)); - } else { - this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, [assocObj])); - } - } - return this; - }; - - EventGraph.prototype.getAssociations = function(context, fromState, toState) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - var associations = []; - - var toMapFromAny = this.fromMap[EventGraph.ANY] || {}; - var toMap = this.fromMap[fromState] || {}; - - associations = associations.concat(this._getAssociationsFromMap( - toMapFromAny, context, fromState, toState)); - associations = associations.concat(this._getAssociationsFromMap( - toMap, context, fromState, toState)); - - return associations; - }; - - EventGraph.prototype._addAssociation = function(assoc) { - var toMap = this.fromMap[assoc.getFromState()]; - - if (! toMap) { - toMap = this.fromMap[assoc.getFromState()] = {}; - } - - var assocList = toMap[assoc.getToState()]; - - if (! assocList) { - assocList = toMap[assoc.getToState()] = []; - } - - assocList.push(assoc); - }; - - EventGraph.prototype._getAssociationsFromMap = function(map, context, fromState, toState) { - var assocList = (map[EventGraph.ANY] || []).concat(map[toState] || []); - return assocList.reduce(function(prev, assoc) { - return prev.concat(assoc.getAssociations(context)); - }, []); - }; - - connect.EventGraph = EventGraph; - -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). * - * SPDX-License-Identifier: Apache-2.0 - */ -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /*---------------------------------------------------------------- - * enum AgentStateType - */ - connect.AgentStateType = connect.makeEnum([ - 'init', - 'routable', - 'not_routable', - 'offline' - ]); - connect.AgentStatusType = connect.AgentStateType; - - /** - * enum AgentAvailStates - */ - connect.AgentAvailStates = connect.makeEnum([ - 'Init', - 'Busy', - 'AfterCallWork', - 'CallingCustomer', - 'Dialing', - 'Joining', - 'PendingAvailable', - 'PendingBusy' - ]); - - /** - * enum AgentErrorStates - */ - connect.AgentErrorStates = connect.makeEnum([ - 'Error', - 'AgentHungUp', - 'BadAddressAgent', - 'BadAddressCustomer', - 'Default', - 'FailedConnectAgent', - 'FailedConnectCustomer', - 'InvalidLocale', - 'LineEngagedAgent', - 'LineEngagedCustomer', - 'MissedCallAgent', - 'MissedCallCustomer', - 'MultipleCcpWindows', - 'RealtimeCommunicationError' - ]); - - /*---------------------------------------------------------------- - * enum AddressType - */ - connect.EndpointType = connect.makeEnum([ - 'phone_number', - 'agent', - 'queue' - ]); - connect.AddressType = connect.EndpointType; - - /*---------------------------------------------------------------- - * enum ConnectionType - */ - connect.ConnectionType = connect.makeEnum([ - 'agent', - 'inbound', - 'outbound', - 'monitoring' - ]); - - /*---------------------------------------------------------------- - * enum ConnectionStateType - */ - connect.ConnectionStateType = connect.makeEnum([ - 'init', - 'connecting', - 'connected', - 'hold', - 'disconnected' - ]); - connect.ConnectionStatusType = connect.ConnectionStateType; - - connect.CONNECTION_ACTIVE_STATES = connect.set([ - connect.ConnectionStateType.CONNECTING, - connect.ConnectionStateType.CONNECTED, - connect.ConnectionStateType.HOLD - ]); - - /*---------------------------------------------------------------- - * enum ContactStateType - */ - connect.ContactStateType = connect.makeEnum([ - 'init', - 'incoming', - 'pending', - 'connecting', - 'connected', - 'missed', - 'error', - 'ended' - ]); - connect.ContactStatusType = connect.ContactStateType; - - connect.CONTACT_ACTIVE_STATES = connect.makeEnum([ - 'incoming', - 'pending', - 'connecting', - 'connected' - ]); - - /*---------------------------------------------------------------- - * enum ContactType - */ - connect.ContactType = connect.makeEnum([ - 'voice', - 'queue_callback', - 'chat', - 'task' - ]); - - /*---------------------------------------------------------------- - * enum ContactInitiationMethod - */ - connect.ContactInitiationMethod = connect.makeEnum([ - 'inbound', - 'outbound', - 'transfer', - 'queue_transfer', - 'callback', - 'api', - 'disconnect' - ]); - - /*---------------------------------------------------------------- - * enum ChannelType - */ - connect.ChannelType = connect.makeEnum([ - 'VOICE', - 'CHAT', - 'TASK' - ]); - - /*---------------------------------------------------------------- - * enum MediaType - */ - connect.MediaType = connect.makeEnum([ - 'softphone', - 'chat', - 'task' - ]); - - /*---------------------------------------------------------------- - * enum SoftphoneCallType - */ - connect.SoftphoneCallType = connect.makeEnum([ - 'audio_video', - 'video_only', - 'audio_only', - 'none' - ]); - - /*---------------------------------------------------------------- - * enum for SoftphoneErrorTypes - */ - connect.SoftphoneErrorTypes = connect.makeEnum([ - 'unsupported_browser', - 'microphone_not_shared', - 'signalling_handshake_failure', - 'signalling_connection_failure', - 'ice_collection_timeout', - 'user_busy_error', - 'webrtc_error', - 'realtime_communication_error', - 'other' - ]); - - /*---------------------------------------------------------------- - * enum for VoiceIdErrorTypes - */ - connect.VoiceIdErrorTypes = connect.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' - ]); - - /*---------------------------------------------------------------- - * enum for CTI exceptions - */ - connect.CTIExceptions = connect.makeEnum([ - "AccessDeniedException", - "InvalidStateException", - "BadEndpointException", - "InvalidAgentARNException", - "InvalidConfigurationException", - "InvalidContactTypeException", - "PaginationException", - "RefreshTokenExpiredException", - "SendDataFailedException", - "UnauthorizedException", - "QuotaExceededException" - ]); - /*---------------------------------------------------------------- - * enum for VoiceId streaming status - */ - connect.VoiceIdStreamingStatus = connect.makeEnum([ - "ONGOING", - "ENDED", - "PENDING_CONFIGURATION" - ]); - - /*---------------------------------------------------------------- - * enum for VoiceId authentication decision - */ - connect.VoiceIdAuthenticationDecision = connect.makeEnum([ - "ACCEPT", - "REJECT", - "NOT_ENOUGH_SPEECH", - "SPEAKER_NOT_ENROLLED", - "SPEAKER_OPTED_OUT", - "SPEAKER_ID_NOT_PROVIDED", - "SPEAKER_EXPIRED" - ]); - - /*---------------------------------------------------------------- - * enum for VoiceId fraud detection decision - */ - connect.VoiceIdFraudDetectionDecision = connect.makeEnum([ - "NOT_ENOUGH_SPEECH", - "HIGH_RISK", - "LOW_RISK" - ]); - - /*---------------------------------------------------------------- - * enum for contact flow authentication decision - */ - connect.ContactFlowAuthenticationDecision = connect.makeEnum([ - "Authenticated", - "NotAuthenticated", - "Inconclusive", - "NotEnrolled", - "OptedOut", - "NotEnabled", - "Error" - ]); - - /*---------------------------------------------------------------- - * enum for contact flow fraud detection decision - */ - connect.ContactFlowFraudDetectionDecision = connect.makeEnum([ - "HighRisk", - "LowRisk", - "Inconclusive", - "NotEnabled", - "Error" - ]); - - /*---------------------------------------------------------------- - * enum for VoiceId EnrollmentRequest Status - */ - connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum([ - "NOT_ENOUGH_SPEECH", - "IN_PROGRESS", - "COMPLETED", - "FAILED" - ]); + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */exports.inherits=require('inherits');exports._extend=function(origin,add){// Don't do anything if add isn't an object +if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]];}return origin;};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}}).call(this);}).call(this,require('_process'),typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./support/isBuffer":96,"_process":86,"inherits":95}],98:[function(require,module,exports){var v1=require('./v1');var v4=require('./v4');var uuid=v4;uuid.v1=v1;uuid.v4=v4;module.exports=uuid;},{"./v1":101,"./v4":102}],99:[function(require,module,exports){/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+0x100).toString(16).substr(1);}function bytesToUuid(buf,offset){var i=offset||0;var bth=byteToHex;// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 +return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join('');}module.exports=bytesToUuid;},{}],100:[function(require,module,exports){// Unique ID creation requires a high quality random # generator. In the +// browser this is a little complicated due to unknown quality of Math.random() +// and inconsistent support for the `crypto` API. We do the best we can via +// feature-detection +// getRandomValues needs to be invoked in a context where "this" is a Crypto +// implementation. Also, find the complete implementation of crypto on IE11. +var getRandomValues=typeof crypto!='undefined'&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!='undefined'&&typeof window.msCrypto.getRandomValues=='function'&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto +var rnds8=new Uint8Array(16);// eslint-disable-line no-undef +module.exports=function whatwgRNG(){getRandomValues(rnds8);return rnds8;};}else{// Math.random()-based (RNG) +// +// If all else fails, use Math.random(). It's fast, but is of unspecified +// quality. +var rnds=new Array(16);module.exports=function mathRNG(){for(var i=0,r;i<16;i++){if((i&0x03)===0)r=Math.random()*0x100000000;rnds[i]=r>>>((i&0x03)<<3)&0xff;}return rnds;};}},{}],101:[function(require,module,exports){var rng=require('./lib/rng');var bytesToUuid=require('./lib/bytesToUuid');// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +var _nodeId;var _clockseq;// Previous uuid creation time +var _lastMSecs=0;var _lastNSecs=0;// See https://github.com/broofa/node-uuid for API details +function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var node=options.node||_nodeId;var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;// node and clockseq need to be initialized to random values if they're not +// specified. We do this lazily to minimize issues related to insufficient +// system entropy. See #189 +if(node==null||clockseq==null){var seedBytes=rng();if(node==null){// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) +node=_nodeId=[seedBytes[0]|0x01,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]];}if(clockseq==null){// Per 4.2.2, randomize (14 bit) clockseq +clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&0x3fff;}}// UUID timestamps are 100 nano-second units since the Gregorian epoch, +// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so +// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' +// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. +var msecs=options.msecs!==undefined?options.msecs:new Date().getTime();// Per 4.2.1.2, use count of uuid's generated during the current clock +// cycle to simulate higher resolution clock +var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;// Time since last uuid creation (in msecs) +var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/10000;// Per 4.2.1.2, Bump clockseq on clock regression +if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&0x3fff;}// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new +// time interval +if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0;}// Per 4.2.1.2 Throw error if too many uuids are requested +if(nsecs>=10000){throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;// Per 4.1.4 - Convert from unix epoch to Gregorian epoch +msecs+=12219292800000;// `time_low` +var tl=((msecs&0xfffffff)*10000+nsecs)%0x100000000;b[i++]=tl>>>24&0xff;b[i++]=tl>>>16&0xff;b[i++]=tl>>>8&0xff;b[i++]=tl&0xff;// `time_mid` +var tmh=msecs/0x100000000*10000&0xfffffff;b[i++]=tmh>>>8&0xff;b[i++]=tmh&0xff;// `time_high_and_version` +b[i++]=tmh>>>24&0xf|0x10;// include version +b[i++]=tmh>>>16&0xff;// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) +b[i++]=clockseq>>>8|0x80;// `clock_seq_low` +b[i++]=clockseq&0xff;// `node` +for(var n=0;n<6;++n){b[i+n]=node[n];}return buf?buf:bytesToUuid(b);}module.exports=v1;},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(require,module,exports){var rng=require('./lib/rng');var bytesToUuid=require('./lib/bytesToUuid');function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=='string'){buf=options==='binary'?new Array(16):null;options=null;}options=options||{};var rnds=options.random||(options.rng||rng)();// Per 4.4, set bits for version and `clock_seq_hi_and_reserved` +rnds[6]=rnds[6]&0x0f|0x40;rnds[8]=rnds[8]&0x3f|0x80;// Copy bytes to buffer, if provided +if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii];}}return buf||bytesToUuid(rnds);}module.exports=v4;},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var LRU_1=require("./utils/LRU");var CACHE_SIZE=1000;/** + * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache] + */var EndpointCache=/** @class */function(){function EndpointCache(maxSize){if(maxSize===void 0){maxSize=CACHE_SIZE;}this.maxSize=maxSize;this.cache=new LRU_1.LRUCache(maxSize);};Object.defineProperty(EndpointCache.prototype,"size",{get:function get(){return this.cache.length;},enumerable:true,configurable:true});EndpointCache.prototype.put=function(key,value){var keyString=typeof key!=='string'?EndpointCache.getKeyString(key):key;var endpointRecord=this.populateValue(value);this.cache.put(keyString,endpointRecord);};EndpointCache.prototype.get=function(key){var keyString=typeof key!=='string'?EndpointCache.getKeyString(key):key;var now=Date.now();var records=this.cache.get(keyString);if(records){for(var i=0;i { - /*---------------------------------------------------------------- - * constants for AgentPermissions - */ - connect.AgentPermissions = { - OUTBOUND_CALL: 'outboundCall', - VOICE_ID: 'voiceId' - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; - /*---------------------------------------------------------------- - * class Agent + /**--------------------------------------------------------------- + * enum ClientMethods */ - var Agent = function () { - if (!connect.agent.initialized) { - throw new connect.StateError("The agent is not yet initialized!"); - } - }; - - Agent.prototype._getData = function () { - return connect.core.getAgentDataProvider().getAgentData(); - }; + connect.ClientMethods = connect.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']); - Agent.prototype._createContactAPI = function (contactData) { - return new connect.Contact(contactData.contactId); + /**--------------------------------------------------------------- + * enum AgentAppClientMethods + */ + connect.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" }; - /** - * @deprecated - * Use `contact.onPending` for any particular contact instead. + /**--------------------------------------------------------------- + * enum MasterMethods */ - Agent.prototype.onContactPending = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.CONTACT_PENDING, f); - }; - - Agent.prototype.onRefresh = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.REFRESH, f); - }; - - Agent.prototype.onRoutable = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ROUTABLE, f); - }; - - Agent.prototype.onNotRoutable = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.NOT_ROUTABLE, f); - }; - - Agent.prototype.onOffline = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.OFFLINE, f); - }; + connect.MasterMethods = connect.makeEnum(['becomeMaster', 'checkMaster']); - Agent.prototype.onError = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ERROR, f); + /**--------------------------------------------------------------- + * abstract class ClientBase + */ + var ClientBase = function ClientBase() {}; + ClientBase.EMPTY_CALLBACKS = { + success: function success() {}, + failure: function failure() {} }; - - Agent.prototype.onSoftphoneError = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.SOFTPHONE_ERROR, f); + ClientBase.prototype.call = function (method, paramsIn, callbacksIn) { + connect.assertNotNull(method, 'method'); + var params = paramsIn || {}; + var callbacks = callbacksIn || ClientBase.EMPTY_CALLBACKS; + this._callImpl(method, params, callbacks); }; - - Agent.prototype.onWebSocketConnectionLost = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, f); - } - - Agent.prototype.onWebSocketConnectionGained = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED, f); - } - - Agent.prototype.onAfterCallWork = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ACW, f); + ClientBase.prototype._callImpl = function (method, params, callbacks) { + throw new connect.NotImplementedError(); }; - Agent.prototype.onStateChange = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.STATE_CHANGE, f); + /**--------------------------------------------------------------- + * class NullClient extends ClientBase + */ + var NullClient = function NullClient() { + ClientBase.call(this); + }; + NullClient.prototype = Object.create(ClientBase.prototype); + NullClient.prototype.constructor = NullClient; + NullClient.prototype._callImpl = function (method, params, callbacks) { + if (callbacks && callbacks.failure) { + var message = connect.sprintf('No such method exists on NULL client: %s', method); + callbacks.failure(new connect.ValueError(message), { + message: message + }); + } }; - Agent.prototype.onMuteToggle = function (f) { - connect.core.getUpstream().onUpstream(connect.AgentEvents.MUTE_TOGGLE, f); + /**--------------------------------------------------------------- + * abstract class UpstreamConduitClientBase extends ClientBase + */ + var UpstreamConduitClientBase = function UpstreamConduitClientBase(conduit, requestEvent, responseEvent) { + ClientBase.call(this); + this.conduit = conduit; + this.requestEvent = requestEvent; + this.responseEvent = responseEvent; + this._requestIdCallbacksMap = {}; + this.conduit.onUpstream(responseEvent, connect.hitch(this, this._handleResponse)); + }; + UpstreamConduitClientBase.prototype = Object.create(ClientBase.prototype); + UpstreamConduitClientBase.prototype.constructor = UpstreamConduitClientBase; + UpstreamConduitClientBase.prototype._callImpl = function (method, params, callbacks) { + var request = connect.EventFactory.createRequest(this.requestEvent, method, params); + this._requestIdCallbacksMap[request.requestId] = callbacks; + this.conduit.sendUpstream(request.event, request); + }; + UpstreamConduitClientBase.prototype._getCallbacksForRequest = function (requestId) { + var callbacks = this._requestIdCallbacksMap[requestId] || null; + if (callbacks != null) { + delete this._requestIdCallbacksMap[requestId]; + } + return callbacks; + }; + UpstreamConduitClientBase.prototype._handleResponse = function (data) { + var callbacks = this._getCallbacksForRequest(data.requestId); + if (callbacks == null) { + return; + } + if (data.err && callbacks.failure) { + callbacks.failure(data.err, data.data); + } else if (callbacks.success) { + callbacks.success(data.data); + } }; - Agent.prototype.onLocalMediaStreamCreated = function (f) { - connect.core.getUpstream().onUpstream(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, f); + /**--------------------------------------------------------------- + * class UpstreamConduitClient extends ClientBase + */ + var UpstreamConduitClient = function UpstreamConduitClient(conduit) { + UpstreamConduitClientBase.call(this, conduit, connect.EventType.API_REQUEST, connect.EventType.API_RESPONSE); }; + UpstreamConduitClient.prototype = Object.create(UpstreamConduitClientBase.prototype); + UpstreamConduitClient.prototype.constructor = UpstreamConduitClient; - Agent.prototype.onSpeakerDeviceChanged = function(f){ - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, f); - } - - Agent.prototype.onMicrophoneDeviceChanged = function(f){ - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, f); - } - - Agent.prototype.onRingerDeviceChanged = function(f){ - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, f); - } - - Agent.prototype.mute = function () { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, - { - event: connect.EventType.MUTE, - data: { mute: true } - }); + /**--------------------------------------------------------------- + * class UpstreamConduitMasterClient extends ClientBase + */ + var UpstreamConduitMasterClient = function UpstreamConduitMasterClient(conduit) { + UpstreamConduitClientBase.call(this, conduit, connect.EventType.MASTER_REQUEST, connect.EventType.MASTER_RESPONSE); }; + UpstreamConduitMasterClient.prototype = Object.create(UpstreamConduitClientBase.prototype); + UpstreamConduitMasterClient.prototype.constructor = UpstreamConduitMasterClient; - Agent.prototype.unmute = function () { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, - { - event: connect.EventType.MUTE, - data: { mute: false } + /**--------------------------------------------------------------- + * class AgentAppClient extends ClientBase + */ + var AgentAppClient = function AgentAppClient(authCookieName, authToken, endpoint) { + connect.assertNotNull(authCookieName, 'authCookieName'); + connect.assertNotNull(authToken, 'authToken'); + connect.assertNotNull(endpoint, 'endpoint'); + ClientBase.call(this); + this.endpointUrl = connect.getUrlWithProtocol(endpoint); + this.authToken = authToken; + this.authCookieName = authCookieName; + }; + AgentAppClient.prototype = Object.create(ClientBase.prototype); + AgentAppClient.prototype.constructor = AgentAppClient; + AgentAppClient.prototype._callImpl = function (method, params, callbacks) { + var self = this; + var bear = {}; + bear[self.authCookieName] = self.authToken; + var options = { + method: 'post', + body: JSON.stringify(params || {}), + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'X-Amz-target': method, + 'X-Amz-Bearer': JSON.stringify(bear) + } + }; + connect.fetch(self.endpointUrl, options).then(function (res) { + callbacks.success(res); + })["catch"](function (err) { + var reader = err.body.getReader(); + var body = ''; + var decoder = new TextDecoder(); + reader.read().then(function processText(_ref) { + var done = _ref.done, + value = _ref.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); }); - }; - - Agent.prototype.setSpeakerDevice = function (deviceId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SET_SPEAKER_DEVICE, - data: { deviceId: deviceId } - }); - }; - - Agent.prototype.setMicrophoneDevice = function (deviceId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, - data: { deviceId: deviceId } }); }; - - Agent.prototype.setRingerDevice = function (deviceId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SET_RINGER_DEVICE, - data: { deviceId: deviceId } + /**--------------------------------------------------------------- + * class AWSClient extends ClientBase + */ + var AWSClient = function AWSClient(authToken, region, endpointIn) { + connect.assertNotNull(authToken, 'authToken'); + connect.assertNotNull(region, 'region'); + ClientBase.call(this); + AWS.config.credentials = new AWS.Credentials({}); + AWS.config.region = region; + this.authToken = authToken; + var baseUrl = connect.getBaseUrl(); + var endpointUrl = endpointIn || (baseUrl.includes(".awsapps.com") ? baseUrl + '/connect/api' : baseUrl + '/api'); + var endpoint = new AWS.Endpoint(endpointUrl); + this.client = new AWS.Connect({ + endpoint: endpoint }); }; - - Agent.prototype.getState = function () { - return this._getData().snapshot.state; - }; - - Agent.prototype.getNextState = function () { - return this._getData().snapshot.nextState; - }; - - Agent.prototype.getAvailabilityState = function () { - return this._getData().snapshot.agentAvailabilityState; - }; - - Agent.prototype.getStatus = Agent.prototype.getState; - - Agent.prototype.getStateDuration = function () { - return connect.now() - this._getData().snapshot.state.startTimestamp.getTime() + connect.core.getSkew(); - }; - - Agent.prototype.getStatusDuration = Agent.prototype.getStateDuration; - - Agent.prototype.getPermissions = function () { - return this.getConfiguration().permissions; - }; - - Agent.prototype.getContacts = function (contactTypeFilter) { + AWSClient.prototype = Object.create(ClientBase.prototype); + AWSClient.prototype.constructor = AWSClient; + AWSClient.prototype._callImpl = function (method, params, callbacks) { var self = this; - return this._getData().snapshot.contacts.map(function (contactData) { - return self._createContactAPI(contactData); - }).filter(function (contact) { - return (!contactTypeFilter) || contact.getType() === contactTypeFilter; - }); - }; - - Agent.prototype.getConfiguration = function () { - return this._getData().configuration; - }; - - Agent.prototype.getAgentStates = function () { - return this.getConfiguration().agentStates; - }; - - Agent.prototype.getRoutingProfile = function () { - return this.getConfiguration().routingProfile; - }; - - Agent.prototype.getChannelConcurrency = function (channel) { - var channelConcurrencyMap = this.getRoutingProfile().channelConcurrencyMap; - if (!channelConcurrencyMap) { - channelConcurrencyMap = Object.keys(connect.ChannelType).reduce(function (acc, key) { - // Exclude TASK from default concurrency. - if (key !== 'TASK') { - acc[connect.ChannelType[key]] = 1; + var log = connect.getLog(); + if (!connect.contains(this.client, method)) { + var message = connect.sprintf('No such method exists on AWS client: %s', method); + callbacks.failure(new connect.ValueError(message), { + message: message + }); + } else { + params = this._translateParams(method, params); + log.trace("AWSClient: --> Calling operation '%s'", method).sendInternalLogToServer(); + this.client[method](params).on('build', function (request) { + request.httpRequest.headers['X-Amz-Bearer'] = self.authToken; + }).send(function (err, data) { + try { + if (err) { + if (err.code === connect.CTIExceptions.UNAUTHORIZED_EXCEPTION) { + callbacks.authFailure(); + } else if (callbacks.accessDenied && (err.code === connect.CTIExceptions.ACCESS_DENIED_EXCEPTION || err.statusCode === 403)) { + callbacks.accessDenied(); + } else { + // Can't pass err directly to postMessage + // postMessage() tries to clone the err object and failed. + // Refer to https://github.com/goatslacker/alt-devtool/issues/5 + var error = {}; + error.type = err.code; + error.message = err.message; + error.stack = err.stack ? err.stack.split('\n') : []; + callbacks.failure(error, data); + } + log.trace("AWSClient: <-- Operation '%s' failed: %s", method, JSON.stringify(err)).sendInternalLogToServer(); + } else { + log.trace("AWSClient: <-- Operation '%s' succeeded.", method).withObject(data).sendInternalLogToServer(); + callbacks.success(data); + } + } catch (e) { + connect.getLog().error("Failed to handle AWS API request for method %s", method).withException(e).sendInternalLogToServer(); } - return acc; - }, {}); + }); } - return channel - ? (channelConcurrencyMap[channel] || 0) - : channelConcurrencyMap; }; - - Agent.prototype.getName = function () { - return this.getConfiguration().name; + AWSClient.prototype._requiresAuthenticationParam = function (method) { + return method !== connect.ClientMethods.COMPLETE_CONTACT && method !== connect.ClientMethods.CLEAR_CONTACT && method !== connect.ClientMethods.REJECT_CONTACT && method !== connect.ClientMethods.CREATE_TASK_CONTACT; }; - - Agent.prototype.getExtension = function () { - return this.getConfiguration().extension; + AWSClient.prototype._translateParams = function (method, params) { + switch (method) { + case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION: + params.configuration = this._translateAgentConfiguration(params.configuration); + break; + case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS: + params.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(params.softphoneStreamStatistics); + break; + case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT: + params.report = this._translateSoftphoneCallReport(params.report); + break; + default: + break; + } + if (this._requiresAuthenticationParam(method)) { + params.authentication = { + authToken: this.authToken + }; + } + return params; }; - - Agent.prototype.getDialableCountries = function () { - return this.getConfiguration().dialableCountries; + AWSClient.prototype._translateAgentConfiguration = function (config) { + return { + name: config.name, + softphoneEnabled: config.softphoneEnabled, + softphoneAutoAccept: config.softphoneAutoAccept, + extension: config.extension, + routingProfile: this._translateRoutingProfile(config.routingProfile), + agentPreferences: config.agentPreferences + }; }; - - Agent.prototype.isSoftphoneEnabled = function () { - return this.getConfiguration().softphoneEnabled; + AWSClient.prototype._translateRoutingProfile = function (profile) { + return { + name: profile.name, + routingProfileARN: profile.routingProfileARN, + defaultOutboundQueue: this._translateQueue(profile.defaultOutboundQueue) + }; }; - - Agent.prototype.setConfiguration = function (configuration, callbacks) { - var client = connect.core.getClient(); - if (configuration && configuration.agentPreferences && !connect.isValidLocale(configuration.agentPreferences.locale)) { - if (callbacks && callbacks.failure) { - callbacks.failure(connect.AgentErrorStates.INVALID_LOCALE); - } - } else { - client.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION, { - configuration: connect.assertNotNull(configuration, 'configuration') - }, { - success: function (data) { - // We need to ask the shared worker to reload agent config - // once we change it so every tab has accurate config. - var conduit = connect.core.getUpstream(); - conduit.sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION); - - if (callbacks.success) { - callbacks.success(data); - } - }, - failure: callbacks && callbacks.failure - }); - } + AWSClient.prototype._translateQueue = function (queue) { + return { + queueARN: queue.queueARN, + name: queue.name + }; }; - - Agent.prototype.setState = function (state, callbacks, options) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.PUT_AGENT_STATE, { - state: connect.assertNotNull(state, 'state'), - enqueueNextState: options && !!options.enqueueNextState - }, callbacks); + AWSClient.prototype._translateSoftphoneStreamStatistics = function (stats) { + stats.forEach(function (stat) { + if ('packetsCount' in stat) { + stat.packetCount = stat.packetsCount; + delete stat.packetsCount; + } + }); + return stats; }; - Agent.prototype.onEnqueuedNextState = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE, f); + AWSClient.prototype._translateSoftphoneCallReport = function (report) { + if ('handshakingTimeMillis' in report) { + report.handshakeTimeMillis = report.handshakingTimeMillis; + delete report.handshakingTimeMillis; + } + if ('preTalkingTimeMillis' in report) { + report.preTalkTimeMillis = report.preTalkingTimeMillis; + delete report.preTalkingTimeMillis; + } + if ('handshakingFailure' in report) { + report.handshakeFailure = report.handshakingFailure; + delete report.handshakingFailure; + } + if ('talkingTimeMillis' in report) { + report.talkTimeMillis = report.talkingTimeMillis; + delete report.talkingTimeMillis; + } + report.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(report.softphoneStreamStatistics); + return report; }; + connect.ClientBase = ClientBase; + connect.NullClient = NullClient; + connect.UpstreamConduitClient = UpstreamConduitClient; + connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; + connect.AWSClient = AWSClient; + connect.AgentAppClient = AgentAppClient; +})(); - Agent.prototype.setStatus = Agent.prototype.setState; +/***/ }), - Agent.prototype.connect = function (endpointIn, params) { - var client = connect.core.getClient(); - var endpoint = new connect.Endpoint(endpointIn); - // Have to remove the endpointId field or AWS JS SDK gets mad. - delete endpoint.endpointId; +/***/ 531: +/***/ (() => { - client.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT, { - endpoint: connect.assertNotNull(endpoint, 'endpoint'), - queueARN: (params && (params.queueARN || params.queueId)) || this.getRoutingProfile().defaultOutboundQueue.queueARN - }, params && { - success: params.success, - failure: params.failure - }); - }; +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + connect.core = {}; + connect.core.initialized = false; + connect.version = "1.7.6"; + connect.DEFAULT_BATCH_SIZE = 500; + var CCP_SYN_TIMEOUT = 1000; // 1 sec + var CCP_ACK_TIMEOUT = 3000; // 3 sec + var CCP_LOAD_TIMEOUT = 5000; // 5 sec + var CCP_IFRAME_REFRESH_INTERVAL = 5000; // 5 sec - Agent.prototype.getAllQueueARNs = function () { - return this.getConfiguration().routingProfile.queues.map(function (queue) { - return queue.queueARN; - }); + var LEGACY_LOGIN_URL_PATTERN = "https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}"; + var CLIENT_ID_MAP = { + "us-east-1": "06919f4fd8ed324e" }; + var AUTHORIZE_ENDPOINT = "/auth/authorize"; + var LEGACY_AUTHORIZE_ENDPOINT = "/connect/auth/authorize"; + var AUTHORIZE_RETRY_INTERVAL = 2000; + var AUTHORIZE_MAX_RETRY = 5; + var LEGACY_WHITELISTED_ORIGINS_ENDPOINT = "/connect/whitelisted-origins"; + var WHITELISTED_ORIGINS_ENDPOINT = "/whitelisted-origins"; + var WHITELISTED_ORIGINS_RETRY_INTERVAL = 2000; + var WHITELISTED_ORIGINS_MAX_RETRY = 5; + connect.numberOfConnectedCCPs = 0; + var CCP_IFRAME_NAME = 'Amazon Connect CCP'; - Agent.prototype.getEndpoints = function (queueARNs, callbacks, pageInfoIn) { - var self = this; - var client = connect.core.getClient(); - connect.assertNotNull(callbacks, "callbacks"); - connect.assertNotNull(callbacks.success, "callbacks.success"); - var pageInfo = pageInfoIn || { }; - - pageInfo.endpoints = pageInfo.endpoints || []; - pageInfo.maxResults = pageInfo.maxResults || connect.DEFAULT_BATCH_SIZE; - - // Backwards compatibility allowing a single queueARN to be specified - // instead of an array. - if (!connect.isArray(queueARNs)) { - queueARNs = [queueARNs]; + /** + * @deprecated + * This function was only meant for internal use. + * The name is misleading for what it should do. + * Internally we have replaced its usage with `getLoginUrl`. + */ + var createLoginUrl = function createLoginUrl(params) { + var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; + connect.assertNotNull(redirect); + if (params.loginUrl) { + return params.loginUrl; + } else if (params.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."); + return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); + } else { + return params.ccpUrl; } + }; - client.call(connect.ClientMethods.GET_ENDPOINTS, { - queueARNs: queueARNs, - nextToken: pageInfo.nextToken || null, - maxResults: pageInfo.maxResults - }, { - success: function (data) { - if (data.nextToken) { - self.getEndpoints(queueARNs, callbacks, { - nextToken: data.nextToken, - maxResults: pageInfo.maxResults, - endpoints: pageInfo.endpoints.concat(data.endpoints) - }); - } else { - pageInfo.endpoints = pageInfo.endpoints.concat(data.endpoints); - var endpoints = pageInfo.endpoints.map(function (endpoint) { - return new connect.Endpoint(endpoint); - }); - - callbacks.success({ - endpoints: endpoints, - addresses: endpoints - }); - } - }, - failure: callbacks.failure - }); + /** + * Replaces `createLoginUrl`, as that function's name was misleading. + * The `params.alias` parameter is deprecated. Please refrain from using it. + */ + var getLoginUrl = function getLoginUrl(params) { + var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; + connect.assertNotNull(redirect); + if (params.loginUrl) { + return params.loginUrl; + } else if (params.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."); + return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); + } else { + return params.ccpUrl; + } }; - Agent.prototype.getAddresses = Agent.prototype.getEndpoints; + /**------------------------------------------------------------------------- + * Returns scheme://host:port for a given url + */ + function sanitizeDomain(url) { + var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/ig); + return domain.length ? domain[0] : ""; + } - //Internal identifier. - Agent.prototype._getResourceId = function() { - queueArns = this.getAllQueueARNs(); - for (let queueArn of queueArns) { - const agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); - - if (agentIdMatch) { - return agentIdMatch[1]; - } + /**------------------------------------------------------------------------- + * Print a warning message if the Connect core is not initialized. + */ + connect.core.checkNotInitialized = function () { + if (connect.core.initialized) { + var log = connect.getLog(); + log.warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer(); } - return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ", queueArns); - } + }; - Agent.prototype.toSnapshot = function () { - return new connect.AgentSnapshot(this._getData()); + /**------------------------------------------------------------------------- + * Basic Connect client initialization. + * Should be used only by the API Shared Worker. + */ + connect.core.init = function (params) { + connect.core.eventBus = new connect.EventBus(); + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); + connect.core.initClient(params); + connect.core.initAgentAppClient(params); + connect.core.initialized = true; }; - /*---------------------------------------------------------------- - * class AgentSnapshot + /**------------------------------------------------------------------------- + * Initialized AWS client + * Should be used by Shared Worker to update AWS client with new credentials + * after refreshed authentication. */ - var AgentSnapshot = function (agentData) { - connect.Agent.call(this); - this.agentData = agentData; + connect.core.initClient = function (params) { + connect.assertNotNull(params, 'params'); + var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); + var region = connect.assertNotNull(params.region, 'params.region'); + var endpoint = params.endpoint || null; + connect.core.client = new connect.AWSClient(authToken, region, endpoint); }; - AgentSnapshot.prototype = Object.create(Agent.prototype); - AgentSnapshot.prototype.constructor = AgentSnapshot; - AgentSnapshot.prototype._getData = function () { - return this.agentData; + /**------------------------------------------------------------------------- + * Initialized AgentApp client + * Should be used by Shared Worker to update AgentApp client with new credentials + * after refreshed authentication. + */ + connect.core.initAgentAppClient = function (params) { + connect.assertNotNull(params, 'params'); + var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); + var authCookieName = connect.assertNotNull(params.authCookieName, 'params.authCookieName'); + var endpoint = connect.assertNotNull(params.agentAppEndpoint, 'params.agentAppEndpoint'); + connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); }; - AgentSnapshot.prototype._createContactAPI = function (contactData) { - return new connect.ContactSnapshot(contactData); + /**------------------------------------------------------------------------- + * Uninitialize Connect. + */ + connect.core.terminate = function () { + connect.core.client = new connect.NullClient(); + connect.core.agentAppClient = new connect.NullClient(); + connect.core.masterClient = new connect.NullClient(); + var bus = connect.core.getEventBus(); + if (bus) bus.unsubscribeAll(); + connect.core.bus = new connect.EventBus(); + connect.core.agentDataProvider = null; + connect.core.softphoneManager = null; + connect.core.upstream = null; + connect.core.keepaliveManager = null; + connect.agent.initialized = false; + connect.core.initialized = false; }; - /*---------------------------------------------------------------- - * class Contact + /**------------------------------------------------------------------------- + * Setup the SoftphoneManager to be initialized when the agent + * is determined to have softphone enabled. */ - var Contact = function (contactId) { - this.contactId = contactId; + connect.core.softphoneUserMediaStream = null; + connect.core.getSoftphoneUserMediaStream = function () { + return connect.core.softphoneUserMediaStream; + }; + connect.core.setSoftphoneUserMediaStream = function (stream) { + connect.core.softphoneUserMediaStream = stream; }; + connect.core.initRingtoneEngines = function (params) { + connect.assertNotNull(params, "params"); + var setupRingtoneEngines = function setupRingtoneEngines(ringtoneSettings) { + connect.assertNotNull(ringtoneSettings, "ringtoneSettings"); + connect.assertNotNull(ringtoneSettings.voice, "ringtoneSettings.voice"); + connect.assertTrue(ringtoneSettings.voice.ringtoneUrl || ringtoneSettings.voice.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"); + connect.assertNotNull(ringtoneSettings.queue_callback, "ringtoneSettings.queue_callback"); + connect.assertTrue(ringtoneSettings.queue_callback.ringtoneUrl || ringtoneSettings.queue_callback.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"); + connect.core.ringtoneEngines = {}; + connect.agent(function (agent) { + agent.onRefresh(function () { + connect.ifMaster(connect.MasterTopics.RINGTONE, function () { + if (!ringtoneSettings.voice.disabled && !connect.core.ringtoneEngines.voice) { + connect.core.ringtoneEngines.voice = new connect.VoiceRingtoneEngine(ringtoneSettings.voice); + connect.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer(); + } + if (!ringtoneSettings.chat.disabled && !connect.core.ringtoneEngines.chat) { + connect.core.ringtoneEngines.chat = new connect.ChatRingtoneEngine(ringtoneSettings.chat); + connect.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer(); + } + if (!ringtoneSettings.task.disabled && !connect.core.ringtoneEngines.task) { + connect.core.ringtoneEngines.task = new connect.TaskRingtoneEngine(ringtoneSettings.task); + connect.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer(); + } + if (!ringtoneSettings.queue_callback.disabled && !connect.core.ringtoneEngines.queue_callback) { + connect.core.ringtoneEngines.queue_callback = new connect.QueueCallbackRingtoneEngine(ringtoneSettings.queue_callback); + connect.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer(); + } + }); + }); + }); + handleRingerDeviceChange(); + }; + var mergeParams = function mergeParams(params, otherParams) { + // For backwards compatibility: support pulling disabled flag and ringtoneUrl + // from softphone config if it exists from downstream into the ringtone config. + params.ringtone = params.ringtone || {}; + params.ringtone.voice = params.ringtone.voice || {}; + params.ringtone.queue_callback = params.ringtone.queue_callback || {}; + params.ringtone.chat = params.ringtone.chat || { + disabled: true + }; + params.ringtone.task = params.ringtone.task || { + disabled: true + }; + if (otherParams.softphone) { + if (otherParams.softphone.disableRingtone) { + params.ringtone.voice.disabled = true; + params.ringtone.queue_callback.disabled = true; + } + if (otherParams.softphone.ringtoneUrl) { + params.ringtone.voice.ringtoneUrl = otherParams.softphone.ringtoneUrl; + params.ringtone.queue_callback.ringtoneUrl = otherParams.softphone.ringtoneUrl; + } + } + if (otherParams.chat) { + if (otherParams.chat.disableRingtone) { + params.ringtone.chat.disabled = true; + } + if (otherParams.chat.ringtoneUrl) { + params.ringtone.chat.ringtoneUrl = otherParams.chat.ringtoneUrl; + } + } - Contact.prototype._getData = function () { - return connect.core.getAgentDataProvider().getContactData(this.getContactId()); - }; + // Merge in ringtone settings from downstream. + if (otherParams.ringtone) { + params.ringtone.voice = connect.merge(params.ringtone.voice, otherParams.ringtone.voice || {}); + params.ringtone.queue_callback = connect.merge(params.ringtone.queue_callback, otherParams.ringtone.voice || {}); + params.ringtone.chat = connect.merge(params.ringtone.chat, otherParams.ringtone.chat || {}); + } + }; - Contact.prototype._createConnectionAPI = function (connectionData) { - if (this.getType() === connect.ContactType.CHAT) { - return new connect.ChatConnection(this.contactId, connectionData.connectionId); - } else if (this.getType() === connect.ContactType.TASK) { - return new connect.TaskConnection(this.contactId, connectionData.connectionId); + // Merge params from params.softphone and params.chat into params.ringtone + // for embedded and non-embedded use cases so that defaults are picked up. + mergeParams(params, params); + if (connect.isFramed()) { + // If the CCP is in a frame, wait for configuration from downstream. + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.CONFIGURE, function (data) { + this.unsubscribe(); + // Merge all params from data into params for any overridden + // values in either legacy "softphone" or "ringtone" settings. + mergeParams(params, data); + setupRingtoneEngines(params.ringtone); + }); } else { - return new connect.VoiceConnection(this.contactId, connectionData.connectionId); + setupRingtoneEngines(params.ringtone); } }; - - Contact.prototype.getEventName = function (eventName) { - return connect.core.getContactEventName(eventName, this.getContactId()); - }; - - Contact.prototype.onRefresh = function (f) { + var handleRingerDeviceChange = function handleRingerDeviceChange() { var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.REFRESH), f); + bus.subscribe(connect.ConfigurationEvents.SET_RINGER_DEVICE, setRingerDevice); }; - - Contact.prototype.onIncoming = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.INCOMING), f); + var setRingerDevice = function setRingerDevice(data) { + if (connect.keys(connect.core.ringtoneEngines).length === 0 || !data || !data.deviceId) { + return; + } + var deviceId = data.deviceId; + for (var ringtoneType in connect.core.ringtoneEngines) { + connect.core.ringtoneEngines[ringtoneType].setOutputDevice(deviceId); + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, + data: { + deviceId: deviceId + } + }); }; + connect.core.initSoftphoneManager = function (paramsIn) { + connect.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer(); + var params = paramsIn || {}; + var competeForMasterOnAgentUpdate = function competeForMasterOnAgentUpdate(softphoneParamsIn) { + var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); + connect.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(); + connect.agent(function (agent) { + if (!agent.getChannelConcurrency(connect.ChannelType.VOICE)) { + return; + } + agent.onRefresh(function () { + var sub = this; + connect.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(); + connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { + connect.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(); + if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { + // Become master to send logs, since we need logs from softphone tab. + connect.becomeMaster(connect.MasterTopics.SEND_LOGS); + connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); + sub.unsubscribe(); + } + }); + }); + }); + }; - Contact.prototype.onConnecting = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTING), f); - }; + /** + * If the window is framed, we need to wait for a CONFIGURE message from + * downstream before we try to initialize, unless params.allowFramedSoftphone is true. + */ + if (connect.isFramed() && !params.allowFramedSoftphone) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.CONFIGURE, function (data) { + connect.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(); + if (data.softphone && data.softphone.allowFramedSoftphone) { + this.unsubscribe(); + competeForMasterOnAgentUpdate(data.softphone); + } + setupEventListenersForMultiTabUseInFirefox(data.softphone); + }); + } else { + competeForMasterOnAgentUpdate(params); + setupEventListenersForMultiTabUseInFirefox(params); + } + connect.agent(function (agent) { + // Sync mute across all tabs + if (agent.isSoftphoneEnabled() && agent.getChannelConcurrency(connect.ChannelType.VOICE)) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.MUTE + }); + } + }); + function setupEventListenersForMultiTabUseInFirefox(softphoneParamsIn) { + var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); - Contact.prototype.onPending = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.PENDING), f); - }; + // keep the softphone params for external use + connect.core.softphoneParams = softphoneParams; + if (connect.isFirefoxBrowser()) { + // In Firefox, when a tab takes over another tab's softphone primary, + // the previous primary tab should delete sofphone manager and stop microphone + connect.core.getUpstream().onUpstream(connect.EventType.MASTER_RESPONSE, function (res) { + if (res.data && res.data.topic === connect.MasterTopics.SOFTPHONE && res.data.takeOver && res.data.masterId !== connect.core.portStreamId) { + if (connect.core.softphoneManager) { + connect.core.softphoneManager.onInitContactSub.unsubscribe(); + delete connect.core.softphoneManager; + } + var userMediaStream = connect.core.getSoftphoneUserMediaStream(); + if (userMediaStream) { + userMediaStream.getTracks().forEach(function (track) { + track.stop(); + }); + connect.core.setSoftphoneUserMediaStream(null); + } + } + }); - Contact.prototype.onAccepted = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ACCEPTED), f); - }; + // In Firefox, when multiple tabs are open, + // webrtc session is not started until READY_TO_START_SESSION event is triggered + connect.core.getEventBus().subscribe(connect.ConnectionEvents.READY_TO_START_SESSION, function () { + connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { + if (connect.core.softphoneManager) { + connect.core.softphoneManager.startSession(); + } + }, function () { + connect.becomeMaster(connect.MasterTopics.SOFTPHONE, function () { + connect.agent(function (agent) { + if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { + connect.becomeMaster(connect.MasterTopics.SEND_LOGS); + connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); + connect.core.softphoneManager.startSession(); + } + }); + }); + }); + }); - Contact.prototype.onMissed = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.MISSED), f); + // handling outbound-call and auto-accept cases for pending session + connect.contact(function (c) { + connect.agent(function (agent) { + c.onRefresh(function (contact) { + if (connect.hasOtherConnectedCCPs() && document.visibilityState === 'visible' && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { + var isOutBoundCall = contact.isSoftphoneCall() && !contact.isInbound(); + var isAutoAcceptEnabled = contact.isSoftphoneCall() && agent.getConfiguration().softphoneAutoAccept; + var isQueuedCallback = contact.getType() === connect.ContactType.QUEUE_CALLBACK; + if (isOutBoundCall || isAutoAcceptEnabled || isQueuedCallback) { + connect.core.triggerReadyToStartSessionEvent(); + } + } + }); + }); + }); + } + } }; - Contact.prototype.onEnded = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ENDED), f); - bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); + // trigger READY_TO_START_SESSION event in a context with Softphone Manager + // internal use only + connect.core.triggerReadyToStartSessionEvent = function () { + var allowFramedSoftphone = connect.core.softphoneParams && connect.core.softphoneParams.allowFramedSoftphone; + if (connect.isCCP()) { + if (allowFramedSoftphone) { + // the event is triggered in this iframed CCP context + connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); + } else { + if (connect.isFramed()) { + // if this is an iframed CCP, the event is send to downstream (CRM) + connect.core.getUpstream().sendDownstream(connect.ConnectionEvents.READY_TO_START_SESSION); + } else { + // if this is a standalone CCP, trigger this event in this CCP context + connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); + } + } + } else { + if (allowFramedSoftphone) { + // the event is send to the upstream (iframed CCP) + connect.core.getUpstream().sendUpstream(connect.ConnectionEvents.READY_TO_START_SESSION); + } else { + // the event is triggered in this CRM context + connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); + } + } }; - - Contact.prototype.onDestroy = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); + connect.core.initPageOptions = function (params) { + connect.assertNotNull(params, "params"); + if (connect.isFramed()) { + // If the CCP is in a frame, wait for configuration from downstream. + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.CONFIGURE, function (data) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.CONFIGURE, + data: data + }); + }); + // Listen for iframe media devices request from CRM + bus.subscribe(connect.EventType.MEDIA_DEVICE_REQUEST, function () { + function sendDevices(devices) { + connect.core.getUpstream().sendDownstream(connect.EventType.MEDIA_DEVICE_RESPONSE, devices); + } + if (navigator && navigator.mediaDevices) { + navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { + devices = devicesIn || []; + devices = devices.map(function (d) { + return d.toJSON(); + }); + sendDevices(devices); + })["catch"](function (err) { + sendDevices({ + error: err.message + }); + }); + } else { + sendDevices({ + error: "No navigator or navigator.mediaDevices object found" + }); + } + }); + } }; - Contact.prototype.onACW = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ACW), f); + /**------------------------------------------------------------------------- + * Get the list of media devices from iframed CCP + * Timeout for the request is passed an an optional argument + * The default timeout is 1000ms + */ + connect.core.getFrameMediaDevices = function (timeoutIn) { + var sub = null; + var timeout = timeoutIn || 1000; + var timeoutPromise = new Promise(function (resolve, reject) { + setTimeout(function () { + reject(new Error("Timeout exceeded")); + }, timeout); + }); + var mediaDevicesPromise = new Promise(function (resolve, reject) { + if (connect.isFramed() || connect.isCCP()) { + if (navigator && navigator.mediaDevices) { + navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { + devices = devicesIn || []; + devices = devices.map(function (d) { + return d.toJSON(); + }); + resolve(devices); + }); + } else { + reject(new Error("No navigator or navigator.mediaDevices object found")); + } + } else { + var bus = connect.core.getEventBus(); + sub = bus.subscribe(connect.EventType.MEDIA_DEVICE_RESPONSE, function (data) { + if (data.error) { + reject(new Error(data.error)); + } else { + resolve(data); + } + }); + connect.core.getUpstream().sendUpstream(connect.EventType.MEDIA_DEVICE_REQUEST); + } + }); + return Promise.race([mediaDevicesPromise, timeoutPromise])["finally"](function () { + if (sub) { + sub.unsubscribe(); + } + }); }; - Contact.prototype.onConnected = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTED), f); + //Internal use only. + connect.core.authorize = function (endpoint) { + var options = { + credentials: 'include' + }; + var authorizeEndpoint = endpoint; + if (!authorizeEndpoint) { + authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; + } + return connect.fetch(authorizeEndpoint, options, AUTHORIZE_RETRY_INTERVAL, AUTHORIZE_MAX_RETRY); }; - Contact.prototype.onError = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ERROR), f); - } - - Contact.prototype.getContactId = function () { - return this.contactId; + /** + * @deprecated + * This used to be used internally, but is no longer needed. + */ + connect.core.verifyDomainAccess = function (authToken, endpoint) { + connect.getLog().warn("This API will be deprecated in the next major version release"); + if (!connect.isFramed()) { + return Promise.resolve(); + } + var options = { + headers: { + 'X-Amz-Bearer': authToken + } + }; + var whitelistedOriginsEndpoint = null; + if (endpoint) { + whitelistedOriginsEndpoint = endpoint; + } else { + whitelistedOriginsEndpoint = connect.core.isLegacyDomain() ? LEGACY_WHITELISTED_ORIGINS_ENDPOINT : WHITELISTED_ORIGINS_ENDPOINT; + } + return connect.fetch(whitelistedOriginsEndpoint, options, WHITELISTED_ORIGINS_RETRY_INTERVAL, WHITELISTED_ORIGINS_MAX_RETRY).then(function (response) { + var topDomain = sanitizeDomain(window.document.referrer); + var isAllowed = response.whitelistedOrigins.some(function (origin) { + return topDomain === sanitizeDomain(origin); + }); + return isAllowed ? Promise.resolve() : Promise.reject(); + }); }; - Contact.prototype.getOriginalContactId = function () { - return this._getData().initialContactId; + /**------------------------------------------------------------------------- + * Returns true if this window's href is on the legacy connect domain. + * Only useful for internal use. + */ + connect.core.isLegacyDomain = function (url) { + url = url || window.location.href; + return url.includes('.awsapps.com'); }; - Contact.prototype.getInitialContactId = Contact.prototype.getOriginalContactId; - Contact.prototype.getType = function () { - return this._getData().type; - }; + /**------------------------------------------------------------------------- + * Initializes Connect by creating or connecting to the API Shared Worker. + * Used only by the CCP + */ + connect.core.initSharedWorker = function (params) { + connect.core.checkNotInitialized(); + if (connect.core.initialized) { + return; + } + connect.assertNotNull(params, 'params'); + var sharedWorkerUrl = connect.assertNotNull(params.sharedWorkerUrl, 'params.sharedWorkerUrl'); + var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); + var refreshToken = connect.assertNotNull(params.refreshToken, 'params.refreshToken'); + var authTokenExpiration = connect.assertNotNull(params.authTokenExpiration, 'params.authTokenExpiration'); + var region = connect.assertNotNull(params.region, 'params.region'); + var endpoint = params.endpoint || null; + var authorizeEndpoint = params.authorizeEndpoint; + if (!authorizeEndpoint) { + authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; + } + var agentAppEndpoint = params.agentAppEndpoint || null; + var authCookieName = params.authCookieName || null; + try { + // Initialize the event bus and agent data providers. + connect.core.eventBus = new connect.EventBus({ + logEvents: true + }); + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); + connect.core.mediaFactory = new connect.MediaFactory(params); - Contact.prototype.getContactDuration = function() { - return this._getData().contactDuration; - } + // Create the shared worker and upstream conduit. + var worker = new SharedWorker(sharedWorkerUrl, "ConnectSharedWorker"); + var conduit = new connect.Conduit("ConnectSharedWorkerConduit", new connect.PortStream(worker.port), new connect.WindowIOStream(window, parent)); - Contact.prototype.getState = function () { - return this._getData().state; - }; + // Set the global upstream conduit for external use. + connect.core.upstream = conduit; + connect.core.webSocketProvider = new WebSocketProvider(); - Contact.prototype.getStatus = Contact.prototype.getState; + // Close our port to the shared worker before the window closes. + global.onunload = function () { + conduit.sendUpstream(connect.EventType.CLOSE); + worker.port.close(); + }; + connect.getLog().scheduleUpstreamLogPush(conduit); + connect.getLog().scheduleDownstreamClientSideLogsPush(); + // Bridge all upstream messages into the event bus. + conduit.onAllUpstream(connect.core.getEventBus().bridge()); + // Pass all upstream messages (from shared worker) downstream (to CCP consumer). + conduit.onAllUpstream(conduit.passDownstream()); + if (connect.isFramed()) { + // Bridge all downstream messages into the event bus. + conduit.onAllDownstream(connect.core.getEventBus().bridge()); + // 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, + authTokenExpiration: authTokenExpiration, + endpoint: endpoint, + refreshToken: refreshToken, + region: region, + authorizeEndpoint: authorizeEndpoint, + agentAppEndpoint: agentAppEndpoint, + authCookieName: authCookieName + }); + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { + connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); + connect.core.initialized = true; + connect.core.portStreamId = data.id; + this.unsubscribe(); + }); + // Add all upstream log entries to our own logger. + conduit.onUpstream(connect.EventType.LOG, function (logEntry) { + if (logEntry.loggerId !== connect.getLog().getLoggerId()) { + connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + } + }); + // Get worker logs + conduit.onUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logEntry) { + connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(logEntry)); + }); + // Get outer context logs + conduit.onDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logs) { + if (connect.isFramed() && Array.isArray(logs)) { + logs.forEach(function (log) { + connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(log)); + }); + } + }); + // Get log from outer context + conduit.onDownstream(connect.EventType.LOG, function (log) { + if (connect.isFramed() && log.loggerId !== connect.getLog().getLoggerId()) { + 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.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); + connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); + connect.getLog().info("isFramed: " + connect.isFramed()).sendInternalLogToServer(); + connect.core.upstream.onDownstream(connect.EventType.OUTER_CONTEXT_INFO, function (data) { + var streamsVersion = data.streamsVersion; + connect.getLog().info("StreamsJS Version: " + streamsVersion).sendInternalLogToServer(); + }); + conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { + connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); + connect.numberOfConnectedCCPs = data.length; + }); + connect.core.client = new connect.UpstreamConduitClient(conduit); + connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); - Contact.prototype.getStateDuration = function () { - return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); - }; + // Pass the TERMINATE request upstream to the shared worker. + connect.core.getEventBus().subscribe(connect.EventType.TERMINATE, conduit.passUpstream()); - Contact.prototype.getStatusDuration = Contact.prototype.getStateDuration; + // Refresh the page when we receive the TERMINATED response from the + // shared worker. + connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, function () { + window.location.reload(true); + }); + worker.port.start(); + conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { + if (data && data.domainId) { + connect.core.voiceIdDomainId = data.domainId; + } + }); - Contact.prototype.getQueue = function () { - return this._getData().queue; - }; + // try fetching voiceId's domainId once the agent is initialized + connect.agent(function () { + var voiceId = new connect.VoiceId(); + voiceId.getDomainId().then(function (domainId) { + connect.getLog().info("voiceId domainId successfully fetched at agent initialization: " + domainId).sendInternalLogToServer(); + })["catch"](function (err) { + connect.getLog().info("voiceId domainId not fetched at agent initialization").withObject({ + err: err + }).sendInternalLogToServer(); + }); + }); - Contact.prototype.getQueueTimestamp = function () { - return this._getData().queueTimestamp; + // Attempt to get permission to show notifications. + var nm = connect.core.getNotificationManager(); + nm.requestPermission(); + } catch (e) { + connect.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer(); + } }; - - Contact.prototype.getConnections = function () { - var self = this; - return this._getData().connections.map(function (connData) { - if (self.getType() === connect.ContactType.CHAT) { - return new connect.ChatConnection(self.contactId, connData.connectionId); - } else if (self.getType() === connect.ContactType.TASK) { - return new connect.TaskConnection(self.contactId, connData.connectionId); - } else { - return new connect.VoiceConnection(self.contactId, connData.connectionId); + connect.core._getCCPIframe = function () { + var _iterator = _createForOfIteratorHelper(window.document.getElementsByTagName('iframe')), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var iframe = _step.value; + if (iframe.name === CCP_IFRAME_NAME) { + return iframe; + } } - }); - }; - - Contact.prototype.getInitialConnection = function () { - return connect.find(this.getConnections(), function (conn) { - return conn.isInitialConnection(); - }) || null; + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return null; }; - Contact.prototype.getActiveInitialConnection = function () { - var initialConn = this.getInitialConnection(); - if (initialConn != null && initialConn.isActive()) { - return initialConn; - } else { - return null; + /**------------------------------------------------------------------------- + * Initializes Connect by creating or connecting to the API Shared Worker. + * Initializes Connect by loading the CCP in an iframe and connecting to it. + */ + connect.core.initCCP = function (containerDiv, paramsIn) { + connect.core.checkNotInitialized(); + if (connect.core.initialized) { + return; } - }; - Contact.prototype.getThirdPartyConnections = function () { - return this.getConnections().filter(function (conn) { - return !conn.isInitialConnection() && conn.getType() !== connect.ConnectionType.AGENT; - }); - }; + // For backwards compatibility, when instead of taking a params object + // as input we only accepted ccpUrl. + var params = {}; + if (typeof paramsIn === 'string') { + params.ccpUrl = paramsIn; + } else { + params = paramsIn; + } + connect.assertNotNull(containerDiv, 'containerDiv'); + connect.assertNotNull(params.ccpUrl, 'params.ccpUrl'); + connect.storageAccess.init(params.ccpUrl, containerDiv, params.storageAccess || {}); - Contact.prototype.getSingleActiveThirdPartyConnection = function () { - return this.getThirdPartyConnections().filter(function (conn) { - return conn.isActive(); - })[0] || null; - }; + // Create the CCP iframe and append it to the container div. + var iframe = document.createElement('iframe'); + iframe.src = params.ccpUrl; + iframe.allow = "microphone; autoplay"; + iframe.style = "width: 100%; height: 100%"; + iframe.title = 'Amazon Connect CCP'; + iframe.name = CCP_IFRAME_NAME; - Contact.prototype.getAgentConnection = function () { - return connect.find(this.getConnections(), function (conn) { - var connType = conn.getType(); - return connType === connect.ConnectionType.AGENT || connType === connect.ConnectionType.MONITORING; - }); - }; + //for Storage Access follow the rsa path + if (connect.storageAccess.canRequest()) { + iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); + iframe.addEventListener('load', connect.storageAccess.request); + } + containerDiv.appendChild(iframe); - Contact.prototype.getName = function () { - return this._getData().name; - }; + // Build the upstream conduit communicating with the CCP iframe. + var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); - Contact.prototype.getContactMetadata = function () { - return this._getData().contactMetadata; - } + // Set the global upstream conduit for external use. + connect.core.upstream = conduit; - Contact.prototype.getDescription = function () { - return this._getData().description; - }; + // Initialize the event bus and agent data providers. + // NOTE: Setting logEvents here to FALSE in order to avoid duplicating + // events which are logged in CCP. + connect.core.eventBus = new connect.EventBus({ + logEvents: false + }); + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); + connect.core.mediaFactory = new connect.MediaFactory(params); + if (connect.storageAccess.canRequest()) { + // Create the Iframe and load the RSA banner and append it to the container div. + connect.storageAccess.setupRequestHandlers({ + onGrant: setupInitCCP + }); + } else { + setupInitCCP(); + } + function setupInitCCP() { + // Let CCP know if iframe is visible + iframe.onload = setTimeout(function () { + var style = window.getComputedStyle(iframe, null); + var data = { + display: style.display, + offsetWidth: iframe.offsetWidth, + offsetHeight: iframe.offsetHeight, + clientRectsLength: iframe.getClientRects().length + }; + conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); + }, 10000); - Contact.prototype.getReferences = function () { - return this._getData().references; - }; + // Init webSocketProvider + connect.core.webSocketProvider = new WebSocketProvider(); + conduit.onAllUpstream(connect.core.getEventBus().bridge()); - Contact.prototype.getAttributes = function () { - return this._getData().attributes; - }; + // Initialize the keepalive manager. + connect.core.keepaliveManager = new KeepaliveManager(conduit, connect.core.getEventBus(), params.ccpSynTimeout || CCP_SYN_TIMEOUT, params.ccpAckTimeout || CCP_ACK_TIMEOUT); + connect.core.iframeRefreshInterval = null; - Contact.prototype.getContactFeatures = function () { - return this._getData().contactFeatures; - }; + // Allow 5 sec (default) before receiving the first ACK from the CCP. + connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { + connect.core.ccpLoadTimeoutInstance = null; + connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); + }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); + connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); + connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); - Contact.prototype.isSoftphoneCall = function () { - return connect.find(this.getConnections(), function (conn) { - return conn.getSoftphoneMediaInfo() != null; - }) != null; - }; + // Once we receive the first ACK, setup our upstream API client and establish + // the SYN/ACK refresh flow. + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { + connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); + connect.core.client = new connect.UpstreamConduitClient(conduit); + connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); + connect.core.portStreamId = data.id; + if (params.softphone || params.chat || params.pageOptions) { + // 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 + }); + } + if (connect.core.ccpLoadTimeoutInstance) { + global.clearTimeout(connect.core.ccpLoadTimeoutInstance); + connect.core.ccpLoadTimeoutInstance = null; + } + conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { + streamsVersion: connect.version + }); + connect.core.keepaliveManager.start(); + this.unsubscribe(); + connect.core.initialized = true; + connect.core.getEventBus().trigger(connect.EventType.INIT); + }); - Contact.prototype._isInbound = function () { - var initiationMethod = this._getData().initiationMethod; - return (initiationMethod === connect.ContactInitiationMethod.OUTBOUND) ? false : true; - } + // Add any logs from the upstream to our own logger. + conduit.onUpstream(connect.EventType.LOG, function (logEntry) { + if (logEntry.loggerId !== connect.getLog().getLoggerId()) { + connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + } + }); - Contact.prototype.isInbound = function () { - var conn = this.getInitialConnection(); + // Pop a login page when we encounter an ACK timeout. + connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { + // loginPopup is true by default, only false if explicitly set to false. + if (params.loginPopup !== false) { + try { + var loginUrl = getLoginUrl(params); + connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(); + // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT + if (params.loginUrl) { + connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); + } + connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions); + } catch (e) { + connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer(); + } + } + if (connect.core.iframeRefreshInterval == null) { + connect.core.iframeRefreshInterval = window.setInterval(function () { + if (connect.storageAccess.canRequest()) { + iframe.removeEventListener('load', connect.storageAccess.request); + iframe.addEventListener('load', connect.storageAccess.request); + iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); + } else { + iframe.src = params.ccpUrl; + } + }, CCP_IFRAME_REFRESH_INTERVAL); + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { + this.unsubscribe(); + global.clearInterval(connect.core.iframeRefreshInterval); + connect.core.iframeRefreshInterval = null; + connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); + if ((params.loginPopupAutoClose || params.loginOptions && params.loginOptions.autoClose) && connect.core.loginWindow) { + connect.core.loginWindow.close(); + connect.core.loginWindow = null; + } + }); + } + }); + if (params.onViewContact) { + connect.core.onViewContact(params.onViewContact); + } + conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { + connect.numberOfConnectedCCPs = data.length; + }); + conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { + if (data && data.domainId) { + connect.core.voiceIdDomainId = data.domainId; + } + }); - // We will gradually change checking inbound by relying on contact initiationMethod - if (conn.getMediaType() === connect.MediaType.TASK) { - return this._isInbound(); + // keep the softphone params for external use + connect.core.softphoneParams = params.softphone; } + }; - return conn ? conn.getType() === connect.ConnectionType.INBOUND : false; + /**-----------------------------------------------------------------------*/ + var KeepaliveManager = function KeepaliveManager(conduit, eventBus, synTimeout, ackTimeout) { + this.conduit = conduit; + this.eventBus = eventBus; + this.synTimeout = synTimeout; + this.ackTimeout = ackTimeout; + this.ackTimer = null; + this.synTimer = null; + this.ackSub = null; + }; + KeepaliveManager.prototype.start = function () { + var self = this; + this.conduit.sendUpstream(connect.EventType.SYNCHRONIZE); + this.ackSub = this.conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { + this.unsubscribe(); + global.clearTimeout(self.ackTimer); + self._deferStart(); + }); + this.ackTimer = global.setTimeout(function () { + self.ackSub.unsubscribe(); + self.eventBus.trigger(connect.EventType.ACK_TIMEOUT); + self._deferStart(); + }, this.ackTimeout); }; - Contact.prototype.isConnected = function () { - return this.getStatus().type === connect.ContactStateType.CONNECTED; + //Fixes the keepalivemanager. + KeepaliveManager.prototype._deferStart = function () { + this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); }; - Contact.prototype.accept = function (callbacks) { - var client = connect.core.getClient(); - var self = this; - var contactId = this.getContactId(); - client.call(connect.ClientMethods.ACCEPT_CONTACT, { - contactId: contactId - }, { - success: function (data) { - var conduit = connect.core.getUpstream(); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.ContactEvents.ACCEPTED, - data: new connect.Contact(contactId) - }); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, self.getContactId()), - data: new connect.Contact(contactId) - }); + // For backwards compatibility only, in case customers are using this to start the keepalivemanager for some reason. + KeepaliveManager.prototype.deferStart = function () { + if (this.synTimer == null) { + this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); + } + }; - // In Firefox, there's a browser restriction that an unfocused browser tab is not allowed to access the user's microphone. - // The problem is that the restriction could cause a webrtc session creation timeout error when you get an incoming call while you are not on the primary tab. - // It was hard to workaround the issue especially when you have multiple tabs open because you needed to find the right tab and accept the contact before the timeout. - // To avoid the error, when multiple tabs are open in Firefox, a webrtc session is not immediately created as an incoming softphone contact is detected. - // Instead, it waits until contact.accept() is called on a tab and lets the tab become the new primary tab and start the web rtc session there - // because the tab should be focused at the moment and have access to the user's microphone. - var contact = new connect.Contact(contactId); - if (connect.isFirefoxBrowser() && contact.isSoftphoneCall()) { - connect.core.triggerReadyToStartSessionEvent(); - } + /**-----------------------------------------------------------------------*/ - if (callbacks && callbacks.success) { - callbacks.success(data); - } - }, - failure: callbacks ? callbacks.failure : null + var WebSocketProvider = function WebSocketProvider() { + var callbacks = { + 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() + }; + var invokeCallbacks = function invokeCallbacks(callbacks, response) { + callbacks.forEach(function (callback) { + callback(response); }); + }; + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.INIT_FAILURE, function () { + invokeCallbacks(callbacks.initFailure); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_OPEN, function (response) { + invokeCallbacks(callbacks.connectionOpen, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_CLOSE, function (response) { + invokeCallbacks(callbacks.connectionClose, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_GAIN, function () { + invokeCallbacks(callbacks.connectionGain); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_LOST, function (response) { + invokeCallbacks(callbacks.connectionLost, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, function (response) { + invokeCallbacks(callbacks.subscriptionUpdate, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, function (response) { + invokeCallbacks(callbacks.subscriptionFailure, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.ALL_MESSAGE, function (response) { + invokeCallbacks(callbacks.allMessage, response); + if (callbacks.topic.has(response.topic)) { + invokeCallbacks(callbacks.topic.get(response.topic), response); + } + }); + this.sendMessage = function (webSocketPayload) { + connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SEND, webSocketPayload); + }; + this.onInitFailure = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.initFailure.add(cb); + return function () { + return callbacks.initFailure["delete"](cb); + }; + }; + this.onConnectionOpen = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionOpen.add(cb); + return function () { + return callbacks.connectionOpen["delete"](cb); + }; + }; + this.onConnectionClose = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionClose.add(cb); + return function () { + return callbacks.connectionClose["delete"](cb); + }; + }; + this.onConnectionGain = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionGain.add(cb); + return function () { + return callbacks.connectionGain["delete"](cb); + }; + }; + this.onConnectionLost = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionLost.add(cb); + return function () { + return callbacks.connectionLost["delete"](cb); + }; + }; + this.onSubscriptionUpdate = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.subscriptionUpdate.add(cb); + return function () { + return callbacks.subscriptionUpdate["delete"](cb); + }; + }; + this.onSubscriptionFailure = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.subscriptionFailure.add(cb); + return function () { + return callbacks.subscriptionFailure["delete"](cb); + }; + }; + this.subscribeTopics = function (topics) { + connect.assertNotNull(topics, 'topics'); + connect.assertTrue(connect.isArray(topics), 'topics must be a array'); + connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SUBSCRIBE, topics); + }; + this.onMessage = function (topicName, cb) { + connect.assertNotNull(topicName, 'topicName'); + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + if (callbacks.topic.has(topicName)) { + callbacks.topic.get(topicName).add(cb); + } else { + callbacks.topic.set(topicName, new Set([cb])); + } + return function () { + return callbacks.topic.get(topicName)["delete"](cb); + }; + }; + this.onAllMessage = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.allMessage.add(cb); + return function () { + return callbacks.allMessage["delete"](cb); + }; + }; }; - Contact.prototype.destroy = function () { - connect.getLog().warn("contact.destroy() has been deprecated."); + /**-----------------------------------------------------------------------*/ + var AgentDataProvider = function AgentDataProvider(bus) { + var agentData = null; + this.bus = bus; + this.bus.subscribe(connect.AgentEvents.UPDATE, connect.hitch(this, this.updateAgentData)); }; - - Contact.prototype.reject = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.REJECT_CONTACT, { - contactId: this.getContactId() - }, callbacks); + AgentDataProvider.prototype.updateAgentData = function (agentData) { + var oldAgentData = this.agentData; + this.agentData = agentData; + if (oldAgentData == null) { + connect.agent.initialized = true; + this.bus.trigger(connect.AgentEvents.INIT, new connect.Agent()); + } + this.bus.trigger(connect.AgentEvents.REFRESH, new connect.Agent()); + this._fireAgentUpdateEvents(oldAgentData); }; - - Contact.prototype.complete = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.COMPLETE_CONTACT, { - contactId: this.getContactId() - }, callbacks); + AgentDataProvider.prototype.getAgentData = function () { + if (this.agentData == null) { + throw new connect.StateError('No agent data is available yet!'); + } + return this.agentData; }; - - Contact.prototype.clear = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.CLEAR_CONTACT, { - contactId: this.getContactId() - }, callbacks); + AgentDataProvider.prototype.getContactData = function (contactId) { + var agentData = this.getAgentData(); + var contactData = connect.find(agentData.snapshot.contacts, function (ctdata) { + return ctdata.contactId === contactId; + }); + if (contactData == null) { + throw new connect.StateError('Contact %s no longer exists.', contactId); + } + return contactData; }; - - Contact.prototype.notifyIssue = function (issueCode, description, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE, { - contactId: this.getContactId(), - issueCode: issueCode, - description: description - }, callbacks); + AgentDataProvider.prototype.getConnectionData = function (contactId, connectionId) { + var contactData = this.getContactData(contactId); + var connectionData = connect.find(contactData.connections, function (cdata) { + return cdata.connectionId === connectionId; + }); + if (connectionData == null) { + throw new connect.StateError('Connection %s for contact %s no longer exists.', connectionId, contactId); + } + return connectionData; }; - - Contact.prototype.addConnection = function (endpointIn, callbacks) { - var client = connect.core.getClient(); - var endpoint = new connect.Endpoint(endpointIn); - // Have to remove the endpointId field or AWS JS SDK gets mad. - delete endpoint.endpointId; - - client.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION, { - contactId: this.getContactId(), - endpoint: endpoint - }, callbacks); + AgentDataProvider.prototype.getInstanceId = function () { + return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]; }; - - Contact.prototype.toggleActiveConnections = function (callbacks) { - var client = connect.core.getClient(); - var connectionId = null; - var holdingConn = connect.find(this.getConnections(), function (conn) { - return conn.getStatus().type === connect.ConnectionStateType.HOLD; + AgentDataProvider.prototype.getAWSAccountId = function () { + return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]; + }; + AgentDataProvider.prototype._diffContacts = function (oldAgentData) { + var diff = { + added: {}, + removed: {}, + common: {}, + oldMap: connect.index(oldAgentData == null ? [] : oldAgentData.snapshot.contacts, function (contact) { + return contact.contactId; + }), + newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { + return contact.contactId; + }) + }; + connect.keys(diff.oldMap).forEach(function (contactId) { + if (connect.contains(diff.newMap, contactId)) { + diff.common[contactId] = diff.newMap[contactId]; + } else { + diff.removed[contactId] = diff.oldMap[contactId]; + } }); - - if (holdingConn != null) { - connectionId = holdingConn.getConnectionId(); - - } else { - var activeConns = this.getConnections().filter(function (conn) { - return conn.isActive(); - }); - if (activeConns.length > 0) { - connectionId = activeConns[0].getConnectionId(); + connect.keys(diff.newMap).forEach(function (contactId) { + if (!connect.contains(diff.oldMap, contactId)) { + diff.added[contactId] = diff.newMap[contactId]; } - } - - client.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS, { - contactId: this.getContactId(), - connectionId: connectionId - }, callbacks); - }; - - Contact.prototype.sendSoftphoneMetrics = function (softphoneStreamStatistics, callbacks) { - var client = connect.core.getClient(); - - client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, { - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - softphoneStreamStatistics: softphoneStreamStatistics - }, callbacks); - - connect.publishSoftphoneStats({ - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - stats: softphoneStreamStatistics }); + return diff; }; - - Contact.prototype.sendSoftphoneReport = function (report, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT, { - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - report: report - }, callbacks); - - connect.publishSoftphoneReport({ - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - report: report + AgentDataProvider.prototype._fireAgentUpdateEvents = function (oldAgentData) { + var self = this; + var diff = null; + var oldAgentState = oldAgentData == null ? connect.AgentAvailStates.INIT : oldAgentData.snapshot.state.name; + var newAgentState = this.agentData.snapshot.state.name; + var oldRoutingState = oldAgentData == null ? connect.AgentStateType.INIT : oldAgentData.snapshot.state.type; + var newRoutingState = this.agentData.snapshot.state.type; + if (oldRoutingState !== newRoutingState) { + connect.core.getAgentRoutingEventGraph().getAssociations(this, oldRoutingState, newRoutingState).forEach(function (event) { + self.bus.trigger(event, new connect.Agent()); + }); + } + if (oldAgentState !== newAgentState) { + this.bus.trigger(connect.AgentEvents.STATE_CHANGE, { + agent: new connect.Agent(), + oldState: oldAgentState, + newState: newAgentState + }); + connect.core.getAgentStateEventGraph().getAssociations(this, oldAgentState, newAgentState).forEach(function (event) { + self.bus.trigger(event, new connect.Agent()); + }); + } + var oldNextState = oldAgentData && oldAgentData.snapshot.nextState ? oldAgentData.snapshot.nextState.name : null; + var newNextState = this.agentData.snapshot.nextState ? this.agentData.snapshot.nextState.name : null; + if (oldNextState !== newNextState && newNextState) { + self.bus.trigger(connect.AgentEvents.ENQUEUED_NEXT_STATE, new connect.Agent()); + } + if (oldAgentData !== null) { + diff = this._diffContacts(oldAgentData); + } else { + diff = { + added: connect.index(this.agentData.snapshot.contacts, function (contact) { + return contact.contactId; + }), + removed: {}, + common: {}, + oldMap: {}, + newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { + return contact.contactId; + }) + }; + } + connect.values(diff.added).forEach(function (contactData) { + self.bus.trigger(connect.ContactEvents.INIT, new connect.Contact(contactData.contactId)); + self._fireContactUpdateEvents(contactData.contactId, connect.ContactStateType.INIT, contactData.state.type); + }); + connect.values(diff.removed).forEach(function (contactData) { + self.bus.trigger(connect.ContactEvents.DESTROYED, new connect.ContactSnapshot(contactData)); + self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.DESTROYED, contactData.contactId), new connect.ContactSnapshot(contactData)); + self._unsubAllContactEventsForContact(contactData.contactId); + }); + connect.keys(diff.common).forEach(function (contactId) { + self._fireContactUpdateEvents(contactId, diff.oldMap[contactId].state.type, diff.newMap[contactId].state.type); }); }; - - Contact.prototype.conferenceConnections = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.CONFERENCE_CONNECTIONS, { - contactId: this.getContactId() - }, callbacks); - }; - - Contact.prototype.toSnapshot = function () { - return new connect.ContactSnapshot(this._getData()); + AgentDataProvider.prototype._fireContactUpdateEvents = function (contactId, oldContactState, newContactState) { + var self = this; + if (oldContactState !== newContactState) { + connect.core.getContactEventGraph().getAssociations(this, oldContactState, newContactState).forEach(function (event) { + self.bus.trigger(event, new connect.Contact(contactId)); + self.bus.trigger(connect.core.getContactEventName(event, contactId), new connect.Contact(contactId)); + }); + } + self.bus.trigger(connect.ContactEvents.REFRESH, new connect.Contact(contactId)); + self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.REFRESH, contactId), new connect.Contact(contactId)); }; - - /*---------------------------------------------------------------- - * class ContactSnapshot - */ - var ContactSnapshot = function (contactData) { - connect.Contact.call(this, contactData.contactId); - this.contactData = contactData; + AgentDataProvider.prototype._unsubAllContactEventsForContact = function (contactId) { + var self = this; + connect.values(connect.ContactEvents).forEach(function (eventName) { + self.bus.getSubscriptions(connect.core.getContactEventName(eventName, contactId)).map(function (sub) { + sub.unsubscribe(); + }); + }); }; - ContactSnapshot.prototype = Object.create(Contact.prototype); - ContactSnapshot.prototype.constructor = ContactSnapshot; - ContactSnapshot.prototype._getData = function () { - return this.contactData; - }; + /** ----- minimal view layer event handling **/ - ContactSnapshot.prototype._createConnectionAPI = function (connectionData) { - return new connect.ConnectionSnapshot(connectionData); + connect.core.onViewContact = function (f) { + connect.core.getUpstream().onUpstream(connect.ContactEvents.VIEW, f); }; - /*---------------------------------------------------------------- - * class Connection + /** + * Used of agent interface control. + * connect.core.viewContact("contactId") -> this is curently programmed to get the contact into view. */ - var Connection = function (contactId, connectionId) { - this.contactId = contactId; - this.connectionId = connectionId; - this._initMediaController(); + connect.core.viewContact = function (contactId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ContactEvents.VIEW, + data: { + contactId: contactId + } + }); }; - Connection.prototype._getData = function () { - return connect.core.getAgentDataProvider().getConnectionData( - this.getContactId(), this.getConnectionId()); - }; + /** ----- minimal view layer event handling **/ - Connection.prototype.getContactId = function () { - return this.contactId; + connect.core.onActivateChannelWithViewType = function (f) { + connect.core.getUpstream().onUpstream(connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, f); }; - Connection.prototype.getConnectionId = function () { - return this.connectionId; + /** + * Used of agent interface control. + * connect.core.activateChannelWithViewType() -> this is curently programmed to get either the number pad, quick connects, or create task into view. + * the valid combinations are ("create_task", "task"), ("number_pad", "softphone"), ("create_task", "softphone"), ("quick_connects", "softphone") + * the softphone with create_task combo is a special case in the channel view to allow all three view type buttons to appear on the softphone screen + * + * The 'source' is an optional parameter which indicates the requester. For example, if invoked with ("create_task", "task", "agentapp") we would know agentapp requested open task view. + */ + connect.core.activateChannelWithViewType = function (viewType, mediaType, source) { + var data = { + viewType: viewType, + mediaType: mediaType + }; + if (source) { + data.source = source; + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, + data: data + }); }; - Connection.prototype.getEndpoint = function () { - return new connect.Endpoint(this._getData().endpoint); + /** + * Used to publish 'task created' event + */ + connect.core.triggerTaskCreated = function (data) { + connect.core.getUpstream().upstreamBus.trigger(connect.TaskEvents.CREATED, data); }; - Connection.prototype.getAddress = Connection.prototype.getEndpoint; + /** ------------------------------------------------- */ - Connection.prototype.getState = function () { - return this._getData().state; + /** + * This will be helpful for the custom and embedded CCPs + * to handle the access denied use case. + */ + connect.core.onAccessDenied = function (f) { + connect.core.getUpstream().onUpstream(connect.EventType.ACCESS_DENIED, f); }; - Connection.prototype.getStatus = Connection.prototype.getState; - - Connection.prototype.getStateDuration = function () { - return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); + /** + * This will be helpful for SAML use cases to handle the custom logins. + */ + connect.core.onAuthFail = function (f) { + connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, f); }; - Connection.prototype.getStatusDuration = Connection.prototype.getStateDuration; + /** ------------------------------------------------- */ - Connection.prototype.getType = function () { - return this._getData().type; - }; + /** + * Used for handling the rtc session stats. + * Usage + * connect.core.onSoftphoneSessionInit(function({ connectionId }) { + * var softphoneManager = connect.core.getSoftphoneManager(); + * if(softphoneManager){ + * // access session + * var session = softphoneManager.getSession(connectionId); + * } + * }); + */ - Connection.prototype.isInitialConnection = function () { - return this._getData().initial; + connect.core.onSoftphoneSessionInit = function (f) { + connect.core.getUpstream().onUpstream(connect.ConnectionEvents.SESSION_INIT, f); }; - Connection.prototype.isActive = function () { - return connect.contains(connect.CONNECTION_ACTIVE_STATES, this.getStatus().type); + /**-----------------------------------------------------------------------*/ + connect.core.onConfigure = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.CONFIGURE, f); }; - Connection.prototype.isConnected = function () { - return this.getStatus().type === connect.ConnectionStateType.CONNECTED; + /**-----------------------------------------------------------------------*/ + connect.core.onInitialized = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.INIT, f); }; - Connection.prototype.isConnecting = function () { - return this.getStatus().type === connect.ConnectionStateType.CONNECTING; + /**-----------------------------------------------------------------------*/ + connect.core.getContactEventName = function (eventName, contactId) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(contactId, 'contactId'); + if (!connect.contains(connect.values(connect.ContactEvents), eventName)) { + throw new connect.ValueError('%s is not a valid contact event.', eventName); + } + return connect.sprintf('%s::%s', eventName, contactId); }; - Connection.prototype.isOnHold = function () { - return this.getStatus().type === connect.ConnectionStateType.HOLD; + /**-----------------------------------------------------------------------*/ + connect.core.getEventBus = function () { + return connect.core.eventBus; }; - Connection.prototype.getSoftphoneMediaInfo = function () { - return this._getData().softphoneMediaInfo; + /**-----------------------------------------------------------------------*/ + connect.core.getWebSocketManager = function () { + return connect.core.webSocketProvider; }; - /** - * Gets the currently monitored contact info, Returns null if does not exists. - * @return {{agentName:string, customerName:string, joinTime:Date}} - */ - Connection.prototype.getMonitorInfo = function () { - return this._getData().monitoringInfo; + /**-----------------------------------------------------------------------*/ + connect.core.getAgentDataProvider = function () { + return connect.core.agentDataProvider; }; - Connection.prototype.destroy = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.DESTROY_CONNECTION, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); + /**-----------------------------------------------------------------------*/ + connect.core.getLocalTimestamp = function () { + return connect.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp; }; - Connection.prototype.sendDigits = function (digits, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.SEND_DIGITS, { - contactId: this.getContactId(), - connectionId: this.getConnectionId(), - digits: digits - }, callbacks); + /**-----------------------------------------------------------------------*/ + connect.core.getSkew = function () { + return connect.core.getAgentDataProvider().getAgentData().snapshot.skew; }; - Connection.prototype.hold = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.HOLD_CONNECTION, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); + /**-----------------------------------------------------------------------*/ + connect.core.getAgentRoutingEventGraph = function () { + return connect.core.agentRoutingEventGraph; }; + connect.core.agentRoutingEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.AgentStateType.ROUTABLE, connect.AgentEvents.ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.NOT_ROUTABLE, connect.AgentEvents.NOT_ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.OFFLINE, connect.AgentEvents.OFFLINE); - Connection.prototype.resume = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.RESUME_CONNECTION, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); + /**-----------------------------------------------------------------------*/ + connect.core.getAgentStateEventGraph = function () { + return connect.core.agentStateEventGraph; }; + connect.core.agentStateEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.AgentEvents.ERROR).assoc(connect.EventGraph.ANY, connect.AgentAvailStates.AFTER_CALL_WORK, connect.AgentEvents.ACW); - Connection.prototype.toSnapshot = function () { - return new connect.ConnectionSnapshot(this._getData()); + /**-----------------------------------------------------------------------*/ + connect.core.getContactEventGraph = function () { + return connect.core.contactEventGraph; }; + connect.core.contactEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.ContactStateType.INCOMING, connect.ContactEvents.INCOMING).assoc(connect.EventGraph.ANY, connect.ContactStateType.PENDING, connect.ContactEvents.PENDING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTING, connect.ContactEvents.CONNECTING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTED, connect.ContactEvents.CONNECTED).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.EventGraph.ANY, connect.ContactStateType.ENDED, connect.ContactEvents.ACW).assoc(connect.values(connect.CONTACT_ACTIVE_STATES), connect.values(connect.relativeComplement(connect.CONTACT_ACTIVE_STATES, connect.ContactStateType)), connect.ContactEvents.ENDED).assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.ContactEvents.ERROR).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.MISSED, connect.ContactEvents.MISSED); - Connection.prototype._initMediaController = function () { - if (this.getMediaInfo()) { - connect.core.mediaFactory.get(this).catch(function () { }); + /**-----------------------------------------------------------------------*/ + connect.core.getClient = function () { + if (!connect.core.client) { + throw new connect.StateError('The connect core has not been initialized!'); } - } - - // Method for checking whether this connection is an agent-side connection - // (type AGENT or MONITORING) - Connection.prototype._isAgentConnectionType = function () { - var connectionType = this.getType(); - return connectionType === connect.ConnectionType.AGENT - || connectionType === connect.ConnectionType.MONITORING; - } - - /** - * Utility method for checking whether this connection is an agent-side connection - * (type AGENT or MONITORING) - * @return {boolean} True if this connection is an agent-side connection. False otherwise. - */ - Connection.prototype._isAgentConnectionType = function () { - var connectionType = this.getType(); - return connectionType === connect.ConnectionType.AGENT - || connectionType === connect.ConnectionType.MONITORING; - } - - /*---------------------------------------------------------------- - * Voice authenticator VoiceId - */ - - var VoiceId = function (contactId) { - this.contactId = contactId; + return connect.core.client; }; + connect.core.client = null; - VoiceId.prototype.getSpeakerId = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.GET_CONTACT, { - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId(), - "awsAccountId": connect.core.getAgentDataProvider().getAWSAccountId() - }, { - success: function (data) { - if(data.contactData.customerId) { - var obj = { - speakerId: data.contactData.customerId - } - connect.getLog().info("getSpeakerId succeeded").withObject(data).sendInternalLogToServer(); - resolve(obj); - } else { - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND, "No speakerId assotiated with this call"); - reject(error); - } - - }, - failure: function (err) { - connect.getLog().error("Get SpeakerId failed") - .withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED, "Get SpeakerId failed", err); - reject(error); - } - }); - }); + /**-----------------------------------------------------------------------*/ + connect.core.getAgentAppClient = function () { + if (!connect.core.agentAppClient) { + throw new connect.StateError('The connect AgentApp Client has not been initialized!'); + } + return connect.core.agentAppClient; }; + connect.core.agentAppClient = null; - VoiceId.prototype.getSpeakerStatus = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function(data){ - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER, { - "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), - "DomainId" : domainId - }, { - success: function (data) { - connect.getLog().info("getSpeakerStatus succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err) { - var error; - var parsedErr = JSON.parse(err); - switch(parsedErr.status) { - case 400: - case 404: - var data = parsedErr; - data.type = data.type ? data.type : connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED; - connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(); - resolve(data); - break; - default: - connect.getLog().error("getSpeakerStatus failed") - .withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED, "Get SpeakerStatus failed", err); - reject(error); - } - } - }); - }).catch(function(err) { - reject(err); - }); - }).catch(function(err){ - reject(err); - }); - }); + /**-----------------------------------------------------------------------*/ + connect.core.getMasterClient = function () { + if (!connect.core.masterClient) { + throw new connect.StateError('The connect master client has not been initialized!'); + } + return connect.core.masterClient; }; + connect.core.masterClient = null; - // internal only - VoiceId.prototype._optOutSpeakerInLcms = function (speakerId) { - var self = this; - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { - "ContactId": self.contactId, - "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), - "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), - "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), - "VoiceIdResult": { - "SpeakerOptedOut": true - } - }, { - success: function (data) { - connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err) { - connect.getLog().error("optOutSpeakerInLcms failed") - .withObject({ - err: err, - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED, "optOutSpeakerInLcms failed", err); - reject(error); - } - }); - }); + /**-----------------------------------------------------------------------*/ + connect.core.getSoftphoneManager = function () { + return connect.core.softphoneManager; }; + connect.core.softphoneManager = null; - VoiceId.prototype.optOutSpeaker = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function(data){ - self.getDomainId().then(function(domainId) { - var speakerId = data.speakerId; - client.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER, { - "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), - "DomainId" : domainId - }, { - success: function (data) { - self._optOutSpeakerInLcms(speakerId).catch(function(){}); - connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err) { - connect.getLog().error("optOutSpeaker failed") - .withObject({ - err: err, - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED, "optOutSpeaker failed.", err); - reject(error); - } - }); - }).catch(function(err) { - reject(err); - }); - }).catch(function(err){ - reject(err); - }); - }); + /**-----------------------------------------------------------------------*/ + connect.core.getNotificationManager = function () { + if (!connect.core.notificationManager) { + connect.core.notificationManager = new connect.NotificationManager(); + } + return connect.core.notificationManager; }; + connect.core.notificationManager = null; - VoiceId.prototype.deleteSpeaker = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function(data){ - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.DELETE_SPEAKER, { - "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), - "DomainId" : domainId - }, { - success: function (data) { - connect.getLog().info("deleteSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err) { - connect.getLog().error("deleteSpeaker failed") - .withObject({ - err: err, - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED, "deleteSpeaker failed.", err); - reject(error); - } - }); - }).catch(function(err) { - reject(err); - }); - }).catch(function(err){ - reject(err); - }); - }); + /**-----------------------------------------------------------------------*/ + connect.core.getPopupManager = function () { + return connect.core.popupManager; }; + connect.core.popupManager = new connect.PopupManager(); - VoiceId.prototype.startSession = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION, { - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId(), - "customerAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), - "clientToken": AWS.util.uuid.v4(), - "domainId" : domainId - }, { - success: function (data) { - if(data.sessionId) { - resolve(data); - } else { - connect.getLog().error("startVoiceIdSession failed, no session id returned") - .withObject({ - data: data - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "No session id returned from start session api"); - reject(error); - } - }, - failure: function (err) { - connect.getLog().error("startVoiceIdSession failed") - .withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "startVoiceIdSession failed", err); - reject(error); - } - }); - }).catch(function(err) { - reject(err); - }); - }); + /**-----------------------------------------------------------------------*/ + connect.core.getUpstream = function () { + if (!connect.core.upstream) { + throw new connect.StateError('There is no upstream conduit!'); + } + return connect.core.upstream; }; + connect.core.upstream = null; - VoiceId.prototype.evaluateSpeaker = function (startNew) { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var pollTimes = 0; - return new Promise(function (resolve, reject) { - function evaluate() { - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.EVALUATE_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "DomainId" : domainId - }, { - success: function (data) { - if(++pollTimes < connect.VoiceIdConstants.EVALUATION_MAX_POLL_TIMES) { - if(data.StreamingStatus === connect.VoiceIdStreamingStatus.PENDING_CONFIGURATION) { - setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); - } else { - if(!data.AuthenticationResult) { - data.AuthenticationResult = {}; - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENABLED; - } + /**-----------------------------------------------------------------------*/ + connect.core.AgentDataProvider = AgentDataProvider; +})(); - if(!data.FraudDetectionResult) { - data.FraudDetectionResult = {}; - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; - } +/***/ }), - // Resolve if both authentication and fraud detection are not enabled. - if(!self.isAuthEnabled(data.AuthenticationResult.Decision) && - !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { - connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - return; - } +/***/ 547: +/***/ (() => { - if(data.StreamingStatus === connect.VoiceIdStreamingStatus.ENDED) { - if(self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision)) { - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; - } - if(self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; - } - } - // Voice print is not long enough for both authentication and fraud detection - if(self.isAuthResultInconclusive(data.AuthenticationResult.Decision) && - self.isFraudResultInconclusive(data.FraudDetectionResult.Decision)) { - connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - return; - } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + var ALL_EVENTS = '<>'; - if(!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && - self.isAuthEnabled(data.AuthenticationResult.Decision)) { - switch (data.AuthenticationResult.Decision) { - case connect.VoiceIdAuthenticationDecision.ACCEPT: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.AUTHENTICATED; - break; - case connect.VoiceIdAuthenticationDecision.REJECT: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_AUTHENTICATED; - break; - case connect.VoiceIdAuthenticationDecision.SPEAKER_OPTED_OUT: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.OPTED_OUT; - break; - case connect.VoiceIdAuthenticationDecision.SPEAKER_NOT_ENROLLED: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENROLLED; - break; - default: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.ERROR; - } - } + /**--------------------------------------------------------------- + * enum EventType + */ + var EventType = connect.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", "update_connected_ccps", "outer_context_info", "media_device_request", "media_device_response"]); - if(!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && - self.isFraudEnabled(data.FraudDetectionResult.Decision)) { - switch (data.FraudDetectionResult.Decision) { - case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.HIGH_RISK; - break; - case connect.VoiceIdFraudDetectionDecision.LOW_RISK: - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.LOW_RISK; - break; - default: - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.ERROR; - } - } + /**--------------------------------------------------------------- + * enum MasterTopics + */ + var MasterTopics = connect.makeNamespacedEnum('connect', ['loginPopup', 'sendLogs', 'softphone', 'ringtone', 'metrics']); - if(!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && - !self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { - // Resolve only when both authentication and fraud detection have results. Otherwise, keep polling. - connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - return; - } else { - setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); - } - } - } else { - connect.getLog().error("evaluateSpeaker timeout").sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_TIMEOUT, "evaluateSpeaker timeout"); - reject(error); - } - }, - failure: function (err) { - var error; - var parsedErr = JSON.parse(err); - switch(parsedErr.status) { - case 400: - case 404: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "evaluateSpeaker failed, session not exists", err); - connect.getLog().error("evaluateSpeaker failed, session not exists").withObject({ err: err }).sendInternalLogToServer(); - break; - default: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); - connect.getLog().error("evaluateSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); - } - reject(error); - } - }) - }).catch(function(err) { - reject(err); - }); - } - - if(!startNew) { - self.syncSpeakerId().then(function () { - evaluate(); - }).catch(function (err) { - connect.getLog().error("syncSpeakerId failed when session startNew=false") - .withObject({err: err}).sendInternalLogToServer(); - reject(err); - }) - } else { - self.startSession().then(function(data) { - self.syncSpeakerId().then(function(data) { - setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); - }).catch(function (err) { - connect.getLog().error("syncSpeakerId failed when session startNew=true") - .withObject({err: err}).sendInternalLogToServer(); - reject(err); - }); - }).catch(function(err){ - connect.getLog().error("startSession failed when session startNew=true") - .withObject({err: err}).sendInternalLogToServer(); - reject(err) - }); - } - }); - }; + /**--------------------------------------------------------------- + * enum AgentEvents + */ + var AgentEvents = connect.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']); - VoiceId.prototype.describeSession = function () { - var self = this; - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - return new Promise(function (resolve, reject) { - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.DESCRIBE_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "DomainId" : domainId - }, { - success: function (data) { - resolve(data) - }, - failure: function (err) { - connect.getLog().error("describeSession failed") - .withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DESCRIBE_SESSION_FAILED, "describeSession failed", err); - reject(error); - } - }) - }).catch(function(err) { - reject(err); - }); - }); - }; + /**--------------------------------------------------------------- + * enum WebSocketEvents + */ + var WebSocketEvents = connect.makeNamespacedEnum('webSocket', ['init_failure', 'connection_open', 'connection_close', 'connection_error', 'connection_gain', 'connection_lost', 'subscription_update', 'subscription_failure', 'all_message', 'send', 'subscribe']); - VoiceId.prototype.checkEnrollmentStatus = function () { - var self = this; - var pollingTimes = 0; + /**--------------------------------------------------------------- + * enum ContactEvents + */ + var ContactEvents = connect.makeNamespacedEnum('contact', ['init', 'refresh', 'destroyed', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'acw', 'view', 'ended', 'error', 'accepted']); + var ChannelViewEvents = connect.makeNamespacedEnum('taskList', ['activate_channel_with_view_type']); + var TaskEvents = connect.makeNamespacedEnum('task', ['created']); - return new Promise(function (resolve, reject) { - function describe () { - if(++pollingTimes < connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES) { - self.describeSession().then(function(data){ - switch(data.Session.EnrollmentRequestDetails.Status) { - case connect.VoiceIdEnrollmentRequestStatus.COMPLETED: - resolve(data); - break; - case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: - setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); - break; - case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: - if(data.Session.StreamingStatus !== connect.VoiceIdStreamingStatus.ENDED) { - setTimeout(describe,connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); - } else { - setTimeout(function(){ - self.startSession().then(function(data) { - describe(); - }).catch(function(err, data){ - reject(err); - }); - }, connect.VoiceIdConstants.START_SESSION_DELAY); - } - break; - default: - var message = data.Session.EnrollmentRequestDetails.Message ? data.Session.EnrollmentRequestDetails.Message : "enrollSpeaker failed. Unknown enrollment status has been received"; - connect.getLog().error(message).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, message, data.Session.EnrollmentRequestDetails.Status); - reject(error); - } - }); - } else { - connect.getLog().error("enrollSpeaker timeout").sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT, "enrollSpeaker timeout"); - reject(error); - } - } - describe(); - }); + /**--------------------------------------------------------------- + * enum ConnectionEvents + */ + var ConnectionEvents = connect.makeNamespacedEnum('connection', ['session_init', 'ready_to_start_session']); + + /**--------------------------------------------------------------- + * enum Configuration Events + */ + var ConfigurationEvents = connect.makeNamespacedEnum('configuration', ['configure', 'set_speaker_device', 'set_microphone_device', 'set_ringer_device', 'speaker_device_changed', 'microphone_device_changed', 'ringer_device_changed']); + + /**--------------------------------------------------------------- + * enum VoiceId Events + */ + var VoiceIdEvents = connect.makeNamespacedEnum('voiceId', ['update_domain_id']); + + /**--------------------------------------------------------------- + * class EventFactory + */ + var EventFactory = function EventFactory() {}; + EventFactory.createRequest = function (type, method, params) { + return { + event: type, + requestId: connect.randomId(), + method: method, + params: params + }; + }; + EventFactory.createResponse = function (type, request, data, err) { + return { + event: type, + requestId: request.requestId, + data: data, + err: err || null + }; }; - VoiceId.prototype.enrollSpeaker = function () { - var self = this; - self.checkConferenceCall(); - return new Promise(function(resolve, reject) { - self.syncSpeakerId().then(function() { - self.getSpeakerStatus().then(function(data) { - if(data.Speaker && data.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT) { - self.deleteSpeaker().then(function() { - self.enrollSpeakerHelper(resolve, reject); - }).catch(function(err) { - reject(err); - }); - } else { - self.enrollSpeakerHelper(resolve, reject); - } - }).catch(function(err) { - reject(err); - }) - }).catch(function(err) { - reject(err) - }) - }) - } + /** + * An object representing an event subscription in an EventBus. + */ + var Subscription = function Subscription(subMap, eventName, f) { + this.subMap = subMap; + this.id = connect.randomId(); + this.eventName = eventName; + this.f = f; + }; - VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject) { - var self = this; - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.ENROLL_BY_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "DomainId" : domainId - }, { - success: function (data) { - if(data.Status === connect.VoiceIdEnrollmentRequestStatus.COMPLETED) { - connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - } else { - self.checkEnrollmentStatus().then(function(data){ - connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }).catch(function(err){ - reject(err); - }) - } - }, - failure: function (err) { - connect.getLog().error("enrollSpeaker failed") - .withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, "enrollSpeaker failed", err); - reject(error); - } - }); - }).catch(function(err) { - reject(err); - }); + /** + * Unsubscribe the handler of this subscription from the EventBus + * from which it was created. + */ + Subscription.prototype.unsubscribe = function () { + this.subMap.unsubscribe(this.eventName, this.id); }; - // internal only - VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId) { - var self = this; - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { - "ContactId": self.contactId, - "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), - "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), - "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), - "VoiceIdResult": { - "generatedSpeakerId": speakerId - } - }, { - success: function (data) { - connect.getLog().info("updateSpeakerIdInLcms succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err) { - connect.getLog().error("updateSpeakerIdInLcms failed") - .withObject({ - err: err, - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_IN_LCMS_FAILED, "updateSpeakerIdInLcms failed", err); - reject(error); - } - }); - }); + /** + * A map of event subscriptions, used by the EventBus. + */ + var SubscriptionMap = function SubscriptionMap() { + this.subIdMap = {}; + this.subEventNameMap = {}; }; - VoiceId.prototype.updateSpeakerIdInVoiceId = function (speakerId) { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - return new Promise(function (resolve, reject) { - self.getDomainId().then(function(domainId) { - client.call(connect.AgentAppClientMethods.UPDATE_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), - "DomainId" : domainId - }, { - success: function (data) { - connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); - self._updateSpeakerIdInLcms(speakerId) - .then(function() { - resolve(data); - }) - .catch(function(err) { - reject(err); - }); - }, - failure: function (err) { - var error; - var parsedErr = JSON.parse(err); - switch(parsedErr.status) { - case 400: - case 404: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "updateSpeakerIdInVoiceId failed, session not exists", err); - connect.getLog().error("updateSpeakerIdInVoiceId failed, session not exists").withObject({ err: err }).sendInternalLogToServer(); - break; - default: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); - connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: err }).sendInternalLogToServer(); - } - reject(error); - } - }); - }).catch(function(err) { - reject(err); - }); - }); + /** + * Add a subscription for the named event. Creates a new Subscription + * object and returns it. This object can be used to unsubscribe. + */ + SubscriptionMap.prototype.subscribe = function (eventName, f) { + var sub = new Subscription(this, eventName, f); + this.subIdMap[sub.id] = sub; + var subList = this.subEventNameMap[eventName] || []; + subList.push(sub); + this.subEventNameMap[eventName] = subList; + return sub; }; - VoiceId.prototype.syncSpeakerId = function () { - var self = this; - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function(data){ - self.updateSpeakerIdInVoiceId(data.speakerId).then(function(data){ - resolve(data); - }).catch(function(err) { - reject(err); - }) - }).catch(function(err){ - reject(err); + /** + * Unsubscribe a subscription matching the given event name and id. + */ + SubscriptionMap.prototype.unsubscribe = function (eventName, subId) { + if (connect.contains(this.subEventNameMap, eventName)) { + this.subEventNameMap[eventName] = this.subEventNameMap[eventName].filter(function (s) { + return s.id !== subId; }); - }) - } - - VoiceId.prototype.getDomainId = function() { - return new Promise(function (resolve, reject) { - const agent = new connect.Agent(); - if (!agent.getPermissions().includes(connect.AgentPermissions.VOICE_ID)) { - reject(new Error("Agent doesn't have the permission for Voice ID")); - } else if (connect.core.voiceIdDomainId) { - resolve(connect.core.voiceIdDomainId); - } else { - var client = connect.core.getClient(); - client.call(connect.AgentAppClientMethods.LIST_INTEGRATION_ASSOCIATIONS, { - "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), - "IntegrationType": "VOICE_ID" - }, { - success: function (data) { - try { - var domainId; - if (data.IntegrationAssociationSummaryList.length >= 1) { - var integrationArn = data.IntegrationAssociationSummaryList[0].IntegrationArn; - domainId = integrationArn.replace(/^.*domain\//i, ''); - } - if (!domainId) { - connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND); - reject(error); - return; - } - connect.getLog().info("getDomainId succeeded").withObject(data).sendInternalLogToServer(); - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.VoiceIdEvents.UPDATE_DOMAIN_ID, - data: { domainId: domainId } - }); - resolve(domainId); - } catch(err) { - connect.getLog().error("getDomainId failed").withObject({ err: err }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); - reject(error); - } - }, - failure: function (err) { - connect.getLog().error("getDomainId failed").withObject({ err: err }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); - reject(error); - } - }); + if (this.subEventNameMap[eventName].length < 1) { + delete this.subEventNameMap[eventName]; } - }); - } - - VoiceId.prototype.checkConferenceCall = function(){ - var self = this; - var isConferenceCall = connect.core.getAgentDataProvider().getContactData(self.contactId).connections.filter(function (conn) { - return connect.contains(connect.CONNECTION_ACTIVE_STATES, conn.state.type); - }).length > 2; - if(isConferenceCall){ - throw new connect.NotImplementedError("VoiceId is not supported for conference calls"); } - } + if (connect.contains(this.subIdMap, subId)) { + delete this.subIdMap[subId]; + } + }; - VoiceId.prototype.isAuthEnabled = function(authResult) { - return authResult !== connect.ContactFlowAuthenticationDecision.NOT_ENABLED; - } + /** + * Get a list of all subscriptions in the subscription map. + */ + SubscriptionMap.prototype.getAllSubscriptions = function () { + return connect.values(this.subEventNameMap).reduce(function (a, b) { + return a.concat(b); + }, []); + }; - VoiceId.prototype.isAuthResultNotEnoughSpeech = function(authResult) { - return authResult === connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH; - } + /** + * Get a list of subscriptions for the given event name, or an empty + * list if there are no subscriptions. + */ + SubscriptionMap.prototype.getSubscriptions = function (eventName) { + return this.subEventNameMap[eventName] || []; + }; - VoiceId.prototype.isAuthResultInconclusive = function(authResult) { - return authResult === connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; - } + /** + * An object which maintains a map of subscriptions and serves as the + * mechanism for triggering events to be handled by subscribers. + */ + var EventBus = function EventBus(paramsIn) { + var params = paramsIn || {}; + this.subMap = new SubscriptionMap(); + this.logEvents = params.logEvents || false; + }; - VoiceId.prototype.isFraudEnabled = function(fraudResult) { - return fraudResult !== connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; - } + /** + * Subscribe to the named event. Returns a new Subscription object + * which can be used to unsubscribe. + */ + EventBus.prototype.subscribe = function (eventName, f) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.subMap.subscribe(eventName, f); + }; - VoiceId.prototype.isFraudResultNotEnoughSpeech = function(fraudResult) { - return fraudResult === connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH; - } + /** + * Subscribe a function to be called on all events. + */ + EventBus.prototype.subscribeAll = function (f) { + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.subMap.subscribe(ALL_EVENTS, f); + }; - VoiceId.prototype.isFraudResultInconclusive = function(fraudResult) { - return fraudResult === connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; - } + /** + * Get a list of subscriptions for the given event name, or an empty + * list if there are no subscriptions. + */ + EventBus.prototype.getSubscriptions = function (eventName) { + return this.subMap.getSubscriptions(eventName); + }; /** - * @class VoiceConnection - * @param {number} contactId - * @param {number} connectionId - * @description - Provides voice media specific operations + * Trigger the given event with the given data. All methods subscribed + * to this event will be called and are provided with the given arbitrary + * data object and the name of the event, in that order. */ - var VoiceConnection = function (contactId, connectionId) { - this._speakerAuthenticator = new VoiceId(contactId); - Connection.call(this, contactId, connectionId); + EventBus.prototype.trigger = function (eventName, data) { + connect.assertNotNull(eventName, 'eventName'); + var self = this; + var allEventSubs = this.subMap.getSubscriptions(ALL_EVENTS); + var eventSubs = this.subMap.getSubscriptions(eventName); + if (this.logEvents && eventName !== connect.EventType.LOG && eventName !== connect.EventType.MASTER_RESPONSE && eventName !== connect.EventType.API_METRIC && eventName !== connect.EventType.SERVER_BOUND_INTERNAL_LOG) { + connect.getLog().trace("Publishing event: %s", eventName).sendInternalLogToServer(); + } + if (eventName.startsWith(connect.ContactEvents.ACCEPTED) && data && data.contactId && !(data instanceof connect.Contact)) { + data = new connect.Contact(data.contactId); + } + allEventSubs.concat(eventSubs).forEach(function (sub) { + try { + sub.f(data || null, eventName, self); + } catch (e) { + connect.getLog().error("'%s' event handler failed.", eventName).withException(e).sendInternalLogToServer(); + } + }); }; - VoiceConnection.prototype = Object.create(Connection.prototype); - VoiceConnection.prototype.constructor = VoiceConnection; - /** - * @deprecated - * Please use getMediaInfo - */ - VoiceConnection.prototype.getSoftphoneMediaInfo = function () { - return this._getData().softphoneMediaInfo; + * Returns a closure which bridges an event from another EventBus to this bus. + * + * Usage: + * conduit.onUpstream("MyEvent", bus.bridge()); + */ + EventBus.prototype.bridge = function () { + var self = this; + return function (data, event) { + self.trigger(event, data); + }; }; - VoiceConnection.prototype.getMediaInfo = function () { - return this._getData().softphoneMediaInfo; + /** + * Unsubscribe all events in the event bus. + */ + EventBus.prototype.unsubscribeAll = function () { + this.subMap.getAllSubscriptions().forEach(function (sub) { + sub.unsubscribe(); + }); }; + connect.EventBus = EventBus; + connect.EventFactory = EventFactory; + connect.EventType = EventType; + connect.AgentEvents = AgentEvents; + connect.ConfigurationEvents = ConfigurationEvents; + connect.ConnectionEvents = ConnectionEvents; + connect.ConnnectionEvents = ConnectionEvents; //deprecate on next major version release. + connect.ContactEvents = ContactEvents; + connect.ChannelViewEvents = ChannelViewEvents; + connect.TaskEvents = TaskEvents; + connect.VoiceIdEvents = VoiceIdEvents; + connect.WebSocketEvents = WebSocketEvents; + connect.MasterTopics = MasterTopics; +})(); - VoiceConnection.prototype.getMediaType = function () { - return connect.MediaType.SOFTPHONE; - }; +/***/ }), - VoiceConnection.prototype.getMediaController = function () { - return connect.core.mediaFactory.get(this); - } +/***/ 42: +/***/ (() => { - VoiceConnection.prototype.getVoiceIdSpeakerId = function() { - return this._speakerAuthenticator.getSpeakerId(); - } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +!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"; - VoiceConnection.prototype.getVoiceIdSpeakerStatus = function() { - return this._speakerAuthenticator.getSpeakerStatus(); - } + 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 assertTrue(e, n) { + if (!e) throw new Error(n); + }, + assertNotNull: function assertNotNull(e, n) { + return b.assertTrue(null !== e && void 0 !== d(e), Object(o.sprintf)("%s must be provided", n || "A value")), e; + }, + isNonEmptyString: function isNonEmptyString(e) { + return "string" == typeof e && e.length > 0; + }, + assertIsList: function assertIsList(e, n) { + if (!Array.isArray(e)) throw new Error(n + " is not an array"); + }, + isFunction: function isFunction(e) { + return !!(e && e.constructor && e.call && e.apply); + }, + isObject: function isObject(e) { + return !("object" !== d(e) || null === e); + }, + isString: function isString(e) { + return "string" == typeof e; + }, + isNumber: function isNumber(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 < n.length; t++) { + var o = n[t]; + o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); + } + } + function C(e, n, t) { + return n && w(e.prototype, n), t && w(e, t), e; + } + var T = function () { + function e() { + v(this, e); + } + return C(e, [{ + key: "debug", + value: function value(e) {} + }, { + key: "info", + value: function value(e) {} + }, { + key: "warn", + value: function value(e) {} + }, { + key: "error", + value: function value(e) {} + }]), e; + }(), + O = { + DEBUG: 10, + INFO: 20, + WARN: 30, + ERROR: 40 + }, + I = function () { + function e() { + v(this, e), this.updateLoggerConfig(), this.consoleLoggerWrapper = _(); + } + return C(e, [{ + key: "writeToClientLogger", + value: function value(e, n) { + if (this.hasClientLogger()) switch (e) { + case O.DEBUG: + return this._clientLogger.debug(n); + case O.INFO: + return this._clientLogger.info(n); + case O.WARN: + return this._clientLogger.warn(n); + case O.ERROR: + return this._clientLogger.error(n); + } + } + }, { + key: "isLevelEnabled", + value: function value(e) { + return e >= this._level; + } + }, { + key: "hasClientLogger", + value: function value() { + return null !== this._clientLogger; + } + }, { + key: "getLogger", + value: function value(e) { + var n = e.prefix || ""; + return this._logsDestination === c ? this.consoleLoggerWrapper : new N(n); + } + }, { + key: "updateLoggerConfig", + value: function value(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 value() {} + }, { + key: "info", + value: function value() {} + }, { + key: "warn", + value: function value() {} + }, { + key: "error", + value: function value() {} + }]), 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 value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.DEBUG, n); + } + }, { + key: "info", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.INFO, n); + } + }, { + key: "warn", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.WARN, n); + } + }, { + key: "error", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.ERROR, n); + } + }, { + key: "_shouldLog", + value: function value(e) { + return E.hasClientLogger() && E.isLevelEnabled(e); + } + }, { + key: "_writeToClientLogger", + value: function value(e, n) { + return E.writeToClientLogger(e, n); + } + }, { + key: "_log", + value: function value(e, n) { + if (this._shouldLog(e)) { + var t = this._convertToSingleStatement(n); + return this._writeToClientLogger(e, t); + } + } + }, { + key: "_convertToSingleStatement", + value: function value(e) { + var n = ""; + this.prefix && (n += this.prefix + " "); + for (var t = 0; t < e.length; t++) { + var o = e[t]; + n += this._convertToString(o) + " "; + } + return n; + } + }, { + key: "_convertToString", + value: function value(e) { + try { + if (!e) return ""; + if (y.isString(e)) return e; + if (y.isObject(e) && y.isFunction(e.toString)) { + var n = e.toString(); + if ("[object Object]" !== n) return n; + } + return JSON.stringify(e); + } catch (n) { + return console.error("Error while converting argument to string", e, n), ""; + } + } + }]), n; + }(), + _ = function _() { + var e = new W(); + return e.debug = console.debug, e.info = console.info, e.warn = console.warn, e.error = console.error, e; + }, + E = new I(); + function F(e, n) { + for (var t = 0; t < n.length; t++) { + var o = n[t]; + o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); + } + } + var L = function () { + function e(n) { + var t = arguments.length > 1 && 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 value() { + var e = this; + this.hasActiveReconnection || (this.hasActiveReconnection = !0, setTimeout(function () { + e._execute(); + }, this._getDelay())); + } + }, { + key: "_execute", + value: function value() { + this.hasActiveReconnection = !1, this.executor(), this.numAttempts++; + } + }, { + key: "connected", + value: function value() { + this.numAttempts = 0; + } + }, { + key: "_getDelay", + value: function value() { + 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 x() { + 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 k(n, t) { + n.forEach(function (n) { + try { + n(t); + } catch (n) { + J(e.error("Error executing callback", n)); + } + }); + }, + h = function h(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 v() { + 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 w(e, n) { + return e && e.readyState === n; + }, + C = function C(e) { + return w(e, WebSocket.OPEN); + }, + T = function T(e) { + return null === e || void 0 === e.readyState || w(e, WebSocket.CLOSED); + }, + O = function O() { + return null !== t.secondary ? t.secondary : t.primary; + }, + I = function I() { + return C(O()); + }, + W = function W() { + 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 N() { + 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 F() { + r.connectWebSocketRetryCount = 0, r.connectionAttemptStartTime = null, r.noOpenConnectionsTimestamp = null; + }, + x = function x() { + 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 R(n) { + v("webSocketOnError"), J(e.error("WebSocketManager Error, error_event: ", JSON.stringify(n))), U(); + }, + j = function j(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 D(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 M(e) { + D(t.primary, "[Primary] WebSocket " + e), D(t.secondary, "[Secondary] WebSocket " + e); + }, + P = function P() { + 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 H(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 G(e, n) { + return JSON.stringify({ + topic: e, + content: n + }); + }, + z = function z(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 U() { + 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 q() { + 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 B() { + 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 J(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 create() { + return new x(); + }, + setGlobalConfig: function setGlobalConfig(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 < b; o++) if ("string" == typeof e[o]) g += e[o];else if ("object" == _typeof(e[o])) { + if ((s = e[o]).keys) for (t = n[d], c = 0; c < s.keys.length; c++) { + if (null == t) throw new Error(i('[sprintf] Cannot access property "%s" of undefined value "%s"', s.keys[c], s.keys[c - 1])); + t = t[s.keys[c]]; + } else t = s.param_no ? n[s.param_no] : n[d++]; + if (r.not_type.test(s.type) && r.not_primitive.test(s.type) && t instanceof Function && (t = t()), r.numeric_arg.test(s.type) && "number" != typeof t && isNaN(t)) throw new TypeError(i("[sprintf] expecting number but found %T", t)); + switch (r.number.test(s.type) && (f = t >= 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"; - VoiceConnection.prototype.optOutVoiceIdSpeaker = function() { - - return this._speakerAuthenticator.optOutSpeaker(); + 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 === "undefined" ? "undefined" : _typeof(window)) && (t = window); } + e.exports = t; +}]); - VoiceConnection.prototype.deleteVoiceIdSpeaker = function() { - return this._speakerAuthenticator.deleteSpeaker(); - } +/***/ }), - VoiceConnection.prototype.evaluateSpeakerWithVoiceId = function(startNew) { - return this._speakerAuthenticator.evaluateSpeaker(startNew); - } +/***/ 312: +/***/ (() => { - VoiceConnection.prototype.enrollSpeakerInVoiceId = function() { - return this._speakerAuthenticator.enrollSpeaker(); - } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + + // How frequently softphone logs should be collected and reported to shared worker. + var SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS = 5000; - VoiceConnection.prototype.updateVoiceIdSpeakerId = function(speakerId) { - return this._speakerAuthenticator.updateSpeakerIdInVoiceId(speakerId); - } + // How frequently logs should be collected and sent downstream + var LOGS_REPORT_INTERVAL_MILLIS = 5000; - VoiceConnection.prototype.getQuickConnectName = function () { - return this._getData().quickConnectName; - }; + // The default log roll interval (30min) + var DEFAULT_LOG_ROLL_INTERVAL = 1800000; - VoiceConnection.prototype.isMute = function () { - return this._getData().mute; + /** + * An enumeration of common logging levels. + */ + var LogLevel = { + TEST: "TEST", + TRACE: "TRACE", + DEBUG: "DEBUG", + INFO: "INFO", + LOG: "LOG", + WARN: "WARN", + ERROR: "ERROR", + CRITICAL: "CRITICAL" }; - VoiceConnection.prototype.muteParticipant = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.MUTE_PARTICIPANT, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); + /** + * An enumeration of common logging components. + */ + var LogComponent = { + CCP: "ccp", + SOFTPHONE: "softphone", + CHAT: "chat", + TASK: "task" }; - VoiceConnection.prototype.unmuteParticipant = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.UNMUTE_PARTICIPANT, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); + /** + * The numeric order of the logging levels above. + * They are spaced to allow the addition of other log + * levels at a later time. + */ + var LogLevelOrder = { + TEST: 0, + TRACE: 10, + DEBUG: 20, + INFO: 30, + LOG: 40, + WARN: 50, + ERROR: 100, + CRITICAL: 200 }; - /** - * @class ChatConnection - * @param {*} contactId - * @param {*} connectionId - * @description adds the chat media specific functionality + * A map from log level to console logger function. */ - var ChatConnection = function (contactId, connectionId) { - Connection.call(this, contactId, connectionId); + var CONSOLE_LOGGER_MAP = { + TRACE: function TRACE(text) { + console.info(text); + }, + DEBUG: function DEBUG(text) { + console.info(text); + }, + INFO: function INFO(text) { + console.info(text); + }, + LOG: function LOG(text) { + console.log(text); + }, + TEST: function TEST(text) { + console.log(text); + }, + WARN: function WARN(text) { + console.warn(text); + }, + ERROR: function ERROR(text) { + console.error(text); + }, + CRITICAL: function CRITICAL(text) { + console.error(text); + } }; - ChatConnection.prototype = Object.create(Connection.prototype); - ChatConnection.prototype.constructor = ChatConnection; + /** + * Checks if it is a valid log component enum + */ - ChatConnection.prototype.getMediaInfo = function () { - var data = this._getData().chatMediaInfo; - if (!data) { - return null; - } else { - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var mediaObject = { - contactId: this.contactId, - initialContactId: contactData.initialContactId || this.contactId, - participantId: this.connectionId, - getConnectionToken: connect.hitch(this, this.getConnectionToken) - }; - if (data.connectionData) { - try { - mediaObject.participantToken = JSON.parse(data.connectionData).ConnectionAuthenticationToken; - } catch (e) { - connect.getLog().error(connect.LogComponent.CHAT, "Connection data is invalid") - .withObject(data) - .withException(e) - .sendInternalLogToServer(); - mediaObject.participantToken = null; - } - } - mediaObject.participantToken = mediaObject.participantToken || null; - /** Just to keep the data accessible */ - mediaObject.originalInfo = this._getData().chatMediaInfo; - return mediaObject; - } + var isValidLogComponent = function isValidLogComponent(component) { + return Object.values(LogComponent).indexOf(component) !== -1; }; /** - * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. - * @returns a promise which, upon success, returns the response from the createTransport API. - * Usage: - * connection.getConnectionToken() - * .then(response => {}) - * .catch(error => {}) + * Extract the custom arguments as required by the logger */ - ChatConnection.prototype.getConnectionToken = function () { - client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var transportDetails = { - transportType: connect.TRANSPORT_TYPES.CHAT_TOKEN, - participantId: this.connectionId, - contactId: contactData.initialContactId || this.contactId + var extractLoggerArgs = function extractLoggerArgs(loggerArgs) { + var args = Array.prototype.slice.call(loggerArgs, 0); + var firstArg = args.shift(); + var format; + var component; + if (isValidLogComponent(firstArg)) { + component = firstArg; + format = args.shift(); + } else { + //default to CCP component + format = firstArg; + component = LogComponent.CCP; + } + return { + format: format, + component: component, + args: args }; - return new Promise(function (resolve, reject) { - client.call(connect.ClientMethods.CREATE_TRANSPORT, transportDetails, { - success: function (data) { - connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(); - resolve(data); - }, - failure: function (err, data) { - connect.getLog().error("getConnectionToken failed").sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - reject(Error("getConnectionToken failed")); - } - }); - }); }; - ChatConnection.prototype.getMediaType = function () { - return connect.MediaType.CHAT; + /** + * A log entry. + * + * @param component The logging component. + * @param level The log level of this log entry. + * @param text The text contained in the log entry. + * @param loggerId The root logger id. + * + * Log entries are aware of their timestamp, order, + * and can contain objects and exception stack traces. + */ + var LogEntry = function LogEntry(component, level, text, loggerId) { + this.component = component; + this.level = level; + this.text = text; + this.time = new Date(); + this.exception = null; + this.objects = []; + this.line = 0; + this.agentResourceId = null; + try { + if (connect.agent.initialized) { + this.agentResourceId = new connect.Agent()._getResourceId(); + } + } catch (e) { + console.log("Issue finding agentResourceId: ", e); //can't use our logger here as we might infinitely attempt to log this error. + } + + this.loggerId = loggerId; }; + LogEntry.fromObject = function (obj) { + var entry = new LogEntry(LogComponent.CCP, obj.level, obj.text, obj.loggerId); - ChatConnection.prototype.getMediaController = function () { - return connect.core.mediaFactory.get(this); + // Required to check for Date objects sent across frame boundaries + if (Object.prototype.toString.call(obj.time) === '[object Date]') { + entry.time = new Date(obj.time.getTime()); + } else if (typeof obj.time === 'number') { + entry.time = new Date(obj.time); + } else if (typeof obj.time === 'string') { + entry.time = Date.parse(obj.time); + } else { + entry.time = new Date(); + } + entry.exception = obj.exception; + entry.objects = obj.objects; + return entry; }; - ChatConnection.prototype._initMediaController = function () { - // Note that a chat media controller only needs to be produced for agent type connections. - if (this._isAgentConnectionType()) { - connect.core.mediaFactory.get(this).catch(function () { }); + /** + * Private method to remove sensitive info from client log + */ + var redactSensitiveInfo = function redactSensitiveInfo(data) { + var regex = /AuthToken.*\=/g; + if (data && _typeof(data) === 'object') { + Object.keys(data).forEach(function (key) { + if (_typeof(data[key]) === 'object') { + redactSensitiveInfo(data[key]); + } else if (typeof data[key] === 'string') { + if (key === "url" || key === "text") { + data[key] = data[key].replace(regex, "[redacted]"); + } else if (key === "quickConnectName") { + data[key] = "[redacted]"; + } + } + }); } - } + }; /** - * @class TaskConnection - * @param {*} contactId - * @param {*} connectionId - * @description adds the task media specific functionality + * Pulls the type, message, and stack trace + * out of the given exception for JSON serialization. */ - var TaskConnection = function (contactId, connectionId) { - Connection.call(this, contactId, connectionId); + var LoggedException = function LoggedException(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') : []; }; - TaskConnection.prototype = Object.create(Connection.prototype); - TaskConnection.prototype.constructor = TaskConnection; - TaskConnection.prototype.getMediaType = function () { - return connect.MediaType.TASK; - } + /** + * Minimally stringify this log entry for printing + * to the console. + */ + LogEntry.prototype.toString = function () { + return connect.sprintf("[%s] [%s] [%s]: %s", this.getTime() && this.getTime().toISOString ? this.getTime().toISOString() : "???", this.getLevel(), this.getAgentResourceId(), this.getText()); + }; - TaskConnection.prototype.getMediaInfo = function () { - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var mediaObject = { - contactId: this.contactId, - initialContactId: contactData.initialContactId || this.contactId, - }; - return mediaObject; + /** + * Get the log entry timestamp. + */ + LogEntry.prototype.getTime = function () { + return this.time; + }; + LogEntry.prototype.getAgentResourceId = function () { + return this.agentResourceId; }; - TaskConnection.prototype.getMediaController = function () { - return connect.core.mediaFactory.get(this); + /** + * Get the level of the log entry. + */ + LogEntry.prototype.getLevel = function () { + return this.level; }; - /*---------------------------------------------------------------- - * class ConnectionSnapshot + /** + * Get the log entry text. */ - var ConnectionSnapshot = function (connectionData) { - connect.Connection.call(this, connectionData.contactId, connectionData.connectionId); - this.connectionData = connectionData; + LogEntry.prototype.getText = function () { + return this.text; }; - ConnectionSnapshot.prototype = Object.create(Connection.prototype); - ConnectionSnapshot.prototype.constructor = ConnectionSnapshot; - ConnectionSnapshot.prototype._getData = function () { - return this.connectionData; + /** + * Get the log entry component. + */ + LogEntry.prototype.getComponent = function () { + return this.component; }; - ConnectionSnapshot.prototype._initMediaController = function () { }; - - var Endpoint = function (paramsIn) { - var params = paramsIn || {}; - this.endpointARN = params.endpointId || params.endpointARN || null; - this.endpointId = this.endpointARN; - this.type = params.type || null; - this.name = params.name || null; - this.phoneNumber = params.phoneNumber || null; - this.agentLogin = params.agentLogin || null; - this.queue = params.queue || null; + /** + * Add an exception stack trace to this log entry. + * A log entry may contain only one exception stack trace. + */ + LogEntry.prototype.withException = function (e) { + this.exception = new LoggedException(e); + return this; }; /** - * Strip the SIP endpoint components from the phoneNumber field. + * Add an arbitrary object to the log entry. A log entry + * may contain any number of objects. */ - Endpoint.prototype.stripPhoneNumber = function () { - return this.phoneNumber ? this.phoneNumber.replace(/sip:([^@]*)@.*/, "$1") : ""; + LogEntry.prototype.withObject = function (obj) { + var copiedObj = connect.deepcopy(obj); + redactSensitiveInfo(copiedObj); + this.objects.push(copiedObj); + return this; }; /** - * Create an Endpoint object from the given phone number and name. + * Add a cross origin event object to the log entry. A log entry + * may contain any number of objects. */ - Endpoint.byPhoneNumber = function (number, name) { - return new Endpoint({ - type: connect.EndpointType.PHONE_NUMBER, - phoneNumber: number, - name: name || null - }); + LogEntry.prototype.withCrossOriginEventObject = function (obj) { + var copiedObj = connect.deepcopyCrossOriginEvent(obj); + redactSensitiveInfo(copiedObj); + this.objects.push(copiedObj); + return this; }; - /*---------------------------------------------------------------- - * class SoftphoneError + /** + * Indicate that this log entry should be sent to the server + * NOTE: This should be used for internal logs only */ - var SoftphoneError = function (errorType, errorMessage, endPointUrl) { - this.errorType = errorType; - this.errorMessage = errorMessage; - this.endPointUrl = endPointUrl; - }; - SoftphoneError.prototype.getErrorType = function () { - return this.errorType; - }; - SoftphoneError.prototype.getErrorMessage = function () { - return this.errorMessage; + LogEntry.prototype.sendInternalLogToServer = function () { + connect.getLog()._serverBoundInternalLogs.push(this); + return this; }; - SoftphoneError.prototype.getEndPointUrl = function () { - return this.endPointUrl; + + /** + * The logger instance. + */ + var Logger = function Logger() { + this._logs = []; + this._rolledLogs = []; + this._logsToPush = []; + this._serverBoundInternalLogs = []; + this._echoLevel = LogLevelOrder.INFO; + this._logLevel = LogLevelOrder.INFO; + this._lineCount = 0; + this._logRollInterval = 0; + this._logRollTimer = null; + this._loggerId = new Date().getTime() + "-" + Math.random().toString(36).slice(2); + this.setLogRollInterval(DEFAULT_LOG_ROLL_INTERVAL); + this._startLogIndexToPush = 0; }; - /*---------------------------------------------------------------- - * Root Subscription APIs. + /** + * Sets the interval in milliseconds that the logs will be rotated. + * Logs are rotated out completely at the end of the second roll + * and will eventually be garbage collected. */ - connect.agent = function (f) { - var bus = connect.core.getEventBus(); - var sub = bus.subscribe(connect.AgentEvents.INIT, f); - if (connect.agent.initialized) { - f(new connect.Agent()); + Logger.prototype.setLogRollInterval = function (interval) { + var self = this; + if (!this._logRollTimer || interval !== this._logRollInterval) { + if (this._logRollTimer) { + global.clearInterval(this._logRollTimer); + } + this._logRollInterval = interval; + this._logRollTimer = global.setInterval(function () { + this._rolledLogs = this._logs; + this._logs = []; + this._startLogIndexToPush = 0; + self.info("Log roll interval occurred."); + }, this._logRollInterval); + } else { + this.warn("Logger is already set to the given interval: %d", this._logRollInterval); } - return sub; }; - connect.agent.initialized = false; - connect.contact = function (f) { - var bus = connect.core.getEventBus(); - return bus.subscribe(connect.ContactEvents.INIT, f); + /** + * Set the log level. This is the minimum level at which logs will + * be kept for later archiving. + */ + Logger.prototype.setLogLevel = function (level) { + if (level in LogLevelOrder) { + this._logLevel = LogLevelOrder[level]; + } else { + throw new Error("Unknown logging level: " + level); + } }; - connect.onWebsocketInitFailure = function (f) { - var bus = connect.core.getEventBus(); - var sub = bus.subscribe(connect.WebSocketEvents.INIT_FAILURE, f); - if (connect.webSocketInitFailed) { - f(); + /** + * Set the echo level. This is the minimum level at which logs will + * be printed to the javascript console. + */ + Logger.prototype.setEchoLevel = function (level) { + if (level in LogLevelOrder) { + this._echoLevel = LogLevelOrder[level]; + } else { + throw new Error("Unknown logging level: " + level); } - return sub; }; /** - * Starts the given function asynchronously only if the shared worker - * says we are the master for the given topic. If there is no master for - * the given topic, we become the master and start the function unless - * shouldNotBecomeMasterIfNone is true. + * Write a particular log entry. * - * @param topic The master topic we are concerned about. - * @param f_true The callback to be invoked if we are the master. - * @param f_else [optional] A callback to be invoked if we are not the master. - * @param shouldNotBecomeMasterIfNone [optional] if true, this tab won't become master. + * @param level The logging level of the entry. + * @param text The text contents of the entry. + * + * @returns The new log entry. */ - connect.ifMaster = function (topic, f_true, f_else, shouldNotBecomeMasterIfNone) { - connect.assertNotNull(topic, "A topic must be provided."); - connect.assertNotNull(f_true, "A true callback must be provided."); + Logger.prototype.write = function (component, level, text) { + var logEntry = new LogEntry(component, level, text, this.getLoggerId()); + redactSensitiveInfo(logEntry); + this.addLogEntry(logEntry); + return logEntry; + }; + Logger.prototype.addLogEntry = function (logEntry) { + // Call this second time as in some places this function is called directly + redactSensitiveInfo(logEntry); + this._logs.push(logEntry); - if (!connect.core.masterClient) { - // We can't be the master because there is no master client! - connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic).sendInternalLogToServer(); - if (f_else) { - f_else(); + //For now only send softphone logs only. + //TODO add CCP logs once we are sure that no sensitive data is being logged. + if (LogComponent.SOFTPHONE === logEntry.component) { + this._logsToPush.push(logEntry); + } + if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { + if (LogLevelOrder[logEntry.level] >= this._echoLevel) { + CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); } - return; + logEntry.line = this._lineCount++; } - - var masterClient = connect.core.getMasterClient(); - masterClient.call(connect.MasterMethods.CHECK_MASTER, { - topic: topic, - shouldNotBecomeMasterIfNone: shouldNotBecomeMasterIfNone - }, { - success: function (data) { - if (data.isMaster) { - f_true(); - - } else if (f_else) { - f_else(); - } - } - }); }; - - /** - * Notify the shared worker and other CCP tabs that we are now the master for the given topic. - */ - connect.becomeMaster = function (topic, successCallback, failureCallback) { - connect.assertNotNull(topic, "A topic must be provided."); - - if (!connect.core.masterClient) { - // We can't be the master because there is no master client! - connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic); - if (failureCallback) { - failureCallback(); + Logger.prototype.sendInternalLogEntryToServer = function (logEntry) { + this._serverBoundInternalLogs.push(logEntry); + if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { + if (LogLevelOrder[logEntry.level] >= this._echoLevel) { + CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); } - } else { - var masterClient = connect.core.getMasterClient(); - masterClient.call(connect.MasterMethods.BECOME_MASTER, { - topic: topic - }, { - success: function () { - if (successCallback) { - successCallback(); - } - } - }); + logEntry.line = this._lineCount++; } }; - connect.Agent = Agent; - connect.AgentSnapshot = AgentSnapshot; - connect.Contact = Contact; - connect.ContactSnapshot = ContactSnapshot; - /** Default will get the Voice connection */ - connect.Connection = VoiceConnection; - connect.BaseConnection = Connection; - connect.VoiceConnection = VoiceConnection; - connect.ChatConnection = ChatConnection; - connect.TaskConnection = TaskConnection; - connect.ConnectionSnapshot = ConnectionSnapshot; - connect.Endpoint = Endpoint; - connect.Address = Endpoint; - connect.SoftphoneError = SoftphoneError; - connect.VoiceId = VoiceId; -})(); - - -!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}]); -//# sourceMappingURL=amazon-connect-websocket-manager.js.map - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - connect.core = {}; - connect.core.initialized = false; - connect.version = "1.7.5"; - connect.DEFAULT_BATCH_SIZE = 500; - - var CCP_SYN_TIMEOUT = 1000; // 1 sec - var CCP_ACK_TIMEOUT = 3000; // 3 sec - var CCP_LOAD_TIMEOUT = 5000; // 5 sec - var CCP_IFRAME_REFRESH_INTERVAL = 5000; // 5 sec - - var LEGACY_LOGIN_URL_PATTERN = "https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}"; - var CLIENT_ID_MAP = { - "us-east-1": "06919f4fd8ed324e" + /** + * Remove all objects from all log entries. + */ + Logger.prototype.clearObjects = function () { + for (var x = 0; x < this._logs.length; x++) { + if (this._logs[x].objects) { + delete this._logs[x].objects; + } + } }; - - var AUTHORIZE_ENDPOINT = "/auth/authorize"; - var LEGACY_AUTHORIZE_ENDPOINT = "/connect/auth/authorize"; - var AUTHORIZE_RETRY_INTERVAL = 2000; - var AUTHORIZE_MAX_RETRY = 5; - - var LEGACY_WHITELISTED_ORIGINS_ENDPOINT = "/connect/whitelisted-origins"; - var WHITELISTED_ORIGINS_ENDPOINT = "/whitelisted-origins"; - var WHITELISTED_ORIGINS_RETRY_INTERVAL = 2000; - var WHITELISTED_ORIGINS_MAX_RETRY = 5; - connect.numberOfConnectedCCPs = 0; + /** + * Remove all exception stack traces from the log entries. + */ + Logger.prototype.clearExceptions = function () { + for (var x = 0; x < this._logs.length; x++) { + if (this._logs[x].exception) { + delete this._logs[x].exception; + } + } + }; + Logger.prototype.trace = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.TRACE, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.debug = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.DEBUG, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.info = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.INFO, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.log = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.LOG, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.test = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.TEST, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.warn = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.WARN, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.error = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.critical = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); + }; /** - * @deprecated - * This function was only meant for internal use. - * The name is misleading for what it should do. - * Internally we have replaced its usage with `getLoginUrl`. + * Create a string representation of the logger contents. */ - var createLoginUrl = function (params) { - var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; - connect.assertNotNull(redirect); - - if (params.loginUrl) { - return params.loginUrl - } else if (params.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."); - return LEGACY_LOGIN_URL_PATTERN - .replace("{alias}", params.alias) - .replace("{client_id}", CLIENT_ID_MAP["us-east-1"]) - .replace("{redirect}", global.encodeURIComponent( - redirect)); - } else { - return params.ccpUrl; + Logger.prototype.toString = function () { + var lines = []; + for (var x = 0; x < this._logs.length; x++) { + lines.push(this._logs[x].toString()); } + return lines.join("\n"); }; /** - * Replaces `createLoginUrl`, as that function's name was misleading. - * The `params.alias` parameter is deprecated. Please refrain from using it. + * Download/Archive logs to a file, + * By default, it returns all logs. + * To filter logs by the minimum log level set by setLogLevel or the default set in _logLevel, + * pass in filterByLogLevel to true in options + * + * @param options download options [Object|String]. + * - of type Object: + * { logName: 'my-log-name', + * filterByLogLevel: false, //download all logs + * } + * - of type String (for backward compatibility), the file's name */ - var getLoginUrl = function (params) { - var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; - connect.assertNotNull(redirect); - if (params.loginUrl) { - return params.loginUrl - } else if (params.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."); - return LEGACY_LOGIN_URL_PATTERN - .replace("{alias}", params.alias) - .replace("{client_id}", CLIENT_ID_MAP["us-east-1"]) - .replace("{redirect}", global.encodeURIComponent( - redirect)); - } else { - return params.ccpUrl; + Logger.prototype.download = function (options) { + var logName = 'agent-log'; + var filterByLogLevel = false; + if (_typeof(options) === 'object') { + logName = options.logName || logName; + filterByLogLevel = options.filterByLogLevel || filterByLogLevel; + } else if (typeof options === 'string') { + logName = options || logName; + } + var self = this; + var logs = this._rolledLogs.concat(this._logs); + if (filterByLogLevel) { + logs = logs.filter(function (entry) { + return LogLevelOrder[entry.level] >= self._logLevel; + }); } + var logBlob = new global.Blob([JSON.stringify(logs, undefined, 4)], ['text/plain']); + var downloadLink = document.createElement('a'); + var logName = logName || 'agent-log'; + downloadLink.href = global.URL.createObjectURL(logBlob); + downloadLink.download = logName + '.txt'; + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); }; - - /**------------------------------------------------------------------------- - * Returns scheme://host:port for a given url - */ - function sanitizeDomain(url) { - var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/ig); - return domain.length ? domain[0] : ""; - } - - /**------------------------------------------------------------------------- - * Print a warning message if the Connect core is not initialized. - */ - connect.core.checkNotInitialized = function () { - if (connect.core.initialized) { - var log = connect.getLog(); - log.warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer(); + Logger.prototype.scheduleUpstreamLogPush = function (conduit) { + if (!connect.upstreamLogPushScheduled) { + connect.upstreamLogPushScheduled = true; + /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to LARS*/ + global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); } }; - - /**------------------------------------------------------------------------- - * Basic Connect client initialization. - * Should be used only by the API Shared Worker. - */ - connect.core.init = function (params) { - connect.core.eventBus = new connect.EventBus(); - connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); - connect.core.initClient(params); - connect.core.initAgentAppClient(params); - connect.core.initialized = true; + Logger.prototype.reportMasterLogsUpStream = function (conduit) { + var logsToPush = this._logsToPush.slice(); + this._logsToPush = []; + connect.ifMaster(connect.MasterTopics.SEND_LOGS, function () { + if (logsToPush.length > 0) { + conduit.sendUpstream(connect.EventType.SEND_LOGS, logsToPush); + } + }); }; - - /**------------------------------------------------------------------------- - * Initialized AWS client - * Should be used by Shared Worker to update AWS client with new credentials - * after refreshed authentication. - */ - connect.core.initClient = function (params) { - connect.assertNotNull(params, 'params'); - - var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); - var region = connect.assertNotNull(params.region, 'params.region'); - var endpoint = params.endpoint || null; - - connect.core.client = new connect.AWSClient(authToken, region, endpoint); + Logger.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush = function (conduit) { + global.setInterval(connect.hitch(this, this.pushOuterContextCCPserverBoundLogsUpstream, conduit), 1000); + }; + Logger.prototype.scheduleUpstreamOuterContextCCPLogsPush = function (conduit) { + global.setInterval(connect.hitch(this, this.pushOuterContextCCPLogsUpstream, conduit), 1000); + }; + Logger.prototype.pushOuterContextCCPserverBoundLogsUpstream = function (conduit) { + if (this._serverBoundInternalLogs.length > 0) { + for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { + this._serverBoundInternalLogs[i].text = this._serverBoundInternalLogs[i].text; + } + conduit.sendUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs); + this._serverBoundInternalLogs = []; + } + }; + Logger.prototype.pushOuterContextCCPLogsUpstream = function (conduit) { + for (var i = this._startLogIndexToPush; i < this._logs.length; i++) { + if (this._logs[i].loggerId !== this._loggerId) { + continue; + } + conduit.sendUpstream(connect.EventType.LOG, this._logs[i]); + } + this._startLogIndexToPush = this._logs.length; + }; + Logger.prototype.getLoggerId = function () { + return this._loggerId; + }; + Logger.prototype.scheduleDownstreamClientSideLogsPush = function () { + global.setInterval(connect.hitch(this, this.pushClientSideLogsDownstream), LOGS_REPORT_INTERVAL_MILLIS); }; + Logger.prototype.pushClientSideLogsDownstream = function () { + var logs = []; - /**------------------------------------------------------------------------- - * Initialized AgentApp client - * Should be used by Shared Worker to update AgentApp client with new credentials - * after refreshed authentication. - */ - connect.core.initAgentAppClient = function (params) { - connect.assertNotNull(params, 'params'); - var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); - var authCookieName = connect.assertNotNull(params.authCookieName, 'params.authCookieName'); - var endpoint = connect.assertNotNull(params.agentAppEndpoint, 'params.agentAppEndpoint'); - - connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); + // We do not send a request if we have less than 50 records so that we minimize the number of + // requests per second. + // 500 is the max we accept on the server. + // We chose 500 because this is the limit imposed by Firehose for a put batch request + if (this._serverBoundInternalLogs.length < 50) { + return; + } else if (this._serverBoundInternalLogs.length > 500) { + logs = this._serverBoundInternalLogs.splice(0, 500); + } else { + logs = this._serverBoundInternalLogs; + this._serverBoundInternalLogs = []; + } + connect.publishClientSideLogs(logs); }; - - /**------------------------------------------------------------------------- - * Uninitialize Connect. - */ - connect.core.terminate = function () { - connect.core.client = new connect.NullClient(); - connect.core.agentAppClient = new connect.NullClient(); - connect.core.masterClient = new connect.NullClient(); - var bus = connect.core.getEventBus(); - if (bus) bus.unsubscribeAll(); - connect.core.bus = new connect.EventBus(); - connect.core.agentDataProvider = null; - connect.core.softphoneManager = null; - connect.core.upstream = null; - connect.core.keepaliveManager = null; - connect.agent.initialized = false; - connect.core.initialized = false; + var DownstreamConduitLogger = function DownstreamConduitLogger(conduit) { + Logger.call(this); + this.conduit = conduit; + global.setInterval(connect.hitch(this, this._pushLogsDownstream), DownstreamConduitLogger.LOG_PUSH_INTERVAL); + + // Disable log rolling, we will purge our own logs once they have + // been pushed downstream. + global.clearInterval(this._logRollTimer); + this._logRollTimer = null; + }; + // How frequently logs should be collected and delivered downstream. + DownstreamConduitLogger.LOG_PUSH_INTERVAL = 1000; + DownstreamConduitLogger.prototype = Object.create(Logger.prototype); + DownstreamConduitLogger.prototype.constructor = DownstreamConduitLogger; + DownstreamConduitLogger.prototype.pushLogsDownstream = function (logs) { + var self = this; + logs.forEach(function (log) { + self.conduit.sendDownstream(connect.EventType.LOG, log); + }); + }; + DownstreamConduitLogger.prototype._pushLogsDownstream = function () { + var self = this; + this._logs.forEach(function (log) { + self.conduit.sendDownstream(connect.EventType.LOG, log); + }); + this._logs = []; + for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { + this.conduit.sendDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs[i]); + } + this._serverBoundInternalLogs = []; }; - - /**------------------------------------------------------------------------- - * Setup the SoftphoneManager to be initialized when the agent - * is determined to have softphone enabled. + + /** + * Wrap a function with try catch block */ - connect.core.softphoneUserMediaStream = null; - - connect.core.getSoftphoneUserMediaStream = function () { - return connect.core.softphoneUserMediaStream; + var tryCatchWrapperMethod = function tryCatchWrapperMethod(fn) { + var wrappedfunction = function wrappedfunction() { + try { + return fn.apply(this, arguments); + } catch (e) { + // Since this wraps Logger class, we can only print it in the console and eat it. + CONSOLE_LOGGER_MAP.ERROR(e); + } + }; + return wrappedfunction; }; - - connect.core.setSoftphoneUserMediaStream = function (stream) { - connect.core.softphoneUserMediaStream = stream; + /** + * This is a wrapper method to wrap each function + * in an object with try catch block. + */ + var tryCatchWrapperObject = function tryCatchWrapperObject(obj) { + for (var method in obj) { + if (typeof obj[method] === 'function') { + obj[method] = tryCatchWrapperMethod(obj[method]); + } + } }; - - connect.core.initRingtoneEngines = function (params) { - connect.assertNotNull(params, "params"); - - var setupRingtoneEngines = function (ringtoneSettings) { - connect.assertNotNull(ringtoneSettings, "ringtoneSettings"); - connect.assertNotNull(ringtoneSettings.voice, "ringtoneSettings.voice"); - connect.assertTrue(ringtoneSettings.voice.ringtoneUrl || ringtoneSettings.voice.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"); - connect.assertNotNull(ringtoneSettings.queue_callback, "ringtoneSettings.queue_callback"); - connect.assertTrue(ringtoneSettings.queue_callback.ringtoneUrl || ringtoneSettings.queue_callback.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"); - - connect.core.ringtoneEngines = {}; - - connect.agent(function (agent) { - agent.onRefresh(function () { - connect.ifMaster(connect.MasterTopics.RINGTONE, function () { - if (!ringtoneSettings.voice.disabled && !connect.core.ringtoneEngines.voice) { - connect.core.ringtoneEngines.voice = - new connect.VoiceRingtoneEngine(ringtoneSettings.voice); - connect.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer(); - } - - if (!ringtoneSettings.chat.disabled && !connect.core.ringtoneEngines.chat) { - connect.core.ringtoneEngines.chat = - new connect.ChatRingtoneEngine(ringtoneSettings.chat); - connect.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer(); - } - - if (!ringtoneSettings.task.disabled && !connect.core.ringtoneEngines.task) { - connect.core.ringtoneEngines.task = - new connect.TaskRingtoneEngine(ringtoneSettings.task); - connect.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer(); - } - - if (!ringtoneSettings.queue_callback.disabled && !connect.core.ringtoneEngines.queue_callback) { - connect.core.ringtoneEngines.queue_callback = - new connect.QueueCallbackRingtoneEngine(ringtoneSettings.queue_callback); - connect.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer(); - } - }); - }); + + /** Create the singleton logger instance. */ + connect.rootLogger = new Logger(); + tryCatchWrapperObject(connect.rootLogger); + + /** Fetch the singleton logger instance. */ + var getLog = function getLog() { + return connect.rootLogger; + }; + connect = connect || {}; + connect.getLog = getLog; + connect.LogEntry = LogEntry; + connect.Logger = Logger; + connect.LogLevel = LogLevel; + connect.LogComponent = LogComponent; + connect.DownstreamConduitLogger = DownstreamConduitLogger; +})(); + +/***/ }), + +/***/ 158: +/***/ (() => { + +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + connect.ChatMediaController = function (mediaInfo, metadata) { + var logger = connect.getLog(); + var logComponent = connect.LogComponent.CHAT; + var createMediaInstance = function createMediaInstance() { + publishTelemetryEvent("Chat media controller init", mediaInfo.contactId); + logger.info(logComponent, "Chat media controller init").withObject(mediaInfo).sendInternalLogToServer(); + connect.ChatSession.setGlobalConfig({ + loggerConfig: { + logger: logger + }, + region: metadata.region }); - handleRingerDeviceChange(); + /** Could be also CUSTOMER - For now we are creating only Agent connection media object */ + var controller = connect.ChatSession.create({ + chatDetails: mediaInfo, + type: "AGENT", + websocketManager: connect.core.getWebSocketManager() + }); + trackChatConnectionStatus(controller); + return controller.connect().then(function (data) { + logger.info(logComponent, "Chat Session Successfully established for contactId %s", mediaInfo.contactId).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session Successfully established", mediaInfo.contactId); + return controller; + })["catch"](function (error) { + logger.error(logComponent, "Chat Session establishement failed for contact %s", mediaInfo.contactId).withException(error).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); + throw error; + }); }; - - var mergeParams = function (params, otherParams) { - // For backwards compatibility: support pulling disabled flag and ringtoneUrl - // from softphone config if it exists from downstream into the ringtone config. - params.ringtone = params.ringtone || {}; - params.ringtone.voice = params.ringtone.voice || {}; - params.ringtone.queue_callback = params.ringtone.queue_callback || {}; - params.ringtone.chat = params.ringtone.chat || { disabled: true }; - params.ringtone.task = params.ringtone.task || { disabled: true }; - - if (otherParams.softphone) { - if (otherParams.softphone.disableRingtone) { - params.ringtone.voice.disabled = true; - params.ringtone.queue_callback.disabled = true; - } - - if (otherParams.softphone.ringtoneUrl) { - params.ringtone.voice.ringtoneUrl = otherParams.softphone.ringtoneUrl; - params.ringtone.queue_callback.ringtoneUrl = otherParams.softphone.ringtoneUrl; - } - } - - if (otherParams.chat) { - if (otherParams.chat.disableRingtone) { - params.ringtone.chat.disabled = true; - } - - if (otherParams.chat.ringtoneUrl) { - params.ringtone.chat.ringtoneUrl = otherParams.chat.ringtoneUrl; - } - } - - // Merge in ringtone settings from downstream. - if (otherParams.ringtone) { - params.ringtone.voice = connect.merge(params.ringtone.voice, - otherParams.ringtone.voice || {}); - params.ringtone.queue_callback = connect.merge(params.ringtone.queue_callback, - otherParams.ringtone.voice || {}); - params.ringtone.chat = connect.merge(params.ringtone.chat, - otherParams.ringtone.chat || {}); - } + var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { + connect.publishMetric({ + name: eventName, + contactId: mediaInfo.contactId, + data: data || mediaInfo + }); }; - - // Merge params from params.softphone and params.chat into params.ringtone - // for embedded and non-embedded use cases so that defaults are picked up. - mergeParams(params, params); - - if (connect.isFramed()) { - // If the CCP is in a frame, wait for configuration from downstream. - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.CONFIGURE, function (data) { - this.unsubscribe(); - // Merge all params from data into params for any overridden - // values in either legacy "softphone" or "ringtone" settings. - mergeParams(params, data); - setupRingtoneEngines(params.ringtone); + var trackChatConnectionStatus = function trackChatConnectionStatus(controller) { + controller.onConnectionBroken(function (data) { + logger.error(logComponent, "Chat Session connection broken").withException(data).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session connection broken", data); }); - - } else { - setupRingtoneEngines(params.ringtone); - } + controller.onConnectionEstablished(function (data) { + logger.info(logComponent, "Chat Session connection established").withObject(data).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session connection established", data); + }); + }; + return { + get: function get() { + return createMediaInstance(); + } + }; }; +})(); - var handleRingerDeviceChange = function() { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.ConfigurationEvents.SET_RINGER_DEVICE, setRingerDevice); - } +/***/ }), - var setRingerDevice = function (data){ - if(connect.keys(connect.core.ringtoneEngines).length === 0 || !data || !data.deviceId){ - return; - } - var deviceId = data.deviceId; - for (var ringtoneType in connect.core.ringtoneEngines) { - connect.core.ringtoneEngines[ringtoneType].setOutputDevice(deviceId); - } +/***/ 7: +/***/ (() => { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, - data: { deviceId: deviceId } - }); - } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ - connect.core.initSoftphoneManager = function (paramsIn) { - connect.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer(); - var params = paramsIn || {}; - - var competeForMasterOnAgentUpdate = function (softphoneParamsIn) { - var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); - connect.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(); - connect.agent(function (agent) { - if (!agent.getChannelConcurrency(connect.ChannelType.VOICE)) { - return; +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + connect.MediaFactory = function (params) { + /** controller holder */ + var mediaControllers = {}; + var toBeDestroyed = new Set(); + var logger = connect.getLog(); + var logComponent = connect.LogComponent.CHAT; + var metadata = connect.merge({}, params) || {}; + metadata.region = metadata.region || "us-west-2"; // Default it to us-west-2 + + var getMediaController = function getMediaController(connectionObj) { + var connectionId = connectionObj.getConnectionId(); + var mediaInfo = connectionObj.getMediaInfo(); + /** if we do not have the media info then just reject the request */ + if (!mediaInfo) { + logger.error(logComponent, "Media info does not exist for a media type %s", connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); + return Promise.reject("Media info does not exist for this connection"); + } + if (!mediaControllers[connectionId]) { + logger.info(logComponent, "media controller of type %s init", connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); + switch (connectionObj.getMediaType()) { + case connect.MediaType.CHAT: + return mediaControllers[connectionId] = new connect.ChatMediaController(connectionObj.getMediaInfo(), metadata).get(); + case connect.MediaType.SOFTPHONE: + return mediaControllers[connectionId] = new connect.SoftphoneMediaController(connectionObj.getMediaInfo()).get(); + case connect.MediaType.TASK: + return mediaControllers[connectionId] = new connect.TaskMediaController(connectionObj.getMediaInfo()).get(); + default: + logger.error(logComponent, "Unrecognized media type %s ", connectionObj.getMediaType()).sendInternalLogToServer(); + return Promise.reject(); } - agent.onRefresh(function () { - var sub = this; - connect.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(); - - connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { - connect.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(); - if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { - // Become master to send logs, since we need logs from softphone tab. - connect.becomeMaster(connect.MasterTopics.SEND_LOGS); - connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); - sub.unsubscribe(); - } - }); - }); - }); + } else { + return mediaControllers[connectionId]; + } + }; + + /** Check all the active states for the connection */ + var ifConnectionActive = function ifConnectionActive(connectionObj) { + return connectionObj.isActive(); + }; + var get = function get(connectionObj) { + if (ifConnectionActive(connectionObj)) { + return getMediaController(connectionObj); + } else { + destroy(connectionObj.getConnectionId()); + return Promise.reject("Media Controller is no longer available for this connection"); + } }; - - /** - * If the window is framed, we need to wait for a CONFIGURE message from - * downstream before we try to initialize, unless params.allowFramedSoftphone is true. - */ - if (connect.isFramed() && !params.allowFramedSoftphone) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.CONFIGURE, function (data) { - connect.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(); - if (data.softphone && data.softphone.allowFramedSoftphone) { - this.unsubscribe(); - competeForMasterOnAgentUpdate(data.softphone); - - } - setupEventListenersForMultiTabUseInFirefox(data.softphone); - }); - } else { - competeForMasterOnAgentUpdate(params); - setupEventListenersForMultiTabUseInFirefox(params); - } - - connect.agent(function (agent) { - // Sync mute across all tabs - if (agent.isSoftphoneEnabled() && agent.getChannelConcurrency(connect.ChannelType.VOICE)) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, - { - event: connect.EventType.MUTE - }); + var destroy = function destroy(connectionId) { + if (mediaControllers[connectionId] && !toBeDestroyed.has(connectionId)) { + logger.info(logComponent, "Destroying mediaController for %s", connectionId); + toBeDestroyed.add(connectionId); + mediaControllers[connectionId].then(function () { + if (typeof controller.cleanUp === "function") controller.cleanUp(); + delete mediaControllers[connectionId]; + toBeDestroyed["delete"](connectionId); + })["catch"](function () { + delete mediaControllers[connectionId]; + toBeDestroyed["delete"](connectionId); + }); } - }); + }; + return { + get: get, + destroy: destroy + }; + }; +})(); - function setupEventListenersForMultiTabUseInFirefox(softphoneParamsIn) { - var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); +/***/ }), - // keep the softphone params for external use - connect.core.softphoneParams = softphoneParams; +/***/ 6: +/***/ (() => { - if (connect.isFirefoxBrowser()) { - // In Firefox, when a tab takes over another tab's softphone primary, - // the previous primary tab should delete sofphone manager and stop microphone - connect.core.getUpstream().onUpstream(connect.EventType.MASTER_RESPONSE, function (res) { - if (res.data && res.data.topic === connect.MasterTopics.SOFTPHONE && res.data.takeOver && (res.data.masterId !== connect.core.portStreamId)) { - if (connect.core.softphoneManager) { - connect.core.softphoneManager.onInitContactSub.unsubscribe(); - delete connect.core.softphoneManager; - } - var userMediaStream = connect.core.getSoftphoneUserMediaStream(); - if (userMediaStream) { - userMediaStream.getTracks().forEach(function(track) { track.stop(); }); - connect.core.setSoftphoneUserMediaStream(null); - } - } - }); +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ - // In Firefox, when multiple tabs are open, - // webrtc session is not started until READY_TO_START_SESSION event is triggered - connect.core.getEventBus().subscribe(connect.ConnectionEvents.READY_TO_START_SESSION, function () { - connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { - if (connect.core.softphoneManager) { - connect.core.softphoneManager.startSession(); - } - }, function () { - connect.becomeMaster(connect.MasterTopics.SOFTPHONE, function () { - connect.agent(function (agent) { - if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { - connect.becomeMaster(connect.MasterTopics.SEND_LOGS); - connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); - connect.core.softphoneManager.startSession(); - } - }); - }); - }); - }); +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; - // handling outbound-call and auto-accept cases for pending session - connect.contact(function (c) { - connect.agent(function (agent) { - c.onRefresh(function (contact) { - if ( - connect.hasOtherConnectedCCPs() && - document.visibilityState === 'visible' && - (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING) - ) { - var isOutBoundCall = contact.isSoftphoneCall() && !contact.isInbound(); - var isAutoAcceptEnabled = contact.isSoftphoneCall() && agent.getConfiguration().softphoneAutoAccept; - var isQueuedCallback = contact.getType() === connect.ContactType.QUEUE_CALLBACK; - if (isOutBoundCall || isAutoAcceptEnabled || isQueuedCallback) { - connect.core.triggerReadyToStartSessionEvent(); - } - } - }); - }); - }); + // TODO move softphone implementations here - Wil do this for GA + connect.SoftphoneMediaController = function (mediaInfo) { + return { + get: function get() { + return Promise.resolve(mediaInfo); } - } + }; }; +})(); - // trigger READY_TO_START_SESSION event in a context with Softphone Manager - // internal use only - connect.core.triggerReadyToStartSessionEvent = function () { - var allowFramedSoftphone = connect.core.softphoneParams && connect.core.softphoneParams.allowFramedSoftphone; - if (connect.isCCP()) { - if (allowFramedSoftphone) { - // the event is triggered in this iframed CCP context - connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); - } else { - if (connect.isFramed()) { - // if this is an iframed CCP, the event is send to downstream (CRM) - connect.core.getUpstream().sendDownstream(connect.ConnectionEvents.READY_TO_START_SESSION); - } else { - // if this is a standalone CCP, trigger this event in this CCP context - connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); - } - } - } else { - if (allowFramedSoftphone) { - // the event is send to the upstream (iframed CCP) - connect.core.getUpstream().sendUpstream(connect.ConnectionEvents.READY_TO_START_SESSION); - } else { - // the event is triggered in this CRM context - connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); - } - } - }; +/***/ }), - connect.core.initPageOptions = function (params) { - connect.assertNotNull(params, "params"); - if (connect.isFramed()) { - // If the CCP is in a frame, wait for configuration from downstream. - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.CONFIGURE, function (data) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, - { - event: connect.ConfigurationEvents.CONFIGURE, - data: data - }); +/***/ 487: +/***/ (() => { + +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + connect.TaskMediaController = function (mediaInfo) { + var logger = connect.getLog(); + var logComponent = connect.LogComponent.TASK; + var createMediaInstance = function createMediaInstance() { + publishTelemetryEvent("Task media controller init", mediaInfo.contactId); + logger.info(logComponent, "Task media controller init").withObject(mediaInfo); + var controller = connect.TaskSession.create({ + contactId: mediaInfo.contactId, + initialContactId: mediaInfo.initialContactId, + websocketManager: connect.core.getWebSocketManager() }); - // Listen for iframe media devices request from CRM - bus.subscribe(connect.EventType.MEDIA_DEVICE_REQUEST, function () { - function sendDevices(devices) { - connect.core.getUpstream().sendDownstream(connect.EventType.MEDIA_DEVICE_RESPONSE, devices); - } - if (navigator && navigator.mediaDevices) { - navigator.mediaDevices.enumerateDevices() - .then(function (devicesIn) { - devices = devicesIn || []; - devices = devices.map(function(d) { return d.toJSON() }); - sendDevices(devices); - }) - .catch(function (err) { - sendDevices({error: err.message}); - }); - } else { - sendDevices({error: "No navigator or navigator.mediaDevices object found"}); - } + trackTaskConnectionStatus(controller); + return controller.connect().then(function () { + logger.info(logComponent, "Task Session Successfully established for contactId %s", mediaInfo.contactId); + publishTelemetryEvent("Task Session Successfully established", mediaInfo.contactId); + return controller; + })["catch"](function (error) { + logger.error(logComponent, "Task Session establishement failed for contact %s", mediaInfo.contactId).withException(error); + publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); + throw error; }); - } + }; + var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { + connect.publishMetric({ + name: eventName, + contactId: mediaInfo.contactId, + data: data || mediaInfo + }); + }; + var trackTaskConnectionStatus = function trackTaskConnectionStatus(controller) { + controller.onConnectionBroken(function (data) { + logger.error(logComponent, "Task Session connection broken").withException(data); + publishTelemetryEvent("Task Session connection broken", data); + }); + controller.onConnectionEstablished(function (data) { + logger.info(logComponent, "Task Session connection established").withObject(data); + publishTelemetryEvent("Task Session connection established", data); + }); + }; + return { + get: function get() { + return createMediaInstance(); + } + }; }; +})(); - /**------------------------------------------------------------------------- - * Get the list of media devices from iframed CCP - * Timeout for the request is passed an an optional argument - * The default timeout is 1000ms - */ - connect.core.getFrameMediaDevices = function (timeoutIn) { - var sub = null; - var timeout = timeoutIn || 1000; - var timeoutPromise = new Promise(function (resolve, reject) { - setTimeout(function () { - reject(new Error("Timeout exceeded")); - }, timeout); - }); - var mediaDevicesPromise = new Promise(function (resolve, reject) { - if (connect.isFramed() || connect.isCCP()) { - if (navigator && navigator.mediaDevices) { - navigator.mediaDevices.enumerateDevices() - .then(function (devicesIn) { - devices = devicesIn || []; - devices = devices.map(function (d) { return d.toJSON() }); - resolve(devices); - }); - } else { - reject(new Error("No navigator or navigator.mediaDevices object found")); - } - } else { - var bus = connect.core.getEventBus(); - sub = bus.subscribe(connect.EventType.MEDIA_DEVICE_RESPONSE, function (data) { - if (data.error) { - reject(new Error(data.error)); - } else { - resolve(data); - } - }); - connect.core.getUpstream().sendUpstream(connect.EventType.MEDIA_DEVICE_REQUEST); - } - }) - return Promise.race([mediaDevicesPromise, timeoutPromise]) - .finally(function () { - if (sub) { - sub.unsubscribe(); - } - }); - } +/***/ }), - //Internal use only. - connect.core.authorize = function (endpoint) { - var options = { - credentials: 'include' +/***/ 743: +/***/ (() => { + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/** + * Module which gets used for the Request storage access + * Exposes init, hasAccess, request and onRequest methods. + * utilizes core post message technique to communicate back to the parent which invokes the storage access + * + * @usage - Used by initCCP and customer can make use of onRequest callbacks , this will be called even before agent login + * + * Example - + * connect.storageAccess.onRequest({ + * onInit(){}, + * onDeny(){}, + * onGrant(){} + * }); + * + * There are 4 lifecycle methods in the storage access check + * + * a) Request - StreamJS would request for storage access check to the embedded Connect hosted storage access banner + * b) Init - Storage access banner inits the access check and sends back the current access state with hasAccess set to true or false + * this is the step where we show the actual RSA banner to agents and for custom use cases hidden container will be shown + * c) Grant [optional] - Executes when Agent/user accepts storage access or already given grant + * d) Deny [optional] - Executes when Agent/user deny the storage access/ + * + * In a positive flow - we should expect Request, Init, Grant and negative Request, Init, Deny + * + * Chrome Implementation of RSA API can be found here - https://github.com/cfredric/chrome-storage-access-api + */ +(function () { + var global = this || globalThis; + var connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + var requestStorageAccessPath = "/request-storage-access"; + /** + * Configurable options exposed via initCCP + * By default canRequest will be set to false to make this as a explicit opt in + */ + var defaultStorageAccessParams = { + /* Config which controls the opt out/in - we expect customers to explicitely opt in. */ + canRequest: true, + /* ["custom", "default"] - decides the rsa page view */ + mode: "default", + custom: { + /** + * Only applicable for custom type RSA page and these messages should be localized by customers + * + * title: 'Cookie Notice', + * header: 'Please provide access' + * + */ + } + }; + var storageParams = {}; + var originalCCPUrl = ""; + var rsaContainer = null; + var onGrantCallbackInvoked = false; + var requesthandlerUnsubscriber; + var storageAccessEvents = { + INIT: "storageAccess::init", + GRANTED: "storageAccess::granted", + DENIED: "storageAccess::denied", + REQUEST: "storageAccess::request" + }; + var initStorageParams = function initStorageParams() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + params.custom = params.custom || {}; + storageParams = _objectSpread(_objectSpread(_objectSpread({}, defaultStorageAccessParams), params), {}, { + custom: _objectSpread(_objectSpread({}, defaultStorageAccessParams.custom), params.custom) + }); + storageParams.canRequest = !(storageParams.canRequest === "false" || storageParams.canRequest === false); + }; + var resetStorageAccessState = function resetStorageAccessState() { + storageParams = {}; + originalCCPUrl = ""; + rsaContainer = null; + }; + + /** + * Handle display none/block properties for the RTSA container, if customer have different settings like height, opacity, positions etc configured they are encouraged to use + * onRequest Callback handle to reset the same. + * */ + var getRSAContainer = function getRSAContainer() { + return { + show: function show() { + rsaContainer.style.display = "block"; + }, + hide: function hide() { + rsaContainer.style.display = "none"; + } }; + }; - var authorizeEndpoint = endpoint; - if (!authorizeEndpoint) { - authorizeEndpoint = connect.core.isLegacyDomain() - ? LEGACY_AUTHORIZE_ENDPOINT - : AUTHORIZE_ENDPOINT; - } - return connect.fetch(authorizeEndpoint, options, AUTHORIZE_RETRY_INTERVAL, AUTHORIZE_MAX_RETRY); + /** + * Custom Mode will show minimalistic UI - without any Connect references or Connect headers + * This will allow fully Custom CCPs to use banner and use minimal real estate to show the storage access Content + * */ + var isCustomRequestAccessMode = function isCustomRequestAccessMode() { + return storageParams && storageParams.mode !== "default"; + }; + var isConnectDomain = function isConnectDomain(origin) { + return origin.match(/.connect.aws.a2z.com|.my.connect.aws|.awsapps.com/); }; - + /** - * @deprecated - * This used to be used internally, but is no longer needed. + * Given the URL, this method generates the prefixed connect domain request storage access URL + * @param {string} url + * @returns {string} */ - connect.core.verifyDomainAccess = function (authToken, endpoint) { - connect.getLog().warn("This API will be deprecated in the next major version release"); - if (!connect.isFramed()) { - return Promise.resolve(); - } - var options = { - headers: { - 'X-Amz-Bearer': authToken + var getRsaUrlWithprefix = function getRsaUrlWithprefix(url) { + var _URL = new URL(url), + origin = _URL.origin, + pathname = _URL.pathname; + if (origin.match(/.awsapps.com/)) { + var prefix = "connect"; + if (pathname.startsWith("/connect-gamma")) { + prefix = "connect-gamma"; } - }; - var whitelistedOriginsEndpoint = null; - if (endpoint){ - whitelistedOriginsEndpoint = endpoint; - } - else { - whitelistedOriginsEndpoint = connect.core.isLegacyDomain() - ? LEGACY_WHITELISTED_ORIGINS_ENDPOINT - : WHITELISTED_ORIGINS_ENDPOINT; + return "".concat(origin, "/").concat(prefix).concat(requestStorageAccessPath); + } else { + return "".concat(origin).concat(requestStorageAccessPath); } - - return connect.fetch(whitelistedOriginsEndpoint, options, WHITELISTED_ORIGINS_RETRY_INTERVAL, WHITELISTED_ORIGINS_MAX_RETRY).then(function (response) { - var topDomain = sanitizeDomain(window.document.referrer); - var isAllowed = response.whitelistedOrigins.some(function (origin) { - return topDomain === sanitizeDomain(origin); - }); - return isAllowed ? Promise.resolve() : Promise.reject(); - }); + }; + var isLocalhost = function isLocalhost(url) { + return url.match(/^https?:\/\/localhost/); }; - /**------------------------------------------------------------------------- - * Returns true if this window's href is on the legacy connect domain. - * Only useful for internal use. + /** + * Fetches the landat path for request storage access page to navigate. This is typically CCP path or channel view + * @returns {string} */ - connect.core.isLegacyDomain = function(url) { - url = url || window.location.href; - return url.includes('.awsapps.com'); - } - + var getlandAtPath = function getlandAtPath() { + if (!originalCCPUrl) { + throw new Error("[StorageAccess] [getlandAtPath] Invoke connect.storageAccess.init first"); + } + if (isConnectDomain(originalCCPUrl) || isLocalhost(originalCCPUrl)) { + var _URL2 = new URL(originalCCPUrl), + pathname = _URL2.pathname; + return pathname; + } + return "/connect/ccp-v2"; + }; - /**------------------------------------------------------------------------- - * Initializes Connect by creating or connecting to the API Shared Worker. - * Used only by the CCP + /** + * + * Method which returns the relative request-storage-access page path. + * Validates against localhost and connect domains and returns prefixed path + * @returns {string} + */ + var getRequestStorageAccessUrl = function getRequestStorageAccessUrl() { + // ccpUrl may contain non standard direct SSO URLs in which case we may ask customers to provide instanceUrl as part of storage access params + + if (!originalCCPUrl) { + throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first"); + } + if (isConnectDomain(originalCCPUrl)) { + return getRsaUrlWithprefix(originalCCPUrl); + } else if (isLocalhost(originalCCPUrl)) { + connect.getLog().info("[StorageAccess] [CCP] Local testing"); + return "".concat(originalCCPUrl).concat(requestStorageAccessPath); + } else if (storageParams.instanceUrl && isConnectDomain(storageParams.instanceUrl)) { + connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(storageParams.instanceUrl)); + return getRsaUrlWithprefix(storageParams.instanceUrl); + } else if (storageParams.instanceUrl && isLocalhost(storageParams.instanceUrl)) { + connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"); + return "".concat(storageParams.instanceUrl).concat(requestStorageAccessPath); + } else { + connect.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"); + // FIXME - For test cases to succeed passing original parameter back instead throw an error by fixing all the CCP URL parameters accross the tests. + throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL"); + } + }; + + /** + * Method which allows customers to listen on Storage access request and it's state changes + * @param {Object} consists of callbacks for the onInit, onDeny and onGrants */ - connect.core.initSharedWorker = function (params) { - connect.core.checkNotInitialized(); - if (connect.core.initialized) { - return; + var onRequestHandler = function onRequestHandler(_ref) { + var onInit = _ref.onInit, + onDeny = _ref.onDeny, + onGrant = _ref.onGrant; + function handleUpstreamMessages(_ref2) { + var data = _ref2.data, + source = _ref2.source; + var iframeContainer = connect.core._getCCPIframe(); + if (iframeContainer.contentWindow !== source) { + // disabling the logs for now + // connect.getLog().error('[StorageAccess][onRequestHandler] Request Coming from unknown domain %s', origin); + return false; + } + if (connect.core.initialized) { + window.removeEventListener("message", handleUpstreamMessages); + } + switch (data.event) { + case storageAccessEvents.INIT: + { + connect.getLog().info("[StorageAccess][INIT] message recieved").withObject(data); + if (onInit) { + onInit(data); + } + break; + } + case storageAccessEvents.GRANTED: + { + connect.getLog().info("[StorageAccess][GRANTED] message recieved").withObject(data); + if (onGrant) { + onGrant(data); + } + break; + } + case storageAccessEvents.DENIED: + { + connect.getLog().info("[StorageAccess][DENIED] message recieved").withObject(data); + if (onDeny) { + onDeny(data); + } + break; + } + default: + { + // Make sure to clean up the handler as soon as the access is granted. + if (connect.core.initialized) { + window.removeEventListener("message", handleUpstreamMessages); + } + break; + } + } } - connect.assertNotNull(params, 'params'); - - var sharedWorkerUrl = connect.assertNotNull(params.sharedWorkerUrl, 'params.sharedWorkerUrl'); - var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); - var refreshToken = connect.assertNotNull(params.refreshToken, 'params.refreshToken'); - var authTokenExpiration = connect.assertNotNull(params.authTokenExpiration, 'params.authTokenExpiration'); - var region = connect.assertNotNull(params.region, 'params.region'); - var endpoint = params.endpoint || null; - var authorizeEndpoint = params.authorizeEndpoint; - if (!authorizeEndpoint) { - authorizeEndpoint = connect.core.isLegacyDomain() - ? LEGACY_AUTHORIZE_ENDPOINT - : AUTHORIZE_ENDPOINT; + // do this only if canRequest is set to true + if (storageParams.canRequest) { + window.addEventListener("message", handleUpstreamMessages); } - var agentAppEndpoint = params.agentAppEndpoint || null; - var authCookieName = params.authCookieName || null; - - try { - // Initialize the event bus and agent data providers. - connect.core.eventBus = new connect.EventBus({ logEvents: true }); - connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); - connect.core.mediaFactory = new connect.MediaFactory(params); - - // Create the shared worker and upstream conduit. - var worker = new SharedWorker(sharedWorkerUrl, "ConnectSharedWorker"); - var conduit = new connect.Conduit("ConnectSharedWorkerConduit", - new connect.PortStream(worker.port), - new connect.WindowIOStream(window, parent)); - - // Set the global upstream conduit for external use. - connect.core.upstream = conduit; - connect.core.webSocketProvider = new WebSocketProvider(); - - // Close our port to the shared worker before the window closes. - global.onunload = function () { - conduit.sendUpstream(connect.EventType.CLOSE); - worker.port.close(); - }; - - connect.getLog().scheduleUpstreamLogPush(conduit); - connect.getLog().scheduleDownstreamClientSideLogsPush(); - // Bridge all upstream messages into the event bus. - conduit.onAllUpstream(connect.core.getEventBus().bridge()); - // Pass all upstream messages (from shared worker) downstream (to CCP consumer). - conduit.onAllUpstream(conduit.passDownstream()); - - if (connect.isFramed()) { - // Bridge all downstream messages into the event bus. - conduit.onAllDownstream(connect.core.getEventBus().bridge()); - // Pass all downstream messages (from CCP consumer) upstream (to shared worker). - conduit.onAllDownstream(conduit.passUpstream()); + return { + unsubscribe: function unsubscribe() { + window.removeEventListener("message", handleUpstreamMessages); } - // Send configuration up to the shared worker. - conduit.sendUpstream(connect.EventType.CONFIGURE, { - authToken: authToken, - authTokenExpiration: authTokenExpiration, - endpoint: endpoint, - refreshToken: refreshToken, - region: region, - authorizeEndpoint: authorizeEndpoint, - agentAppEndpoint: agentAppEndpoint, - authCookieName: authCookieName - }); - - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { - connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); - connect.core.initialized = true; - connect.core.portStreamId = data.id; - this.unsubscribe(); - }); - // Add all upstream log entries to our own logger. - conduit.onUpstream(connect.EventType.LOG, function (logEntry) { - if (logEntry.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + }; + }; + + /** + * setupRequestHandlers - method which attaches post message handlers and let the initCCP flow to continue. + * In case of custom CCPs - it also does hide/show the container. + * @param {*} param0 + */ + var setupRequestHandlers = function setupRequestHandlers(_ref3) { + var onGrantCallback = _ref3.onGrant; + if (requesthandlerUnsubscriber) { + requesthandlerUnsubscriber.unsubscribe(); + } + requesthandlerUnsubscriber = onRequestHandler({ + onInit: function onInit(messageData) { + console.log("%c[INIT]", "background:lime; color: black; font-size:large"); + connect.getLog().info("[StorageAccess][onInit] callback executed").withObject(messageData === null || messageData === void 0 ? void 0 : messageData.data); + if (!(messageData !== null && messageData !== void 0 && messageData.data.hasAccess) && isCustomRequestAccessMode()) { + getRSAContainer().show(); } - }); - // Get worker logs - conduit.onUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logEntry) { - connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(logEntry)); - }); - // Get outer context logs - conduit.onDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logs) { - if (connect.isFramed() && Array.isArray(logs)) { - logs.forEach(function (log) { - connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(log)); - }); + }, + onDeny: function onDeny() { + console.log("%c[DENIED]", "background:lime; color: black; font-size:large"); + connect.getLog().info("[StorageAccess][onDeny] callback executed"); + if (isCustomRequestAccessMode()) { + getRSAContainer().show(); } - }); - // Get log from outer context - conduit.onDownstream(connect.EventType.LOG, function (log) { - if (connect.isFramed() && log.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(log)); + }, + onGrant: function onGrant() { + console.log("%c[Granted]", "background:lime; color: black; font-size:large"); + connect.getLog().info("[StorageAccess][onGrant] callback executed"); + if (isCustomRequestAccessMode()) { + getRSAContainer().hide(); } - }); - // Reload the page if the shared worker detects an API auth failure. - conduit.onUpstream(connect.EventType.AUTH_FAIL, function (logEntry) { - location.reload(); - }); + // Invoke onGrantCallback only once as it setsup initCCP callbacks and events + if (!onGrantCallbackInvoked) { + onGrantCallback(); + onGrantCallbackInvoked = true; + } + } + }); + }; + connect.storageAccess = Object.freeze({ + /** + * Checks wther user has opted out for storage Access checks or not + * @returns {boolean} + */ + canRequest: function canRequest() { + return storageParams.canRequest; + }, + /** + * Mainly used by Tests, by default storage access is enabled for all + */ + optOutFromRequestAccess: function optOutFromRequestAccess() { + defaultStorageAccessParams.canRequest = false; + }, + /** + * Mainly used by Tests + */ + optInForRequestAccess: function optInForRequestAccess() { + defaultStorageAccessParams.canRequest = true; + }, + /** + * Method which inits the Storage Access module with Customer paramters. + * and generates request storage access URL and apply customization to the default paramters + * @param {*} params - storage access params + * @param {*} container - Container where CCP is being shown + * @returns {{canRequest, requestAccessPageurl}} + */ + init: function init(ccpUrl, containerDiv) { + var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + connect.assertNotNull(ccpUrl, "ccpUrl"); + connect.assertNotNull(containerDiv, "container"); + rsaContainer = containerDiv; + originalCCPUrl = ccpUrl; + initStorageParams(params); + connect.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(ccpUrl, " - ").concat(!storageParams.canRequest ? "user has opted out, skipping request storage access" : "Proceeding with requesting storage access")).withObject(storageParams); + }, + setupRequestHandlers: setupRequestHandlers, + getRequestStorageAccessUrl: getRequestStorageAccessUrl, + storageAccessEvents: storageAccessEvents, + resetStorageAccessState: resetStorageAccessState, + getStorageAccessParams: function getStorageAccessParams() { + return storageParams; + }, + onRequest: onRequestHandler, + request: function request() { + var iframeContainer = connect.core._getCCPIframe(); + iframeContainer.contentWindow.postMessage({ + event: storageAccessEvents.REQUEST, + data: _objectSpread(_objectSpread({}, storageParams), {}, { + landat: getlandAtPath() + }) + }, "*"); + } + }); +})(); - connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); - connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); - connect.getLog().info("isFramed: " + connect.isFramed()).sendInternalLogToServer(); - connect.core.upstream.onDownstream(connect.EventType.OUTER_CONTEXT_INFO, function (data) { - var streamsVersion = data.streamsVersion; - connect.getLog().info("StreamsJS Version: " + streamsVersion).sendInternalLogToServer(); - }); +/***/ }), - conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { - connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); - connect.numberOfConnectedCCPs = data.length; - }); +/***/ 555: +/***/ (() => { - connect.core.client = new connect.UpstreamConduitClient(conduit); - connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); - - // Pass the TERMINATE request upstream to the shared worker. - connect.core.getEventBus().subscribe(connect.EventType.TERMINATE, - conduit.passUpstream()); - - // Refresh the page when we receive the TERMINATED response from the - // shared worker. - connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, function () { - window.location.reload(true); +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + var connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + var RingtoneEngineBase = function RingtoneEngineBase(ringtoneConfig) { + var self = this; + this._prevContactId = null; + connect.assertNotNull(ringtoneConfig, "ringtoneConfig"); + if (!ringtoneConfig.ringtoneUrl) { + throw new Error("ringtoneUrl is required!"); + } + if (global.Audio && typeof global.Promise !== "undefined") { + this._playableAudioPromise = new Promise(function (resolve, reject) { + self._audio = new Audio(ringtoneConfig.ringtoneUrl); + self._audio.loop = true; + self._audio.addEventListener("canplay", function () { + self._audioPlayable = true; + resolve(self._audio); + }); }); - - worker.port.start(); + } else { + this._audio = null; + connect.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer(); + } + self._driveRingtone(); + }; + RingtoneEngineBase.prototype._driveRingtone = function () { + throw new Error("Not implemented."); + }; + RingtoneEngineBase.prototype._startRingtone = function (contact) { + if (this._audio) { + this._audio.play()["catch"](function (e) { + this._publishTelemetryEvent("Ringtone Playback Failure", contact); + connect.getLog().error("Ringtone Playback Failure").sendInternalLogToServer(); + }); + this._publishTelemetryEvent("Ringtone Start", contact); + connect.getLog().info("Ringtone Start").sendInternalLogToServer(); + } + }; + RingtoneEngineBase.prototype._stopRingtone = function (contact) { + if (this._audio) { + this._audio.pause(); + this._audio.currentTime = 0; + this._publishTelemetryEvent("Ringtone Stop", contact); + connect.getLog().info("Ringtone Stop").sendInternalLogToServer(); + } + }; - conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { - if (data && data.domainId) { - connect.core.voiceIdDomainId = data.domainId; + /** + * Stop ringtone. + */ + RingtoneEngineBase.prototype.stopRingtone = function () { + this._stopRingtone(); + }; + RingtoneEngineBase.prototype._ringtoneSetup = function (contact) { + var self = this; + connect.ifMaster(connect.MasterTopics.RINGTONE, function () { + self._startRingtone(contact); + self._prevContactId = contact.getContactId(); + contact.onConnected(lily.hitch(self, self._stopRingtone)); + contact.onAccepted(lily.hitch(self, self._stopRingtone)); + contact.onEnded(lily.hitch(self, self._stopRingtone)); + // Just to make sure to stop the ringtone in case of the failures of specific callbacks(onAccepted,onConnected); + contact.onRefresh(function (contact) { + if (contact.getStatus().type !== connect.ContactStatusType.CONNECTING && contact.getStatus().type !== connect.ContactStatusType.INCOMING) { + self._stopRingtone(); } }); - - // try fetching voiceId's domainId once the agent is initialized - connect.agent(function () { - var voiceId = new connect.VoiceId(); - voiceId.getDomainId() - .then(function(domainId) { - connect.getLog().info("voiceId domainId successfully fetched at agent initialization: " + domainId).sendInternalLogToServer(); - }) - .catch(function(err) { - connect.getLog().info("voiceId domainId not fetched at agent initialization").withObject({ err: err }).sendInternalLogToServer(); - }); + }); + }; + RingtoneEngineBase.prototype._publishTelemetryEvent = function (eventName, contact) { + if (contact && contact.getContactId()) { + connect.publishMetric({ + name: eventName, + contactId: contact.getContactId() }); - - // Attempt to get permission to show notifications. - var nm = connect.core.getNotificationManager(); - nm.requestPermission(); - - } catch (e) { - connect.getLog().error("Failed to initialize the API shared worker, we're dead!") - .withException(e).sendInternalLogToServer(); } }; - - /**------------------------------------------------------------------------- - * Initializes Connect by creating or connecting to the API Shared Worker. - * Initializes Connect by loading the CCP in an iframe and connecting to it. + + /** + * Change the audio device used to play ringtone. + * If audio element is not fully initialized, the API will wait _audioPlayablePromise for 3 seconds and fail on timeout. + * This API is supported only by browsers that implemented ES6 Promise and http://www.w3.org/TR/audio-output/ + * Return a Promise that indicates the result of changing output device. */ - connect.core.initCCP = function (containerDiv, paramsIn) { - connect.core.checkNotInitialized(); - if (connect.core.initialized) { - return; + RingtoneEngineBase.prototype.setOutputDevice = function (deviceId) { + if (this._playableAudioPromise) { + var playableAudioWithTimeout = Promise.race([this._playableAudioPromise, new Promise(function (resolve, reject) { + global.setTimeout(function () { + reject("Timed out waiting for playable audio"); + }, 3000 /*ms*/); + })]); + + return playableAudioWithTimeout.then(function (audio) { + if (audio) { + if (audio.setSinkId) { + return Promise.resolve(audio.setSinkId(deviceId)); + } else { + return Promise.reject("Not supported"); + } + } else { + return Promise.reject("No audio found"); + } + }); } - - // For backwards compatibility, when instead of taking a params object - // as input we only accepted ccpUrl. - var params = {}; - if (typeof (paramsIn) === 'string') { - params.ccpUrl = paramsIn; - } else { - params = paramsIn; + if (global.Promise) { + return Promise.reject("Not eligible ringtone owner"); } - - connect.assertNotNull(containerDiv, 'containerDiv'); - connect.assertNotNull(params.ccpUrl, 'params.ccpUrl'); - - // Create the CCP iframe and append it to the container div. - var iframe = document.createElement('iframe'); - iframe.src = params.ccpUrl; - iframe.allow = "microphone; autoplay"; - iframe.style = "width: 100%; height: 100%"; - iframe.title = 'Amazon Connect CCP'; - containerDiv.appendChild(iframe); - - // Initialize the event bus and agent data providers. - // NOTE: Setting logEvents here to FALSE in order to avoid duplicating - // events which are logged in CCP. - connect.core.eventBus = new connect.EventBus({ logEvents: false }); - connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); - connect.core.mediaFactory = new connect.MediaFactory(params); - - // Build the upstream conduit communicating with the CCP iframe. - var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); - - // Let CCP know if iframe is visible - iframe.onload = setTimeout(function() { - var style = window.getComputedStyle(iframe, null); - var data = { - display: style.display, - offsetWidth: iframe.offsetWidth, - offsetHeight: iframe.offsetHeight, - clientRectsLength: iframe.getClientRects().length - }; - conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); - }, 10000); - - // Set the global upstream conduit for external use. - connect.core.upstream = conduit; - - // Init webSocketProvider - connect.core.webSocketProvider = new WebSocketProvider(); - - conduit.onAllUpstream(connect.core.getEventBus().bridge()); - - // Initialize the keepalive manager. - connect.core.keepaliveManager = new KeepaliveManager(conduit, - connect.core.getEventBus(), - params.ccpSynTimeout || CCP_SYN_TIMEOUT, - params.ccpAckTimeout || CCP_ACK_TIMEOUT) - ; - connect.core.iframeRefreshInterval = null; - - // Allow 5 sec (default) before receiving the first ACK from the CCP. - connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { - connect.core.ccpLoadTimeoutInstance = null; - connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); - }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); - - connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); - connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); - - // Once we receive the first ACK, setup our upstream API client and establish - // the SYN/ACK refresh flow. - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { - connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); - connect.core.client = new connect.UpstreamConduitClient(conduit); - connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); - connect.core.portStreamId = data.id; - - if (params.softphone || params.chat || params.pageOptions) { - // 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 - }); - } - - if (connect.core.ccpLoadTimeoutInstance) { - global.clearTimeout(connect.core.ccpLoadTimeoutInstance); - connect.core.ccpLoadTimeoutInstance = null; + }; + var VoiceRingtoneEngine = function VoiceRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + VoiceRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + VoiceRingtoneEngine.prototype.constructor = VoiceRingtoneEngine; + VoiceRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + var onContactConnect = function onContactConnect(contact) { + if (contact.getType() === lily.ContactType.VOICE && contact.isSoftphoneCall() && contact.isInbound()) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Ringtone Connecting", contact); + connect.getLog().info("Ringtone Connecting").sendInternalLogToServer(); } - - conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { streamsVersion: connect.version }); - - connect.core.keepaliveManager.start(); - this.unsubscribe(); - - connect.core.initialized = true; - connect.core.getEventBus().trigger(connect.EventType.INIT); + }; + connect.contact(function (contact) { + contact.onConnecting(onContactConnect); }); - - // Add any logs from the upstream to our own logger. - conduit.onUpstream(connect.EventType.LOG, function (logEntry) { - if (logEntry.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + new connect.Agent().getContacts().forEach(function (contact) { + if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { + onContactConnect(contact); } }); - - // Pop a login page when we encounter an ACK timeout. - connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { - // loginPopup is true by default, only false if explicitly set to false. - if (params.loginPopup !== false) { - try { - var loginUrl = getLoginUrl(params); - connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(); - // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT - if (params.loginUrl) { - connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); - } - connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions); - } catch (e) { - connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer(); - } - } - - if (connect.core.iframeRefreshInterval == null) { - connect.core.iframeRefreshInterval = window.setInterval(function () { - iframe.src = params.ccpUrl; - }, CCP_IFRAME_REFRESH_INTERVAL); - - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { - this.unsubscribe(); - global.clearInterval(connect.core.iframeRefreshInterval); - connect.core.iframeRefreshInterval = null; - connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); - if ((params.loginPopupAutoClose || (params.loginOptions && params.loginOptions.autoClose)) && connect.core.loginWindow) { - connect.core.loginWindow.close(); - connect.core.loginWindow = null; - } - }); + }; + var ChatRingtoneEngine = function ChatRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + ChatRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + ChatRingtoneEngine.prototype.constructor = ChatRingtoneEngine; + ChatRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + var onContactConnect = function onContactConnect(contact) { + if (contact.getType() === lily.ContactType.CHAT && contact.isInbound()) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Chat Ringtone Connecting", contact); + connect.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer(); } + }; + connect.contact(function (contact) { + contact.onConnecting(onContactConnect); }); - - if (params.onViewContact) { - connect.core.onViewContact(params.onViewContact); - } - - conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { - connect.numberOfConnectedCCPs = data.length; - }); - - conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { - if (data && data.domainId) { - connect.core.voiceIdDomainId = data.domainId; + }; + var TaskRingtoneEngine = function TaskRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + TaskRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + TaskRingtoneEngine.prototype.constructor = TaskRingtoneEngine; + TaskRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + var onContactConnect = function onContactConnect(contact) { + if (contact.getType() === lily.ContactType.TASK && contact.isInbound()) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Task Ringtone Connecting", contact); + connect.getLog().info("Task Ringtone Connecting").sendInternalLogToServer(); } + }; + connect.contact(function (contact) { + contact.onConnecting(onContactConnect); }); - - // keep the softphone params for external use - connect.core.softphoneParams = params.softphone; }; - - /**-----------------------------------------------------------------------*/ - var KeepaliveManager = function (conduit, eventBus, synTimeout, ackTimeout) { - this.conduit = conduit; - this.eventBus = eventBus; - this.synTimeout = synTimeout; - this.ackTimeout = ackTimeout; - this.ackTimer = null; - this.synTimer = null; - this.ackSub = null; + var QueueCallbackRingtoneEngine = function QueueCallbackRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); }; - - KeepaliveManager.prototype.start = function () { + QueueCallbackRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + QueueCallbackRingtoneEngine.prototype.constructor = QueueCallbackRingtoneEngine; + QueueCallbackRingtoneEngine.prototype._driveRingtone = function () { var self = this; - - this.conduit.sendUpstream(connect.EventType.SYNCHRONIZE); - this.ackSub = this.conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { - this.unsubscribe(); - global.clearTimeout(self.ackTimer); - self._deferStart(); + connect.contact(function (contact) { + contact.onIncoming(function () { + if (contact.getType() === lily.ContactType.QUEUE_CALLBACK) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Callback Ringtone Connecting", contact); + connect.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer(); + } + }); }); - this.ackTimer = global.setTimeout(function () { - self.ackSub.unsubscribe(); - self.eventBus.trigger(connect.EventType.ACK_TIMEOUT); - self._deferStart(); - }, this.ackTimeout); - }; - - //Fixes the keepalivemanager. - KeepaliveManager.prototype._deferStart = function () { - this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); }; - // For backwards compatibility only, in case customers are using this to start the keepalivemanager for some reason. - KeepaliveManager.prototype.deferStart = function () { - if (this.synTimer == null) { - this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); - } - }; - - /**-----------------------------------------------------------------------*/ - - var WebSocketProvider = function () { - - var callbacks = { - 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() - }; - - var invokeCallbacks = function (callbacks, response) { - callbacks.forEach(function (callback) { - callback(response); + /* export connect.RingtoneEngine */ + connect.VoiceRingtoneEngine = VoiceRingtoneEngine; + connect.ChatRingtoneEngine = ChatRingtoneEngine; + connect.TaskRingtoneEngine = TaskRingtoneEngine; + connect.QueueCallbackRingtoneEngine = QueueCallbackRingtoneEngine; +})(); + +/***/ }), + +/***/ 960: +/***/ (() => { + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + global.ccpVersion = "V2"; + var RTPJobIntervalMs = 1000; + var statsReportingJobIntervalMs = 30000; + var streamBufferSize = 500; + var CallTypeMap = {}; + CallTypeMap[connect.SoftphoneCallType.AUDIO_ONLY] = 'Audio'; + CallTypeMap[connect.SoftphoneCallType.VIDEO_ONLY] = 'Video'; + CallTypeMap[connect.SoftphoneCallType.AUDIO_VIDEO] = 'AudioVideo'; + CallTypeMap[connect.SoftphoneCallType.NONE] = 'None'; + var AUDIO_INPUT = 'audio_input'; + var AUDIO_OUTPUT = 'audio_output'; + var MediaTypeMap = {}; + MediaTypeMap[connect.ContactType.VOICE] = "Voice"; + var UNKNOWN_MEDIA_TYPE = "Unknown"; + var timeSeriesStreamStatsBuffer = []; + var aggregatedUserAudioStats = {}; + var aggregatedRemoteAudioStats = {}; + var rtpStatsJob = null; + var reportStatsJob = null; + //Logger specific to softphone. + var logger = null; + var SoftphoneErrorTypes = connect.SoftphoneErrorTypes; + var HANG_UP_MULTIPLE_SESSIONS_EVENT = "MultiSessionHangUp"; + var MULTIPLE_SESSIONS_EVENT = "MultiSessions"; + var localMediaStream = {}; + var softphoneClientId = connect.randomId(); + var requestIceAccess = function requestIceAccess(transport) { + return new Promise(function (resolve, reject) { + connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT, transport, { + success: function success(data) { + resolve(data.softphoneTransport.softphoneMediaConnections); + }, + failure: function failure(reason) { + if (reason.message && reason.message.includes("SoftphoneConnectionLimitBreachedException")) { + publishError("multiple_softphone_active_sessions", "Number of active sessions are more then allowed limit.", ""); + } + reject(Error("requestIceAccess failed")); + }, + authFailure: function authFailure() { + reject(Error("Authentication failed while requestIceAccess")); + }, + accessDenied: function accessDenied() { + reject(Error("Access Denied while requestIceAccess")); + } }); - }; - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.INIT_FAILURE, function () { - invokeCallbacks(callbacks.initFailure); - }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_OPEN, function (response) { - invokeCallbacks(callbacks.connectionOpen, response); - }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_CLOSE, function (response) { - invokeCallbacks(callbacks.connectionClose, response); - }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_GAIN, function () { - invokeCallbacks(callbacks.connectionGain); - }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_LOST, function (response) { - invokeCallbacks(callbacks.connectionLost, response); - }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, function (response) { - invokeCallbacks(callbacks.subscriptionUpdate, response); }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, function (response) { - invokeCallbacks(callbacks.subscriptionFailure, response); - }); - - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.ALL_MESSAGE, function (response) { - invokeCallbacks(callbacks.allMessage, response); - if (callbacks.topic.has(response.topic)) { - invokeCallbacks(callbacks.topic.get(response.topic), response); + }; + var SoftphoneManager = function SoftphoneManager(softphoneParams) { + var self = this; + logger = new SoftphoneLogger(connect.getLog()); + logger.info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(); + var rtcPeerConnectionFactory; + if (connect.RtcPeerConnectionFactory) { + rtcPeerConnectionFactory = new connect.RtcPeerConnectionFactory(logger, connect.core.getWebSocketManager(), softphoneClientId, connect.hitch(self, requestIceAccess, { + transportType: "softphone", + softphoneClientId: softphoneClientId + }), connect.hitch(self, publishError)); + } + if (!isBrowserSoftPhoneSupported()) { + publishError(SoftphoneErrorTypes.UNSUPPORTED_BROWSER, "Connect does not support this browser. Some functionality may not work. ", ""); + } + var gumPromise = fetchUserMedia({ + success: function success(stream) { + connect.core.setSoftphoneUserMediaStream(stream); + }, + failure: function failure(err) { + publishError(err, "Your microphone is not enabled in your browser. ", ""); } }); - - this.sendMessage = function (webSocketPayload) { - connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SEND, webSocketPayload); - }; - - this.onInitFailure = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.initFailure.add(cb); - return function () { - return callbacks.initFailure.delete(cb); - }; - }; + handleSoftPhoneMuteToggle(); + handleSpeakerDeviceChange(); + handleMicrophoneDeviceChange(); + this.ringtoneEngine = null; + var rtcSessions = {}; + // Tracks the agent connection ID, so that if the same contact gets re-routed to the same agent, it'll still set up softphone + var callsDetected = {}; + this.onInitContactSub = {}; + this.onInitContactSub.unsubscribe = function () {}; - this.onConnectionOpen = function(cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionOpen.add(cb); - return function () { - return callbacks.connectionOpen.delete(cb); - }; + // variables for firefox multitab + var isSessionPending = false; + var pendingContact = null; + var pendingAgentConnectionId = null; + var postponeStartingSession = function postponeStartingSession(contact, agentConnectionId) { + isSessionPending = true; + pendingContact = contact; + pendingAgentConnectionId = agentConnectionId; }; - - this.onConnectionClose = function(cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionClose.add(cb); - return function () { - return callbacks.connectionClose.delete(cb); - }; + var cancelPendingSession = function cancelPendingSession() { + isSessionPending = false; + pendingContact = null; + pendingAgentConnectionId = null; }; - this.onConnectionGain = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionGain.add(cb); - return function () { - return callbacks.connectionGain.delete(cb); - }; - }; - - this.onConnectionLost = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionLost.add(cb); - return function () { - return callbacks.connectionLost.delete(cb); - }; - }; - - this.onSubscriptionUpdate = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.subscriptionUpdate.add(cb); - return function () { - return callbacks.subscriptionUpdate.delete(cb); - }; + // helper method to provide access to rtc sessions + this.getSession = function (connectionId) { + return rtcSessions[connectionId]; }; - - this.onSubscriptionFailure = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.subscriptionFailure.add(cb); - return function () { - return callbacks.subscriptionFailure.delete(cb); - }; + this.replaceLocalMediaTrack = function (connectionId, track) { + var stream = localMediaStream[connectionId].stream; + if (stream) { + var oldTrack = stream.getAudioTracks()[0]; + track.enabled = oldTrack.enabled; + oldTrack.enabled = false; + stream.removeTrack(oldTrack); + stream.addTrack(track); + } }; - - this.subscribeTopics = function (topics) { - connect.assertNotNull(topics, 'topics'); - connect.assertTrue(connect.isArray(topics), 'topics must be a array'); - connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SUBSCRIBE, topics); + var isContactTerminated = function isContactTerminated(contact) { + return contact.getStatus().type === connect.ContactStatusType.ENDED || contact.getStatus().type === connect.ContactStatusType.ERROR || contact.getStatus().type === connect.ContactStatusType.MISSED; }; - - this.onMessage = function (topicName, cb) { - connect.assertNotNull(topicName, 'topicName'); - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - if (callbacks.topic.has(topicName)) { - callbacks.topic.get(topicName).add(cb); - } else { - callbacks.topic.set(topicName, new Set([cb])); + var destroySession = function destroySession(agentConnectionId) { + if (rtcSessions.hasOwnProperty(agentConnectionId)) { + var session = rtcSessions[agentConnectionId]; + // Currently the assumption is it will throw an exception only and if only it already has been hung up. + // TODO: Update once the hangup API does not throw exceptions + new Promise(function (resolve, reject) { + delete rtcSessions[agentConnectionId]; + delete callsDetected[agentConnectionId]; + session.hangup(); + })["catch"](function (err) { + lily.getLog().warn("Clean up the session locally " + agentConnectionId, err.message).sendInternalLogToServer(); + }); } - return function () { - return callbacks.topic.get(topicName).delete(cb); - }; - }; - - this.onAllMessage = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.allMessage.add(cb); - return function () { - return callbacks.allMessage.delete(cb); - }; }; - - }; - - /**-----------------------------------------------------------------------*/ - var AgentDataProvider = function (bus) { - var agentData = null; - this.bus = bus; - this.bus.subscribe(connect.AgentEvents.UPDATE, connect.hitch(this, this.updateAgentData)); - }; - - AgentDataProvider.prototype.updateAgentData = function (agentData) { - var oldAgentData = this.agentData; - this.agentData = agentData; - - if (oldAgentData == null) { - connect.agent.initialized = true; - this.bus.trigger(connect.AgentEvents.INIT, new connect.Agent()); - } - - this.bus.trigger(connect.AgentEvents.REFRESH, new connect.Agent()); - - this._fireAgentUpdateEvents(oldAgentData); - }; - - AgentDataProvider.prototype.getAgentData = function () { - if (this.agentData == null) { - throw new connect.StateError('No agent data is available yet!'); - } - - return this.agentData; - }; - - AgentDataProvider.prototype.getContactData = function (contactId) { - var agentData = this.getAgentData(); - var contactData = connect.find(agentData.snapshot.contacts, function (ctdata) { - return ctdata.contactId === contactId; - }); - - if (contactData == null) { - throw new connect.StateError('Contact %s no longer exists.', contactId); - } - - return contactData; - }; - - AgentDataProvider.prototype.getConnectionData = function (contactId, connectionId) { - var contactData = this.getContactData(contactId); - var connectionData = connect.find(contactData.connections, function (cdata) { - return cdata.connectionId === connectionId; - }); - - if (connectionData == null) { - throw new connect.StateError('Connection %s for contact %s no longer exists.', connectionId, contactId); - } - - return connectionData; - }; - - AgentDataProvider.prototype.getInstanceId = function(){ - return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]; - } - AgentDataProvider.prototype.getAWSAccountId = function(){ - return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]; - } - - AgentDataProvider.prototype._diffContacts = function (oldAgentData) { - var diff = { - added: {}, - removed: {}, - common: {}, - oldMap: connect.index(oldAgentData == null ? [] : oldAgentData.snapshot.contacts, function (contact) { return contact.contactId; }), - newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { return contact.contactId; }) - }; - - connect.keys(diff.oldMap).forEach(function (contactId) { - if (connect.contains(diff.newMap, contactId)) { - diff.common[contactId] = diff.newMap[contactId]; - } else { - diff.removed[contactId] = diff.oldMap[contactId]; + // When multiple RTC sessions detected, ignore the new call and hang up the previous sessions. + // TODO: Update when connect-rtc exposes an API to detect session status. + var sanityCheckActiveSessions = function sanityCheckActiveSessions(rtcSessions) { + if (Object.keys(rtcSessions).length > 0) { + // Error! our state doesn't match, tear it all down. + for (var connectionId in rtcSessions) { + if (rtcSessions.hasOwnProperty(connectionId)) { + // Log an error for the session we are about to end. + publishMultipleSessionsEvent(HANG_UP_MULTIPLE_SESSIONS_EVENT, rtcSessions[connectionId].callId, connectionId); + destroySession(connectionId); + } + } + throw new Error("duplicate session detected, refusing to setup new connection"); } - }); - - connect.keys(diff.newMap).forEach(function (contactId) { - if (!connect.contains(diff.oldMap, contactId)) { - diff.added[contactId] = diff.newMap[contactId]; + }; + this.startSession = function (_contact, _agentConnectionId) { + var contact = isSessionPending ? pendingContact : _contact; + var agentConnectionId = isSessionPending ? pendingAgentConnectionId : _agentConnectionId; + if (!contact || !agentConnectionId) { + return; } - }); - - return diff; - }; - - AgentDataProvider.prototype._fireAgentUpdateEvents = function (oldAgentData) { - var self = this; - var diff = null; - var oldAgentState = oldAgentData == null ? connect.AgentAvailStates.INIT : oldAgentData.snapshot.state.name; - var newAgentState = this.agentData.snapshot.state.name; - var oldRoutingState = oldAgentData == null ? connect.AgentStateType.INIT : oldAgentData.snapshot.state.type; - var newRoutingState = this.agentData.snapshot.state.type; - - if (oldRoutingState !== newRoutingState) { - connect.core.getAgentRoutingEventGraph().getAssociations(this, oldRoutingState, newRoutingState).forEach(function (event) { - self.bus.trigger(event, new connect.Agent()); - }); - } - - if (oldAgentState !== newAgentState) { - this.bus.trigger(connect.AgentEvents.STATE_CHANGE, { - agent: new connect.Agent(), - oldState: oldAgentState, - newState: newAgentState - - }); - connect.core.getAgentStateEventGraph().getAssociations(this, oldAgentState, newAgentState).forEach(function (event) { - self.bus.trigger(event, new connect.Agent()); - }); - } + cancelPendingSession(); + + // Set to true, this will block subsequent invokes from entering. + callsDetected[agentConnectionId] = true; + logger.info("Softphone call detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); - var oldNextState = oldAgentData && oldAgentData.snapshot.nextState ? oldAgentData.snapshot.nextState.name : null; - var newNextState = this.agentData.snapshot.nextState ? this.agentData.snapshot.nextState.name : null; - if (oldNextState !== newNextState && newNextState) { - self.bus.trigger(connect.AgentEvents.ENQUEUED_NEXT_STATE, new connect.Agent()); - } + // Ensure our session state matches our contact state to prevent issues should we lose track of a contact. + sanityCheckActiveSessions(rtcSessions); + if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { + publishTelemetryEvent("Softphone Connecting", contact.getContactId()); + } + initializeParams(); + var softphoneInfo = contact.getAgentConnection().getSoftphoneMediaInfo(); + var callConfig = parseCallConfig(softphoneInfo.callConfigJson); + var webSocketProvider; + if (callConfig.useWebSocketProvider) { + webSocketProvider = connect.core.getWebSocketManager(); + } + var session = new connect.RTCSession(callConfig.signalingEndpoint, callConfig.iceServers, softphoneInfo.callContextToken, logger, contact.getContactId(), agentConnectionId, webSocketProvider); + rtcSessions[agentConnectionId] = session; + if (connect.core.getSoftphoneUserMediaStream()) { + session.mediaStream = connect.core.getSoftphoneUserMediaStream(); + } - if (oldAgentData !== null) { - diff = this._diffContacts(oldAgentData); - - } else { - diff = { - added: connect.index(this.agentData.snapshot.contacts, function (contact) { return contact.contactId; }), - removed: {}, - common: {}, - oldMap: {}, - newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { return contact.contactId; }) - }; - } - - connect.values(diff.added).forEach(function (contactData) { - self.bus.trigger(connect.ContactEvents.INIT, new connect.Contact(contactData.contactId)); - self._fireContactUpdateEvents(contactData.contactId, connect.ContactStateType.INIT, contactData.state.type); - }); - - connect.values(diff.removed).forEach(function (contactData) { - self.bus.trigger(connect.ContactEvents.DESTROYED, new connect.ContactSnapshot(contactData)); - self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.DESTROYED, contactData.contactId), new connect.ContactSnapshot(contactData)); - self._unsubAllContactEventsForContact(contactData.contactId); - }); - - connect.keys(diff.common).forEach(function (contactId) { - self._fireContactUpdateEvents(contactId, diff.oldMap[contactId].state.type, diff.newMap[contactId].state.type); - }); - }; - - AgentDataProvider.prototype._fireContactUpdateEvents = function (contactId, oldContactState, newContactState) { - var self = this; - if (oldContactState !== newContactState) { - connect.core.getContactEventGraph().getAssociations(this, oldContactState, newContactState).forEach(function (event) { - self.bus.trigger(event, new connect.Contact(contactId)); - self.bus.trigger(connect.core.getContactEventName(event, contactId), new connect.Contact(contactId)); + // Custom Event to indicate the session init operations + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConnectionEvents.SESSION_INIT, + data: { + connectionId: agentConnectionId + } }); - } + session.onSessionFailed = function (rtcSession, reason) { + delete rtcSessions[agentConnectionId]; + delete callsDetected[agentConnectionId]; + publishSoftphoneFailureLogs(rtcSession, reason); + publishSessionFailureTelemetryEvent(contact.getContactId(), reason); + stopJobsAndReport(contact, rtcSession.sessionReport); + }; + session.onSessionConnected = function (rtcSession) { + publishTelemetryEvent("Softphone Session Connected", contact.getContactId()); + // Become master to send logs, since we need logs from softphone tab. + connect.becomeMaster(connect.MasterTopics.SEND_LOGS); + //start stats collection and reporting jobs + startStatsCollectionJob(rtcSession); + startStatsReportingJob(contact); + fireContactAcceptedEvent(contact); + }; + session.onSessionCompleted = function (rtcSession) { + publishTelemetryEvent("Softphone Session Completed", contact.getContactId()); + delete rtcSessions[agentConnectionId]; + delete callsDetected[agentConnectionId]; + // Stop all jobs and perform one last job. + stopJobsAndReport(contact, rtcSession.sessionReport); - self.bus.trigger(connect.ContactEvents.REFRESH, new connect.Contact(contactId)); - self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.REFRESH, contactId), new connect.Contact(contactId)); - }; - - AgentDataProvider.prototype._unsubAllContactEventsForContact = function (contactId) { - var self = this; - connect.values(connect.ContactEvents).forEach(function (eventName) { - self.bus.getSubscriptions(connect.core.getContactEventName(eventName, contactId)) - .map(function (sub) { sub.unsubscribe(); }); - }); - }; - - /** ----- minimal view layer event handling **/ - - connect.core.onViewContact = function (f) { - connect.core.getUpstream().onUpstream(connect.ContactEvents.VIEW, f); - }; - - /** - * Used of agent interface control. - * connect.core.viewContact("contactId") -> this is curently programmed to get the contact into view. - */ - connect.core.viewContact = function (contactId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ContactEvents.VIEW, - data: { - contactId: contactId + // Cleanup the cached streams + deleteLocalMediaStream(agentConnectionId); + }; + session.onLocalStreamAdded = function (rtcSession, stream) { + // Cache the streams for mute/unmute + localMediaStream[agentConnectionId] = { + stream: stream + }; + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, + data: { + connectionId: agentConnectionId + } + }); + }; + session.remoteAudioElement = document.getElementById('remote-audio'); + if (rtcPeerConnectionFactory) { + session.connect(rtcPeerConnectionFactory.get(callConfig.iceServers)); + } else { + session.connect(); } - }); - }; + }; + var onRefreshContact = function onRefreshContact(contact, agentConnectionId) { + if (rtcSessions[agentConnectionId] && isContactTerminated(contact)) { + destroySession(agentConnectionId); + cancelPendingSession(); + } + if (contact.isSoftphoneCall() && !callsDetected[agentConnectionId] && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { + if (connect.isFirefoxBrowser() && connect.hasOtherConnectedCCPs()) { + postponeStartingSession(contact, agentConnectionId); + } else { + self.startSession(contact, agentConnectionId); + } + } + }; + var onInitContact = function onInitContact(contact) { + var agentConnectionId = contact.getAgentConnection().connectionId; + logger.info("Contact detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + if (!callsDetected[agentConnectionId]) { + contact.onRefresh(function () { + onRefreshContact(contact, agentConnectionId); + }); + } + }; + self.onInitContactSub = connect.contact(onInitContact); - /** ----- minimal view layer event handling **/ - - connect.core.onActivateChannelWithViewType = function (f) { - connect.core.getUpstream().onUpstream(connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, f); - }; - - /** - * Used of agent interface control. - * connect.core.activateChannelWithViewType() -> this is curently programmed to get either the number pad, quick connects, or create task into view. - * the valid combinations are ("create_task", "task"), ("number_pad", "softphone"), ("create_task", "softphone"), ("quick_connects", "softphone") - * the softphone with create_task combo is a special case in the channel view to allow all three view type buttons to appear on the softphone screen - * - * The 'source' is an optional parameter which indicates the requester. For example, if invoked with ("create_task", "task", "agentapp") we would know agentapp requested open task view. - */ - connect.core.activateChannelWithViewType = function (viewType, mediaType, source) { - const data = { viewType, mediaType }; - if (source) { - data.source = source; - } - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, - data + // Contact already in connecting state scenario - In this case contact INIT is missed hence the OnRefresh callback is missed. + new connect.Agent().getContacts().forEach(function (contact) { + var agentConnectionId = contact.getAgentConnection().connectionId; + logger.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId" + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + onInitContact(contact); + onRefreshContact(contact, agentConnectionId); }); }; - - /** - * Used to publish 'task created' event - */ - connect.core.triggerTaskCreated = function (data) { - connect.core.getUpstream().upstreamBus.trigger(connect.TaskEvents.CREATED, data); - }; - - /** ------------------------------------------------- */ - - /** - * This will be helpful for the custom and embedded CCPs - * to handle the access denied use case. - */ - connect.core.onAccessDenied = function (f) { - connect.core.getUpstream().onUpstream(connect.EventType.ACCESS_DENIED, f); - }; - - /** - * This will be helpful for SAML use cases to handle the custom logins. - */ - connect.core.onAuthFail = function (f) { - connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, f); - }; - - /** ------------------------------------------------- */ - - /** - * Used for handling the rtc session stats. - * Usage - * connect.core.onSoftphoneSessionInit(function({ connectionId }) { - * var softphoneManager = connect.core.getSoftphoneManager(); - * if(softphoneManager){ - * // access session - * var session = softphoneManager.getSession(connectionId); - * } - * }); - */ - - connect.core.onSoftphoneSessionInit = function (f) { - connect.core.getUpstream().onUpstream(connect.ConnectionEvents.SESSION_INIT, f); - }; - - /**-----------------------------------------------------------------------*/ - connect.core.onConfigure = function(f) { - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.CONFIGURE, f); - } - - /**-----------------------------------------------------------------------*/ - connect.core.onInitialized = function(f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.INIT, f); - } - - /**-----------------------------------------------------------------------*/ - connect.core.getContactEventName = function (eventName, contactId) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(contactId, 'contactId'); - if (!connect.contains(connect.values(connect.ContactEvents), eventName)) { - throw new connect.ValueError('%s is not a valid contact event.', eventName); + var fireContactAcceptedEvent = function fireContactAcceptedEvent(contact) { + var conduit = connect.core.getUpstream(); + var agentConnection = contact.getAgentConnection(); + if (!agentConnection) { + logger.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer(); + return; + } + var softphoneMediaInfo = agentConnection.getSoftphoneMediaInfo(); + if (!softphoneMediaInfo) { + logger.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer(); + return; + } + if (softphoneMediaInfo.autoAccept === true) { + logger.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.ContactEvents.ACCEPTED, + data: new connect.Contact(contact.contactId) + }); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, contact.contactId), + data: new connect.Contact(contact.contactId) + }); + } else { + logger.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer(); } - return connect.sprintf('%s::%s', eventName, contactId); - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getEventBus = function () { - return connect.core.eventBus; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getWebSocketManager = function () { - return connect.core.webSocketProvider; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentDataProvider = function () { - return connect.core.agentDataProvider; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getLocalTimestamp = function () { - return connect.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getSkew = function () { - return connect.core.getAgentDataProvider().getAgentData().snapshot.skew; }; - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentRoutingEventGraph = function () { - return connect.core.agentRoutingEventGraph; + + // Bind events for mute + var handleSoftPhoneMuteToggle = function handleSoftPhoneMuteToggle() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.MUTE, muteToggle); }; - connect.core.agentRoutingEventGraph = new connect.EventGraph() - .assoc(connect.EventGraph.ANY, connect.AgentStateType.ROUTABLE, - connect.AgentEvents.ROUTABLE) - .assoc(connect.EventGraph.ANY, connect.AgentStateType.NOT_ROUTABLE, - connect.AgentEvents.NOT_ROUTABLE) - .assoc(connect.EventGraph.ANY, connect.AgentStateType.OFFLINE, - connect.AgentEvents.OFFLINE); - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentStateEventGraph = function () { - return connect.core.agentStateEventGraph; + var handleSpeakerDeviceChange = function handleSpeakerDeviceChange() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE, setSpeakerDevice); }; - connect.core.agentStateEventGraph = new connect.EventGraph() - .assoc(connect.EventGraph.ANY, - connect.values(connect.AgentErrorStates), - connect.AgentEvents.ERROR) - .assoc(connect.EventGraph.ANY, connect.AgentAvailStates.AFTER_CALL_WORK, - connect.AgentEvents.ACW); - - /**-----------------------------------------------------------------------*/ - connect.core.getContactEventGraph = function () { - return connect.core.contactEventGraph; + var handleMicrophoneDeviceChange = function handleMicrophoneDeviceChange() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, setMicrophoneDevice); }; - - connect.core.contactEventGraph = new connect.EventGraph() - .assoc(connect.EventGraph.ANY, - connect.ContactStateType.INCOMING, - connect.ContactEvents.INCOMING) - .assoc(connect.EventGraph.ANY, - connect.ContactStateType.PENDING, - connect.ContactEvents.PENDING) - .assoc(connect.EventGraph.ANY, - connect.ContactStateType.CONNECTING, - connect.ContactEvents.CONNECTING) - .assoc(connect.EventGraph.ANY, - connect.ContactStateType.CONNECTED, - connect.ContactEvents.CONNECTED) - .assoc(connect.ContactStateType.CONNECTING, - connect.ContactStateType.ERROR, - connect.ContactEvents.MISSED) - .assoc(connect.ContactStateType.INCOMING, - connect.ContactStateType.ERROR, - connect.ContactEvents.MISSED) - .assoc(connect.EventGraph.ANY, - connect.ContactStateType.ENDED, - connect.ContactEvents.ACW) - .assoc(connect.values(connect.CONTACT_ACTIVE_STATES), - connect.values(connect.relativeComplement(connect.CONTACT_ACTIVE_STATES, connect.ContactStateType)), - connect.ContactEvents.ENDED) - .assoc(connect.EventGraph.ANY, - connect.values(connect.AgentErrorStates), - connect.ContactEvents.ERROR) - .assoc(connect.ContactStateType.CONNECTING, - connect.ContactStateType.MISSED, - connect.ContactEvents.MISSED); - /**-----------------------------------------------------------------------*/ - connect.core.getClient = function () { - if (!connect.core.client) { - throw new connect.StateError('The connect core has not been initialized!'); - } - return connect.core.client; + // Make sure once we disconnected we get the mute state back to normal + var deleteLocalMediaStream = function deleteLocalMediaStream(connectionId) { + delete localMediaStream[connectionId]; + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.MUTE_TOGGLE, + data: { + muted: false + } + }); }; - connect.core.client = null; - /**-----------------------------------------------------------------------*/ - connect.core.getAgentAppClient = function () { - if (!connect.core.agentAppClient) { - throw new connect.StateError('The connect AgentApp Client has not been initialized!'); + // Check for the local streams if exists - revert it + // And inform other clients about the change + var muteToggle = function muteToggle(data) { + var status; + if (connect.keys(localMediaStream).length === 0) { + return; } - return connect.core.agentAppClient; - }; - connect.core.agentAppClient = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getMasterClient = function () { - if (!connect.core.masterClient) { - throw new connect.StateError('The connect master client has not been initialized!'); + if (data && data.mute !== undefined) { + status = data.mute; } - return connect.core.masterClient; - }; - connect.core.masterClient = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getSoftphoneManager = function () { - return connect.core.softphoneManager; - }; - connect.core.softphoneManager = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getNotificationManager = function () { - if (!connect.core.notificationManager) { - connect.core.notificationManager = new connect.NotificationManager(); + for (var connectionId in localMediaStream) { + if (localMediaStream.hasOwnProperty(connectionId)) { + var localMedia = localMediaStream[connectionId].stream; + if (localMedia) { + var audioTracks = localMedia.getAudioTracks()[0]; + if (status !== undefined) { + audioTracks.enabled = !status; + localMediaStream[connectionId].muted = status; + if (status) { + logger.info("Agent has muted the contact, connectionId - " + connectionId).sendInternalLogToServer(); + } else { + logger.info("Agent has unmuted the contact, connectionId - " + connectionId).sendInternalLogToServer(); + } + } else { + status = localMediaStream[connectionId].muted || false; + } + } + } } - return connect.core.notificationManager; - }; - connect.core.notificationManager = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getPopupManager = function () { - return connect.core.popupManager; + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.MUTE_TOGGLE, + data: { + muted: status + } + }); }; - connect.core.popupManager = new connect.PopupManager(); - - /**-----------------------------------------------------------------------*/ - connect.core.getUpstream = function () { - if (!connect.core.upstream) { - throw new connect.StateError('There is no upstream conduit!'); + var setSpeakerDevice = function setSpeakerDevice(data) { + if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { + return; } - return connect.core.upstream; + var deviceId = data.deviceId; + var remoteAudioElement = document.getElementById('remote-audio'); + try { + logger.info("Trying to set speaker to device " + deviceId); + if (remoteAudioElement && typeof remoteAudioElement.setSinkId === 'function') { + remoteAudioElement.setSinkId(deviceId); + } + } catch (e) { + logger.error("Failed to set speaker to device " + deviceId); + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, + data: { + deviceId: deviceId + } + }); }; - connect.core.upstream = null; - - /**-----------------------------------------------------------------------*/ - connect.core.AgentDataProvider = AgentDataProvider; - -})(); -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -(function () { - var global = this; - var connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - var RingtoneEngineBase = function (ringtoneConfig) { - var self = this; - this._prevContactId = null; - - connect.assertNotNull(ringtoneConfig, "ringtoneConfig"); - if (!ringtoneConfig.ringtoneUrl) { - throw new Error("ringtoneUrl is required!"); + var setMicrophoneDevice = function setMicrophoneDevice(data) { + if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { + return; } - - if (global.Audio && typeof global.Promise !== "undefined") { - this._playableAudioPromise = new Promise(function (resolve, reject) { - self._audio = new Audio(ringtoneConfig.ringtoneUrl); - self._audio.loop = true; - self._audio.addEventListener("canplay", function () { - self._audioPlayable = true; - resolve(self._audio); - }); + var deviceId = data.deviceId; + var softphoneManager = connect.core.getSoftphoneManager(); + try { + navigator.mediaDevices.getUserMedia({ + audio: { + deviceId: { + exact: deviceId + } + } + }).then(function (newMicrophoneStream) { + var newMicrophoneTrack = newMicrophoneStream.getAudioTracks()[0]; + for (var connectionId in localMediaStream) { + if (localMediaStream.hasOwnProperty(connectionId)) { + var localMedia = localMediaStream[connectionId].stream; + var session = softphoneManager.getSession(connectionId); + //Replace the audio track in the RtcPeerConnection + session._pc.getSenders()[0].replaceTrack(newMicrophoneTrack).then(function () { + //Replace the audio track in the local media stream (for mute / unmute) + softphoneManager.replaceLocalMediaTrack(connectionId, newMicrophoneTrack); + }); + } + } }); - + } catch (e) { + logger.error("Failed to set microphone device " + deviceId); + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, + data: { + deviceId: deviceId + } + }); + }; + var publishSoftphoneFailureLogs = function publishSoftphoneFailureLogs(rtcSession, reason) { + if (reason === connect.RTCErrors.ICE_COLLECTION_TIMEOUT) { + var endPointUrl = "\n"; + for (var i = 0; i < rtcSession._iceServers.length; i++) { + for (var j = 0; j < rtcSession._iceServers[i].urls.length; j++) { + endPointUrl = endPointUrl + rtcSession._iceServers[i].urls[j] + "\n"; + } + } + publishError(SoftphoneErrorTypes.ICE_COLLECTION_TIMEOUT, "Ice collection timedout. ", endPointUrl); + } else if (reason === connect.RTCErrors.USER_BUSY) { + publishError(SoftphoneErrorTypes.USER_BUSY_ERROR, "Softphone call UserBusy error. ", ""); + } else if (reason === connect.RTCErrors.SIGNALLING_HANDSHAKE_FAILURE) { + publishError(SoftphoneErrorTypes.SIGNALLING_HANDSHAKE_FAILURE, "Handshaking with Signalling Server " + rtcSession._signalingUri + " failed. ", rtcSession._signalingUri); + } else if (reason === connect.RTCErrors.GUM_TIMEOUT_FAILURE || reason === connect.RTCErrors.GUM_OTHER_FAILURE) { + publishError(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED, "Your microphone is not enabled in your browser. ", ""); + } else if (reason === connect.RTCErrors.SIGNALLING_CONNECTION_FAILURE) { + publishError(SoftphoneErrorTypes.SIGNALLING_CONNECTION_FAILURE, "URL " + rtcSession._signalingUri + " cannot be reached. ", rtcSession._signalingUri); + } else if (reason === connect.RTCErrors.CALL_NOT_FOUND) { + // No need to publish any softphone error for this case. CCP UX will handle this case. + logger.error("Softphone call failed due to CallNotFoundException.").sendInternalLogToServer(); } else { - this._audio = null; - connect.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer(); + publishError(SoftphoneErrorTypes.WEBRTC_ERROR, "webrtc system error. ", ""); } - - self._driveRingtone(); }; - RingtoneEngineBase.prototype._driveRingtone = function () { - throw new Error("Not implemented."); + /** Parse the JSON encoded web call config into the data it represents. */ + var parseCallConfig = function parseCallConfig(serializedConfig) { + // Our underscore is too old for unescape + // https://issues.amazon.com/issues/CSWF-1467 + var decodedJSON = serializedConfig.replace(/"/g, '"'); + return JSON.parse(decodedJSON); }; - - RingtoneEngineBase.prototype._startRingtone = function (contact) { - if (this._audio) { - this._audio.play() - .catch(function(e) { - this._publishTelemetryEvent("Ringtone Playback Failure", contact); - connect.getLog().error("Ringtone Playback Failure").sendInternalLogToServer(); - }); - this._publishTelemetryEvent("Ringtone Start", contact); - connect.getLog().info("Ringtone Start").sendInternalLogToServer(); + var fetchUserMedia = function fetchUserMedia(callbacksIn) { + var callbacks = callbacksIn || {}; + callbacks.success = callbacks.success || function () {}; + callbacks.failure = callbacks.failure || function () {}; + var CONSTRAINT = { + audio: true + }; + var promise = null; + if (typeof Promise !== "function") { + callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); + return; } - }; - - RingtoneEngineBase.prototype._stopRingtone = function (contact) { - if (this._audio) { - this._audio.pause(); - this._audio.currentTime = 0; - this._publishTelemetryEvent("Ringtone Stop", contact); - connect.getLog().info("Ringtone Stop").sendInternalLogToServer(); + if (_typeof(navigator.mediaDevices) === "object" && typeof navigator.mediaDevices.getUserMedia === "function") { + promise = navigator.mediaDevices.getUserMedia(CONSTRAINT); + } else if (typeof navigator.webkitGetUserMedia === "function") { + promise = new Promise(function (resolve, reject) { + navigator.webkitGetUserMedia(CONSTRAINT, resolve, reject); + }); + } else { + callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); + return; } + promise.then(function (stream) { + var audioTracks = stream.getAudioTracks(); + if (audioTracks && audioTracks.length > 0) { + callbacks.success(stream); + } else { + callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); + } + }, function (err) { + callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); + }); + return promise; }; - - /** - * Stop ringtone. - */ - RingtoneEngineBase.prototype.stopRingtone = function () { - this._stopRingtone(); - }; - - RingtoneEngineBase.prototype._ringtoneSetup = function (contact) { - var self = this; - connect.ifMaster(connect.MasterTopics.RINGTONE, function () { - self._startRingtone(contact); - self._prevContactId = contact.getContactId(); - - contact.onConnected(lily.hitch(self, self._stopRingtone)); - contact.onAccepted(lily.hitch(self, self._stopRingtone)); - contact.onEnded(lily.hitch(self, self._stopRingtone)); - // Just to make sure to stop the ringtone in case of the failures of specific callbacks(onAccepted,onConnected); - contact.onRefresh(function (contact) { - if (contact.getStatus().type !== connect.ContactStatusType.CONNECTING && - contact.getStatus().type !== connect.ContactStatusType.INCOMING) { - self._stopRingtone(); - } - }); + var publishError = function publishError(errorType, message, endPointUrl) { + logger.error("Softphone error occurred : ", errorType, message || "").sendInternalLogToServer(); + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.SOFTPHONE_ERROR, + data: new connect.SoftphoneError(errorType, message, endPointUrl) }); }; - - RingtoneEngineBase.prototype._publishTelemetryEvent = function (eventName, contact) { - if (contact && contact.getContactId()) { + var publishSessionFailureTelemetryEvent = function publishSessionFailureTelemetryEvent(contactId, reason) { + publishTelemetryEvent("Softphone Session Failed", contactId, { + failedReason: reason + }); + }; + var publishTelemetryEvent = function publishTelemetryEvent(eventName, contactId, data) { + if (contactId) { connect.publishMetric({ name: eventName, - contactId: contact.getContactId() + contactId: contactId, + data: data }); } }; - /** - * Change the audio device used to play ringtone. - * If audio element is not fully initialized, the API will wait _audioPlayablePromise for 3 seconds and fail on timeout. - * This API is supported only by browsers that implemented ES6 Promise and http://www.w3.org/TR/audio-output/ - * Return a Promise that indicates the result of changing output device. - */ - RingtoneEngineBase.prototype.setOutputDevice = function (deviceId) { - if (this._playableAudioPromise) { - var playableAudioWithTimeout = Promise.race([ - this._playableAudioPromise, - new Promise(function (resolve, reject) { - global.setTimeout(function () { reject("Timed out waiting for playable audio"); }, 3000/*ms*/); - }) - ]); - return playableAudioWithTimeout.then(function (audio) { - if (audio) { - if (audio.setSinkId) { - return Promise.resolve(audio.setSinkId(deviceId)); - } else { - return Promise.reject("Not supported"); - } - } else { - return Promise.reject("No audio found"); - } - }); + // Publish the contact and agent information in a multiple sessions scenarios + var publishMultipleSessionsEvent = function publishMultipleSessionsEvent(eventName, contactId, agentConnectionId) { + publishTelemetryEvent(eventName, contactId, [{ + name: "AgentConnectionId", + value: agentConnectionId + }]); + logger.info("Publish multiple session error metrics", eventName, "contactId " + contactId, "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + }; + var isBrowserSoftPhoneSupported = function isBrowserSoftPhoneSupported() { + // In Opera, the true version is after "Opera" or after "Version" + if (connect.isOperaBrowser() && connect.getOperaBrowserVersion() > 17) { + return true; } - - if (global.Promise) { - return Promise.reject("Not eligible ringtone owner"); + // In Chrome, the true version is after "Chrome" + else if (connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 22) { + return true; + } + // In Firefox, the true version is after "Firefox" + else if (connect.isFirefoxBrowser() && connect.getFirefoxBrowserVersion() > 21) { + return true; + } else { + return false; } }; - - var VoiceRingtoneEngine = function (ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); + var sendSoftphoneMetrics = function sendSoftphoneMetrics(contact) { + var streamStats = timeSeriesStreamStatsBuffer.slice(); + timeSeriesStreamStatsBuffer = []; + if (streamStats.length > 0) { + contact.sendSoftphoneMetrics(streamStats, { + success: function success() { + logger.info("sendSoftphoneMetrics success" + JSON.stringify(streamStats)).sendInternalLogToServer(); + }, + failure: function failure(data) { + logger.error("sendSoftphoneMetrics failed.").withObject(data).sendInternalLogToServer(); + } + }); + } }; - VoiceRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - VoiceRingtoneEngine.prototype.constructor = VoiceRingtoneEngine; - - VoiceRingtoneEngine.prototype._driveRingtone = function () { - var self = this; - - var onContactConnect = function (contact) { - if (contact.getType() === lily.ContactType.VOICE && - contact.isSoftphoneCall() && contact.isInbound()) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Ringtone Connecting", contact); - connect.getLog().info("Ringtone Connecting").sendInternalLogToServer(); - } + var sendSoftphoneReport = function sendSoftphoneReport(contact, report, userAudioStats, remoteAudioStats) { + report.streamStats = [addStreamTypeToStats(userAudioStats, AUDIO_INPUT), addStreamTypeToStats(remoteAudioStats, AUDIO_OUTPUT)]; + var callReport = { + callStartTime: report.sessionStartTime, + callEndTime: report.sessionEndTime, + gumTimeMillis: report.gumTimeMillis, + initializationTimeMillis: report.initializationTimeMillis, + iceCollectionTimeMillis: report.iceCollectionTimeMillis, + signallingConnectTimeMillis: report.signallingConnectTimeMillis, + handshakingTimeMillis: report.handshakingTimeMillis, + preTalkingTimeMillis: report.preTalkingTimeMillis, + talkingTimeMillis: report.talkingTimeMillis, + cleanupTimeMillis: report.cleanupTimeMillis, + iceCollectionFailure: report.iceCollectionFailure, + signallingConnectionFailure: report.signallingConnectionFailure, + handshakingFailure: report.handshakingFailure, + gumOtherFailure: report.gumOtherFailure, + gumTimeoutFailure: report.gumTimeoutFailure, + createOfferFailure: report.createOfferFailure, + setLocalDescriptionFailure: report.setLocalDescriptionFailure, + userBusyFailure: report.userBusyFailure, + invalidRemoteSDPFailure: report.invalidRemoteSDPFailure, + noRemoteIceCandidateFailure: report.noRemoteIceCandidateFailure, + setRemoteDescriptionFailure: report.setRemoteDescriptionFailure, + softphoneStreamStatistics: report.streamStats }; - - connect.contact(function (contact) { - contact.onConnecting(onContactConnect); - }); - - new connect.Agent().getContacts().forEach(function (contact) { - if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { - onContactConnect(contact); + contact.sendSoftphoneReport(callReport, { + success: function success() { + logger.info("sendSoftphoneReport success" + JSON.stringify(callReport)).sendInternalLogToServer(); + }, + failure: function failure(data) { + logger.error("sendSoftphoneReport failed.").withObject(data).sendInternalLogToServer(); } }); }; - - - var ChatRingtoneEngine = function (ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); + var startStatsCollectionJob = function startStatsCollectionJob(rtcSession) { + rtpStatsJob = window.setInterval(function () { + rtcSession.getUserAudioStats().then(function (stats) { + var previousUserStats = aggregatedUserAudioStats; + aggregatedUserAudioStats = stats; + timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedUserAudioStats, previousUserStats, AUDIO_INPUT)); + }, function (error) { + logger.debug("Failed to get user audio stats.", error).sendInternalLogToServer(); + }); + rtcSession.getRemoteAudioStats().then(function (stats) { + var previousRemoteStats = aggregatedRemoteAudioStats; + aggregatedRemoteAudioStats = stats; + timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedRemoteAudioStats, previousRemoteStats, AUDIO_OUTPUT)); + }, function (error) { + logger.debug("Failed to get remote audio stats.", error).sendInternalLogToServer(); + }); + }, 1000); }; - ChatRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - ChatRingtoneEngine.prototype.constructor = ChatRingtoneEngine; - - ChatRingtoneEngine.prototype._driveRingtone = function () { - var self = this; - - var onContactConnect = function (contact) { - if (contact.getType() === lily.ContactType.CHAT && contact.isInbound()) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Chat Ringtone Connecting", contact); - connect.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer(); - } - }; - - connect.contact(function (contact) { - contact.onConnecting(onContactConnect); - }); + var startStatsReportingJob = function startStatsReportingJob(contact) { + reportStatsJob = window.setInterval(function () { + sendSoftphoneMetrics(contact); + }, statsReportingJobIntervalMs); }; - - var TaskRingtoneEngine = function (ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); + var initializeParams = function initializeParams() { + aggregatedUserAudioStats = null; + aggregatedRemoteAudioStats = null; + timeSeriesStreamStatsBuffer = []; + rtpStatsJob = null; + reportStatsJob = null; + }; + var getTimeSeriesStats = function getTimeSeriesStats(currentStats, previousStats, streamType) { + if (previousStats && currentStats) { + var packetsLost = currentStats.packetsLost > previousStats.packetsLost ? currentStats.packetsLost - previousStats.packetsLost : 0; + var packetsCount = currentStats.packetsCount > previousStats.packetsCount ? currentStats.packetsCount - previousStats.packetsCount : 0; + return new RTPStreamStats(currentStats.timestamp, packetsLost, packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); + } else { + return new RTPStreamStats(currentStats.timestamp, currentStats.packetsLost, currentStats.packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); + } + }; + var stopJob = function stopJob(task) { + if (task !== null) { + window.clearInterval(task); + } + return null; + }; + var stopJobsAndReport = function stopJobsAndReport(contact, sessionReport) { + rtpStatsJob = stopJob(rtpStatsJob); + reportStatsJob = stopJob(reportStatsJob); + sendSoftphoneReport(contact, sessionReport, addStreamTypeToStats(aggregatedUserAudioStats, AUDIO_INPUT), addStreamTypeToStats(aggregatedRemoteAudioStats, AUDIO_OUTPUT)); + sendSoftphoneMetrics(contact); }; - TaskRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - TaskRingtoneEngine.prototype.constructor = TaskRingtoneEngine; - TaskRingtoneEngine.prototype._driveRingtone = function () { + /** + * Adding streamtype parameter on top of RTCJS RTStats object. + */ + var RTPStreamStats = function RTPStreamStats(timestamp, packetsLost, packetsCount, streamType, audioLevel, jitterBufferMillis, roundTripTimeMillis) { + this.softphoneStreamType = streamType; + this.timestamp = timestamp; + this.packetsLost = packetsLost; + this.packetsCount = packetsCount; + this.audioLevel = audioLevel; + this.jitterBufferMillis = jitterBufferMillis; + this.roundTripTimeMillis = roundTripTimeMillis; + }; + var addStreamTypeToStats = function addStreamTypeToStats(stats, streamType) { + stats = stats || {}; + return new RTPStreamStats(stats.timestamp, stats.packetsLost, stats.packetsCount, streamType, stats.audioLevel); + }; + var SoftphoneLogger = function SoftphoneLogger(logger) { + this._originalLogger = logger; var self = this; - - var onContactConnect = function (contact) { - if (contact.getType() === lily.ContactType.TASK && contact.isInbound()) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Task Ringtone Connecting", contact); - connect.getLog().info("Task Ringtone Connecting").sendInternalLogToServer(); - } + this._tee = function (level, method) { + return function () { + // call the original logger object to output to browser + //Connect logger follows %s format to print objects to console. + var args = Array.prototype.slice.call(arguments[0]); + var format = ""; + args.forEach(function () { + format = format + " %s"; + }); + return method.apply(self._originalLogger, [connect.LogComponent.SOFTPHONE, format].concat(args)); + }; }; - - connect.contact(function (contact) { - contact.onConnecting(onContactConnect); - }); }; + SoftphoneLogger.prototype.debug = function () { + return this._tee(1, this._originalLogger.debug)(arguments); + }; + SoftphoneLogger.prototype.info = function () { + return this._tee(2, this._originalLogger.info)(arguments); + }; + SoftphoneLogger.prototype.log = function () { + return this._tee(3, this._originalLogger.log)(arguments); + }; + SoftphoneLogger.prototype.warn = function () { + return this._tee(4, this._originalLogger.warn)(arguments); + }; + SoftphoneLogger.prototype.error = function () { + return this._tee(5, this._originalLogger.error)(arguments); + }; + connect.SoftphoneManager = SoftphoneManager; +})(); +/***/ }), - var QueueCallbackRingtoneEngine = function (ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); - }; - QueueCallbackRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - QueueCallbackRingtoneEngine.prototype.constructor = QueueCallbackRingtoneEngine; +/***/ 778: +/***/ (() => { - QueueCallbackRingtoneEngine.prototype._driveRingtone = function () { - var self = this; +/*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ - connect.contact(function (contact) { - contact.onIncoming(function () { - if (contact.getType() === lily.ContactType.QUEUE_CALLBACK) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Callback Ringtone Connecting", contact); - connect.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer(); +(function () { + var ctx = this; + var sprintf = function sprintf() { + if (!sprintf.cache.hasOwnProperty(arguments[0])) { + sprintf.cache[arguments[0]] = sprintf.parse(arguments[0]); + } + return sprintf.format.call(null, sprintf.cache[arguments[0]], arguments); + }; + sprintf.format = function (parse_tree, argv) { + var cursor = 1, + tree_length = parse_tree.length, + node_type = '', + arg, + output = [], + i, + k, + match, + pad, + pad_character, + pad_length; + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]); + if (node_type === 'string') { + output.push(parse_tree[i]); + } else if (node_type === 'array') { + match = parse_tree[i]; // convenience purposes only + if (match[2]) { + // keyword argument + arg = argv[cursor]; + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw sprintf('[sprintf] property "%s" does not exist', match[2][k]); + } + arg = arg[match[2][k]]; + } + } else if (match[1]) { + // positional argument (explicit) + arg = argv[match[1]]; + } else { + // positional argument (implicit) + arg = argv[cursor++]; + } + if (/[^s]/.test(match[8]) && get_type(arg) != 'number') { + throw sprintf('[sprintf] expecting number but found %s', get_type(arg)); + } + switch (match[8]) { + case 'b': + arg = arg.toString(2); + break; + case 'c': + arg = String.fromCharCode(arg); + break; + case 'd': + arg = parseInt(arg, 10); + break; + case 'e': + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); + break; + case 'f': + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); + break; + case 'o': + arg = arg.toString(8); + break; + case 's': + arg = (arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg; + break; + case 'u': + arg = arg >>> 0; + break; + case 'x': + arg = arg.toString(16); + break; + case 'X': + arg = arg.toString(16).toUpperCase(); + break; + } + arg = /[def]/.test(match[8]) && match[3] && arg >= 0 ? '+' + arg : arg; + pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; + pad_length = match[6] - String(arg).length; + pad = match[6] ? str_repeat(pad_character, pad_length) : ''; + output.push(match[5] ? arg + pad : pad + arg); + } + } + return output.join(''); + }; + sprintf.cache = {}; + sprintf.parse = function (fmt) { + var _fmt = fmt, + match = [], + parse_tree = [], + arg_names = 0; + while (_fmt) { + if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { + parse_tree.push(match[0]); + } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { + parse_tree.push('%'); + } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1; + var field_list = [], + replacement_field = match[2], + field_match = []; + if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { + if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } else { + throw '[sprintf] huh?'; + } + } + } else { + throw '[sprintf] huh?'; + } + match[2] = field_list; + } else { + arg_names |= 2; } - }); - }); + if (arg_names === 3) { + throw '[sprintf] mixing positional and named placeholders is not (yet) supported'; + } + parse_tree.push(match); + } else { + throw '[sprintf] huh?'; + } + _fmt = _fmt.substring(match[0].length); + } + return parse_tree; + }; + var vsprintf = function vsprintf(fmt, argv, _argv) { + _argv = argv.slice(0); + _argv.splice(0, 0, fmt); + return sprintf.apply(null, _argv); }; - /* export connect.RingtoneEngine */ - connect.VoiceRingtoneEngine = VoiceRingtoneEngine; - connect.ChatRingtoneEngine = ChatRingtoneEngine; - connect.TaskRingtoneEngine = TaskRingtoneEngine; - connect.QueueCallbackRingtoneEngine = QueueCallbackRingtoneEngine; + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); + } + function str_repeat(input, multiplier) { + for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} + return output.join(''); + } + + /** + * export to either browser or node.js + */ + ctx.sprintf = sprintf; + ctx.vsprintf = vsprintf; })(); +/***/ }), + +/***/ 768: +/***/ (() => { + /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -27880,769 +10821,1103 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect = global.connect || {}; global.connect = connect; global.lily = connect; - global.ccpVersion = "V2"; - - var RTPJobIntervalMs = 1000; - var statsReportingJobIntervalMs = 30000; - var streamBufferSize = 500; - var CallTypeMap = {}; - CallTypeMap[connect.SoftphoneCallType.AUDIO_ONLY] = 'Audio'; - CallTypeMap[connect.SoftphoneCallType.VIDEO_ONLY] = 'Video'; - CallTypeMap[connect.SoftphoneCallType.AUDIO_VIDEO] = 'AudioVideo'; - CallTypeMap[connect.SoftphoneCallType.NONE] = 'None'; - var AUDIO_INPUT = 'audio_input'; - var AUDIO_OUTPUT = 'audio_output'; - var MediaTypeMap = {}; - MediaTypeMap[connect.ContactType.VOICE] = "Voice"; - var UNKNOWN_MEDIA_TYPE = "Unknown"; + /**--------------------------------------------------------------- + * class Stream + * + * Represents an object from which messages can be read and to which + * messages can be sent. + */ + var Stream = function Stream() {}; - var timeSeriesStreamStatsBuffer = []; - var aggregatedUserAudioStats = {}; - var aggregatedRemoteAudioStats = {}; - var rtpStatsJob = null; - var reportStatsJob = null; - //Logger specific to softphone. - var logger = null; - var SoftphoneErrorTypes = connect.SoftphoneErrorTypes; - var HANG_UP_MULTIPLE_SESSIONS_EVENT = "MultiSessionHangUp"; - var MULTIPLE_SESSIONS_EVENT = "MultiSessions"; + /** + * Send a message to the stream. This method must be implemented by subclasses. + */ + Stream.prototype.send = function (message) { + throw new connect.NotImplementedError(); + }; - var localMediaStream = {}; + /** + * Provide a method to be called when messages are received from this stream. + * This method must be implemented by subclasses. + */ + Stream.prototype.onMessage = function (f) { + throw new connect.NotImplementedError(); + }; - var softphoneClientId = connect.randomId(); + /**--------------------------------------------------------------- + * class NullStream extends Stream + * + * A null stream which provides no message sending or receiving facilities. + */ + var NullStream = function NullStream() { + Stream.call(this); + }; + NullStream.prototype = Object.create(Stream.prototype); + NullStream.prototype.constructor = NullStream; + NullStream.prototype.onMessage = function (f) {}; + NullStream.prototype.send = function (message) {}; - var requestIceAccess = function (transport) { - return new Promise(function (resolve, reject) { - connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT, transport, { - success: function (data) { - resolve(data.softphoneTransport.softphoneMediaConnections); - }, - failure: function (reason) { - if (reason.message && reason.message.includes("SoftphoneConnectionLimitBreachedException")) { - publishError("multiple_softphone_active_sessions", "Number of active sessions are more then allowed limit.", ""); - } - reject(Error("requestIceAccess failed")); - }, - authFailure: function () { - reject(Error("Authentication failed while requestIceAccess")); - }, - accessDenied: function () { - reject(Error("Access Denied while requestIceAccess")); - } - }); - }); + /**--------------------------------------------------------------- + * class WindowStream extends Stream + * + * A stream for communicating with a window object. The domain provided + * must match the allowed message domains of the downstream receiver + * or messages will be rejected, see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage + * for more info. + */ + var WindowStream = function WindowStream(win, domain) { + Stream.call(this); + this.window = win; + this.domain = domain || '*'; + }; + WindowStream.prototype = Object.create(Stream.prototype); + WindowStream.prototype.constructor = WindowStream; + WindowStream.prototype.send = function (message) { + this.window.postMessage(message, this.domain); + }; + WindowStream.prototype.onMessage = function (f) { + this.window.addEventListener("message", f); }; - var SoftphoneManager = function (softphoneParams) { - var self = this; - logger = new SoftphoneLogger(connect.getLog()); - logger.info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(); - var rtcPeerConnectionFactory; - if (connect.RtcPeerConnectionFactory) { - rtcPeerConnectionFactory = new connect.RtcPeerConnectionFactory(logger, - connect.core.getWebSocketManager(), - softphoneClientId, - connect.hitch(self, requestIceAccess, { - transportType: "softphone", - softphoneClientId: softphoneClientId - }), - connect.hitch(self, publishError)); - } - if (!isBrowserSoftPhoneSupported()) { - publishError(SoftphoneErrorTypes.UNSUPPORTED_BROWSER, - "Connect does not support this browser. Some functionality may not work. ", - ""); - } - var gumPromise = fetchUserMedia({ - success: function (stream) { - connect.core.setSoftphoneUserMediaStream(stream); - }, - failure: function (err) { - publishError(err, "Your microphone is not enabled in your browser. ", ""); + /**--------------------------------------------------------------- + * class WindowIOStream extends Stream + * + * A stream used by IFrame/popup windows to communicate with their parents + * and vise versa. + * + * This object encapsulates the fact that incoming and outgoing messages + * arrive on different windows and allows this to be managed as a single + * Stream object. + */ + var WindowIOStream = function WindowIOStream(inputwin, outputwin, domain) { + Stream.call(this); + this.input = inputwin; + this.output = outputwin; + this.domain = domain || '*'; + }; + WindowIOStream.prototype = Object.create(Stream.prototype); + WindowIOStream.prototype.constructor = WindowIOStream; + WindowIOStream.prototype.send = function (message) { + this.output.postMessage(message, this.domain); + }; + WindowIOStream.prototype.onMessage = function (f) { + var _this = this; + this.input.addEventListener("message", function (message) { + if (message.source === _this.output) { + f(message); } }); - handleSoftPhoneMuteToggle(); - handleSpeakerDeviceChange(); - handleMicrophoneDeviceChange(); - - this.ringtoneEngine = null; - var rtcSessions = {}; - // Tracks the agent connection ID, so that if the same contact gets re-routed to the same agent, it'll still set up softphone - var callsDetected = {}; - this.onInitContactSub = {}; - this.onInitContactSub.unsubscribe = function() {}; + }; - // variables for firefox multitab - var isSessionPending = false; - var pendingContact = null; - var pendingAgentConnectionId = null; - var postponeStartingSession = function (contact, agentConnectionId) { - isSessionPending = true; - pendingContact = contact; - pendingAgentConnectionId = agentConnectionId; - } - var cancelPendingSession = function () { - isSessionPending = false; - pendingContact = null; - pendingAgentConnectionId = null; - } + /**--------------------------------------------------------------- + * class PortStream extends Stream + * + * A stream wrapping an HTML5 Worker port. This could be the port + * used to connect to a Worker or one of the multitude of ports + * made available to a SharedWorker for communication back to + * its connected clients. + */ + var PortStream = function PortStream(port) { + Stream.call(this); + this.port = port; + this.id = connect.randomId(); + }; + PortStream.prototype = Object.create(Stream.prototype); + PortStream.prototype.constructor = PortStream; + PortStream.prototype.send = function (message) { + this.port.postMessage(message); + }; + PortStream.prototype.onMessage = function (f) { + this.port.addEventListener("message", f); + }; + PortStream.prototype.getId = function () { + return this.id; + }; - // helper method to provide access to rtc sessions - this.getSession = function (connectionId) { - return rtcSessions[connectionId]; - } + /**--------------------------------------------------------------- + * class StreamMultiplexer extends Stream + * + * A wrapper for multiplexed downstream communication with + * multiple streams at once. Mainly useful for the SharedWorker to + * broadcast events to many PortStream objects at once. + */ + var StreamMultiplexer = function StreamMultiplexer(streams) { + Stream.call(this); + this.streamMap = streams ? connect.index(streams, function (s) { + return s.getId(); + }) : {}; + this.messageListeners = []; + }; + StreamMultiplexer.prototype = Object.create(Stream.prototype); + StreamMultiplexer.prototype.constructor = StreamMultiplexer; - this.replaceLocalMediaTrack = function(connectionId, track) { - var stream = localMediaStream[connectionId].stream; - if(stream){ - var oldTrack = stream.getAudioTracks()[0]; - track.enabled = oldTrack.enabled; - oldTrack.enabled = false; - stream.removeTrack(oldTrack); - stream.addTrack(track); + /** + * Send a message to all ports in the multiplexer. + */ + StreamMultiplexer.prototype.send = function (message) { + this.getStreams().forEach(function (stream) { + try { + stream.send(message); + } catch (e) { + // Couldn't send message to one of the downstreams for some reason... + // No reliable logging possible without further failures, + // no recovery, just eat it. } - }; + }); + }; - var isContactTerminated = function (contact) { - return contact.getStatus().type === connect.ContactStatusType.ENDED || - contact.getStatus().type === connect.ContactStatusType.ERROR || - contact.getStatus().type === connect.ContactStatusType.MISSED; - }; + /** + * Register a method which will be called when a message is received from + * any of the downstreams. + */ + StreamMultiplexer.prototype.onMessage = function (f) { + this.messageListeners.push(f); - var destroySession = function (agentConnectionId) { - if (rtcSessions.hasOwnProperty(agentConnectionId)) { - var session = rtcSessions[agentConnectionId]; - // Currently the assumption is it will throw an exception only and if only it already has been hung up. - // TODO: Update once the hangup API does not throw exceptions - new Promise(function (resolve, reject) { - delete rtcSessions[agentConnectionId]; - delete callsDetected[agentConnectionId]; - session.hangup(); - }).catch(function (err) { - lily.getLog().warn("Clean up the session locally " + agentConnectionId, err.message).sendInternalLogToServer(); - }); - } - }; + // Update existing streams with the new listener. + this.getStreams().forEach(function (stream) { + stream.onMessage(f); + }); + }; - // When multiple RTC sessions detected, ignore the new call and hang up the previous sessions. - // TODO: Update when connect-rtc exposes an API to detect session status. - var sanityCheckActiveSessions = function (rtcSessions) { - if (Object.keys(rtcSessions).length > 0) { - // Error! our state doesn't match, tear it all down. - for (var connectionId in rtcSessions) { - if (rtcSessions.hasOwnProperty(connectionId)) { - // Log an error for the session we are about to end. - publishMultipleSessionsEvent(HANG_UP_MULTIPLE_SESSIONS_EVENT, rtcSessions[connectionId].callId, connectionId); - destroySession(connectionId); - } - } - throw new Error("duplicate session detected, refusing to setup new connection"); - } - }; + /** + * Add a stream to the multiplexer. + */ + StreamMultiplexer.prototype.addStream = function (stream) { + var self = this; + this.streamMap[stream.getId()] = stream; - this.startSession = function (_contact, _agentConnectionId) { - var contact = isSessionPending ? pendingContact : _contact; - var agentConnectionId = isSessionPending ? pendingAgentConnectionId : _agentConnectionId; - if (!contact || !agentConnectionId) { - return; - } - cancelPendingSession(); - - // Set to true, this will block subsequent invokes from entering. - callsDetected[agentConnectionId] = true; - logger.info("Softphone call detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + // Update stream with existing listeners. + this.messageListeners.forEach(function (messageListener) { + stream.onMessage(messageListener); + }); + }; - // Ensure our session state matches our contact state to prevent issues should we lose track of a contact. - sanityCheckActiveSessions(rtcSessions); + /** + * Remove the given downstream. This is typically used in response + * to the SharedWorker's onclose event, indicating that a consumer + * tab has been closed. + */ + StreamMultiplexer.prototype.removeStream = function (stream) { + delete this.streamMap[stream.getId()]; + }; - if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { - publishTelemetryEvent("Softphone Connecting", contact.getContactId()); - } + /** + * Get a list of streams in the multiplexer. + */ + StreamMultiplexer.prototype.getStreams = function (stream) { + return connect.values(this.streamMap); + }; - initializeParams(); - var softphoneInfo = contact.getAgentConnection().getSoftphoneMediaInfo(); - var callConfig = parseCallConfig(softphoneInfo.callConfigJson); - var webSocketProvider; - if (callConfig.useWebSocketProvider) { - webSocketProvider = connect.core.getWebSocketManager(); - } - var session = new connect.RTCSession( - callConfig.signalingEndpoint, - callConfig.iceServers, - softphoneInfo.callContextToken, - logger, - contact.getContactId(), - agentConnectionId, - webSocketProvider); + /** + * Get the stream matching the given port. + */ + StreamMultiplexer.prototype.getStreamForPort = function (port) { + return connect.find(this.getStreams(), function (s) { + return s.port === port; + }); + }; + + /**--------------------------------------------------------------- + * class Conduit + * + * An object which bridges an upstream and a downstream, allowing messages + * to be passed to and from each and providing an event bus for event + * subscriptions to be made upstream and downstream. + */ + var Conduit = function Conduit(name, upstream, downstream) { + this.name = name; + this.upstream = upstream || new NullStream(); + this.downstream = downstream || new NullStream(); + this.downstreamBus = new connect.EventBus(); + this.upstreamBus = new connect.EventBus(); + this.upstream.onMessage(connect.hitch(this, this._dispatchEvent, this.upstreamBus)); + this.downstream.onMessage(connect.hitch(this, this._dispatchEvent, this.downstreamBus)); + }; + Conduit.prototype.onUpstream = function (eventName, f) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.upstreamBus.subscribe(eventName, f); + }; + Conduit.prototype.onAllUpstream = function (f) { + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.upstreamBus.subscribeAll(f); + }; + Conduit.prototype.onDownstream = function (eventName, f) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.downstreamBus.subscribe(eventName, f); + }; + Conduit.prototype.onAllDownstream = function (f) { + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.downstreamBus.subscribeAll(f); + }; + Conduit.prototype.sendUpstream = function (eventName, data) { + connect.assertNotNull(eventName, 'eventName'); + this.upstream.send({ + event: eventName, + data: data + }); + }; + Conduit.prototype.sendDownstream = function (eventName, data) { + connect.assertNotNull(eventName, 'eventName'); + this.downstream.send({ + event: eventName, + data: data + }); + }; + Conduit.prototype._dispatchEvent = function (bus, messageEvent) { + var message = messageEvent.data; + if (message.event) { + bus.trigger(message.event, message.data); + } + }; + + /** + * Returns a closure which passes events upstream. + * + * Usage: + * conduit.onDownstream("MyEvent", conduit.passUpstream()); + */ + Conduit.prototype.passUpstream = function () { + var self = this; + return function (data, eventName) { + self.upstream.send({ + event: eventName, + data: data + }); + }; + }; - rtcSessions[agentConnectionId] = session; + /** + * Returns a closure which passes events downstream. + * + * Usage: + * conduit.onUpstream("MyEvent", conduit.passDownstream()); + */ + Conduit.prototype.passDownstream = function () { + var self = this; + return function (data, eventName) { + self.downstream.send({ + event: eventName, + data: data + }); + }; + }; - if (connect.core.getSoftphoneUserMediaStream()) { - session.mediaStream = connect.core.getSoftphoneUserMediaStream(); - } + /** + * Shutdown the conduit's event busses and remove all subscriptions. + */ + Conduit.prototype.shutdown = function () { + this.upstreamBus.unsubscribeAll(); + this.downstreamBus.unsubscribeAll(); + }; - // Custom Event to indicate the session init operations - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConnectionEvents.SESSION_INIT, - data: { - connectionId: agentConnectionId - } - }); + /**--------------------------------------------------------------- + * class IFrameConduit extends Conduit + * + * Creates a conduit for the given IFrame element. + */ + var IFrameConduit = function IFrameConduit(name, window, iframe, domain) { + Conduit.call(this, name, new WindowIOStream(window, iframe.contentWindow, domain || '*'), null); + }; + IFrameConduit.prototype = Object.create(Conduit.prototype); + IFrameConduit.prototype.constructor = IFrameConduit; + connect.Stream = Stream; + connect.NullStream = NullStream; + connect.WindowStream = WindowStream; + connect.WindowIOStream = WindowIOStream; + connect.PortStream = PortStream; + connect.StreamMultiplexer = StreamMultiplexer; + connect.Conduit = Conduit; + connect.IFrameConduit = IFrameConduit; +})(); - session.onSessionFailed = function (rtcSession, reason) { - delete rtcSessions[agentConnectionId]; - delete callsDetected[agentConnectionId]; - publishSoftphoneFailureLogs(rtcSession, reason); - publishSessionFailureTelemetryEvent(contact.getContactId(), reason); - stopJobsAndReport(contact, rtcSession.sessionReport); - }; - session.onSessionConnected = function (rtcSession) { - publishTelemetryEvent("Softphone Session Connected", contact.getContactId()); - // Become master to send logs, since we need logs from softphone tab. - connect.becomeMaster(connect.MasterTopics.SEND_LOGS); - //start stats collection and reporting jobs - startStatsCollectionJob(rtcSession); - startStatsReportingJob(contact); - fireContactAcceptedEvent(contact); - }; +/***/ }), - session.onSessionCompleted = function (rtcSession) { - publishTelemetryEvent("Softphone Session Completed", contact.getContactId()); +/***/ 738: +/***/ (() => { - delete rtcSessions[agentConnectionId]; - delete callsDetected[agentConnectionId]; - // Stop all jobs and perform one last job. - stopJobsAndReport(contact, rtcSession.sessionReport); +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; - // Cleanup the cached streams - deleteLocalMediaStream(agentConnectionId); - }; + /**------------------------------------------------------------------------- + * GraphLink <> + * + * Represents the association of one or more attributes to a state transition. + */ + var GraphLink = function GraphLink(fromState, toState) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + this.fromState = fromState; + this.toState = toState; + }; + GraphLink.prototype.getAssociations = function (context) { + throw connect.NotImplementedError(); + }; + GraphLink.prototype.getFromState = function () { + return this.fromState; + }; + GraphLink.prototype.getToState = function () { + return this.toState; + }; - session.onLocalStreamAdded = function (rtcSession, stream) { - // Cache the streams for mute/unmute - localMediaStream[agentConnectionId] = { - stream: stream - }; - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, - data: { - connectionId: agentConnectionId - } - }); - }; + /**------------------------------------------------------------------------- + * DirectGraphLink <> extends GraphLink + * + * Represents the by-value representation of one or more attributes to a + * state transition. + */ + var DirectGraphLink = function DirectGraphLink(fromState, toState, associations) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + connect.assertNotNull(associations, 'associations'); + GraphLink.call(this, fromState, toState); + this.associations = associations; + }; + DirectGraphLink.prototype = Object.create(GraphLink.prototype); + DirectGraphLink.prototype.constructor = DirectGraphLink; + DirectGraphLink.prototype.getAssociations = function (context) { + return this.associations; + }; - session.remoteAudioElement = document.getElementById('remote-audio'); - if (rtcPeerConnectionFactory) { - session.connect(rtcPeerConnectionFactory.get(callConfig.iceServers)); + /** + * FunctionalGraphLink <> extends GraphLink + * + * Represents a functional association of one or more attributes to a + * state transition. + */ + var FunctionalGraphLink = function FunctionalGraphLink(fromState, toState, closure) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + connect.assertNotNull(closure, 'closure'); + connect.assertTrue(connect.isFunction(closure), 'closure must be a function'); + GraphLink.call(this, fromState, toState); + this.closure = closure; + }; + FunctionalGraphLink.prototype = Object.create(GraphLink.prototype); + FunctionalGraphLink.prototype.constructor = FunctionalGraphLink; + FunctionalGraphLink.prototype.getAssociations = function (context) { + return this.closure(context, this.getFromState(), this.getToState()); + }; + + /**------------------------------------------------------------------------- + * EventGraph <> + * + * Builds a map of associations from one state to another in context of a + * particular object. The associations can be direct (one or more values) + * or functional (a method returning one or more values), and are used to + * provide additional contextual event hooks for the UI to consume. + */ + var EventGraph = function EventGraph() { + this.fromMap = {}; + }; + EventGraph.ANY = "<>"; + EventGraph.prototype.assoc = function (fromStateObj, toStateObj, assocObj) { + var self = this; + if (!fromStateObj) { + throw new Error("fromStateObj is not defined."); + } + if (!toStateObj) { + throw new Error("toStateObj is not defined."); + } + if (!assocObj) { + throw new Error("assocObj is not defined."); + } + if (fromStateObj instanceof Array) { + fromStateObj.forEach(function (fromState) { + self.assoc(fromState, toStateObj, assocObj); + }); + } else if (toStateObj instanceof Array) { + toStateObj.forEach(function (toState) { + self.assoc(fromStateObj, toState, assocObj); + }); + } else { + if (typeof assocObj === "function") { + this._addAssociation(new FunctionalGraphLink(fromStateObj, toStateObj, assocObj)); + } else if (assocObj instanceof Array) { + this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, assocObj)); } else { - session.connect(); + this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, [assocObj])); } } + return this; + }; + EventGraph.prototype.getAssociations = function (context, fromState, toState) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + var associations = []; + var toMapFromAny = this.fromMap[EventGraph.ANY] || {}; + var toMap = this.fromMap[fromState] || {}; + associations = associations.concat(this._getAssociationsFromMap(toMapFromAny, context, fromState, toState)); + associations = associations.concat(this._getAssociationsFromMap(toMap, context, fromState, toState)); + return associations; + }; + EventGraph.prototype._addAssociation = function (assoc) { + var toMap = this.fromMap[assoc.getFromState()]; + if (!toMap) { + toMap = this.fromMap[assoc.getFromState()] = {}; + } + var assocList = toMap[assoc.getToState()]; + if (!assocList) { + assocList = toMap[assoc.getToState()] = []; + } + assocList.push(assoc); + }; + EventGraph.prototype._getAssociationsFromMap = function (map, context, fromState, toState) { + var assocList = (map[EventGraph.ANY] || []).concat(map[toState] || []); + return assocList.reduce(function (prev, assoc) { + return prev.concat(assoc.getAssociations(context)); + }, []); + }; + connect.EventGraph = EventGraph; +})(); - var onRefreshContact = function (contact, agentConnectionId) { - if (rtcSessions[agentConnectionId] && isContactTerminated(contact)) { - destroySession(agentConnectionId); - cancelPendingSession(); - } - if (contact.isSoftphoneCall() && !callsDetected[agentConnectionId] && ( - contact.getStatus().type === connect.ContactStatusType.CONNECTING || - contact.getStatus().type === connect.ContactStatusType.INCOMING)) { - if (connect.isFirefoxBrowser() && connect.hasOtherConnectedCCPs()) { - postponeStartingSession(contact, agentConnectionId); - } else { - self.startSession(contact, agentConnectionId); - } - } - }; +/***/ }), - var onInitContact = function (contact) { - var agentConnectionId = contact.getAgentConnection().connectionId; - logger.info("Contact detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); +/***/ 420: +/***/ (() => { - if (!callsDetected[agentConnectionId]) { - contact.onRefresh(function () { - onRefreshContact(contact, agentConnectionId); - }); - } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + var userAgent = navigator.userAgent; + var ONE_DAY_MILLIS = 24 * 60 * 60 * 1000; + var DEFAULT_POPUP_HEIGHT = 578; + var DEFAULT_POPUP_WIDTH = 433; + var COPYABLE_EVENT_FIELDS = ["bubbles", "cancelBubble", "cancelable", "composed", "data", "defaultPrevented", "eventPhase", "isTrusted", "lastEventId", "origin", "returnValue", "timeStamp", "type"]; + + /** + * Unpollute sprintf functions from the global namespace. + */ + connect.sprintf = global.sprintf; + connect.vsprintf = global.vsprintf; + delete global.sprintf; + delete global.vsprintf; + connect.HTTP_STATUS_CODES = { + SUCCESS: 200, + TOO_MANY_REQUESTS: 429, + INTERNAL_SERVER_ERROR: 500 + }; + connect.TRANSPORT_TYPES = { + CHAT_TOKEN: "chat_token", + WEB_SOCKET: "web_socket" + }; + + /** + * Binds the given instance object as the context for + * the method provided. + * + * @param scope The instance object to be set as the scope + * of the function. + * @param method The method to be encapsulated. + * + * All other arguments, if any, are bound to the method + * invocation inside the closure. + * + * @return A closure encapsulating the invocation of the + * method provided in context of the given instance. + */ + connect.hitch = function () { + var args = Array.prototype.slice.call(arguments); + var scope = args.shift(); + var method = args.shift(); + connect.assertNotNull(scope, 'scope'); + connect.assertNotNull(method, 'method'); + connect.assertTrue(connect.isFunction(method), 'method must be a function'); + return function () { + var closureArgs = Array.prototype.slice.call(arguments); + return method.apply(scope, args.concat(closureArgs)); }; + }; - self.onInitContactSub = connect.contact(onInitContact); + /** + * Determine if the given value is a callable function type. + * Borrowed from Underscore.js. + */ + connect.isFunction = function (obj) { + return !!(obj && obj.constructor && obj.call && obj.apply); + }; - // Contact already in connecting state scenario - In this case contact INIT is missed hence the OnRefresh callback is missed. - new connect.Agent().getContacts().forEach(function (contact) { - var agentConnectionId = contact.getAgentConnection().connectionId; - logger.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId" + contact.getContactId(), "agent connectionId " + agentConnectionId) - .sendInternalLogToServer(); - onInitContact(contact); - onRefreshContact(contact, agentConnectionId); + /** + * Determine if the given value is an array. + */ + connect.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + /** + * Get a list of keys from a Javascript object used + * as a hash map. + */ + connect.keys = function (map) { + var keys = []; + connect.assertNotNull(map, 'map'); + for (var k in map) { + keys.push(k); + } + return keys; + }; + + /** + * Get a list of values from a Javascript object used + * as a hash map. + */ + connect.values = function (map) { + var values = []; + connect.assertNotNull(map, 'map'); + for (var k in map) { + values.push(map[k]); + } + return values; + }; + + /** + * Get a list of key/value pairs from the given map. + */ + connect.entries = function (map) { + var entries = []; + for (var k in map) { + entries.push({ + key: k, + value: map[k] + }); + } + return entries; + }; + + /** + * Merge two or more maps together into a new map, + * or simply copy a single map. + */ + connect.merge = function () { + var argMaps = Array.prototype.slice.call(arguments, 0); + var resultMap = {}; + argMaps.forEach(function (map) { + connect.entries(map).forEach(function (kv) { + resultMap[kv.key] = kv.value; + }); }); + return resultMap; }; - - var fireContactAcceptedEvent = function (contact) { - var conduit = connect.core.getUpstream(); - var agentConnection = contact.getAgentConnection(); - if (!agentConnection) { - logger.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer(); - return; + connect.now = function () { + return new Date().getTime(); + }; + connect.find = function (array, predicate) { + for (var x = 0; x < array.length; x++) { + if (predicate(array[x])) { + return array[x]; + } } - var softphoneMediaInfo = agentConnection.getSoftphoneMediaInfo(); - if (!softphoneMediaInfo) { - logger.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer(); - return; + return null; + }; + connect.contains = function (obj, value) { + if (obj instanceof Array) { + return connect.find(obj, function (v) { + return v === value; + }) != null; + } else { + return value in obj; } - if (softphoneMediaInfo.autoAccept === true) { - logger.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.ContactEvents.ACCEPTED, - data: new connect.Contact(contact.contactId) - }); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, contact.contactId), - data: new connect.Contact(contact.contactId) - }); + }; + connect.containsValue = function (obj, value) { + if (obj instanceof Array) { + return connect.find(obj, function (v) { + return v === value; + }) != null; } else { - logger.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer(); + return connect.find(connect.values(obj), function (v) { + return v === value; + }) != null; } }; - // Bind events for mute - var handleSoftPhoneMuteToggle = function () { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.MUTE, muteToggle); + /** + * Generate a random ID consisting of the current timestamp + * and a random base-36 number based on Math.random(). + */ + connect.randomId = function () { + return connect.sprintf("%s-%s", connect.now(), Math.random().toString(36).slice(2)); }; - var handleSpeakerDeviceChange = function() { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE, setSpeakerDevice); - } - - var handleMicrophoneDeviceChange = function () { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, setMicrophoneDevice); - } - - // Make sure once we disconnected we get the mute state back to normal - var deleteLocalMediaStream = function (connectionId) { - delete localMediaStream[connectionId]; - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.MUTE_TOGGLE, - data: { muted: false } + /** + * Generate an enum from the given list of lower-case enum values, + * where the enum keys will be upper case. + * + * Conversion from pascal case based on code from here: + * http://stackoverflow.com/questions/30521224 + */ + connect.makeEnum = function (values) { + var enumObj = {}; + values.forEach(function (value) { + var key = value.replace(/\.?([a-z]+)_?/g, function (x, y) { + return y.toUpperCase() + "_"; + }).replace(/_$/, ""); + enumObj[key] = value; }); + return enumObj; }; - - // Check for the local streams if exists - revert it - // And inform other clients about the change - var muteToggle = function (data) { - var status; - if (connect.keys(localMediaStream).length === 0) { - return; - } - - if (data && data.mute !== undefined) { - status = data.mute; - } - - for (var connectionId in localMediaStream) { - if (localMediaStream.hasOwnProperty(connectionId)) { - var localMedia = localMediaStream[connectionId].stream; - if (localMedia) { - var audioTracks = localMedia.getAudioTracks()[0]; - if (status !== undefined) { - audioTracks.enabled = !status; - localMediaStream[connectionId].muted = status; - - if (status) { - logger.info("Agent has muted the contact, connectionId - " + connectionId).sendInternalLogToServer(); - } else { - logger.info("Agent has unmuted the contact, connectionId - " + connectionId).sendInternalLogToServer(); - } - - } else { - status = localMediaStream[connectionId].muted || false; - } - } - } - } - - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.MUTE_TOGGLE, - data: { muted: status } + connect.makeNamespacedEnum = function (prefix, values) { + var enumObj = connect.makeEnum(values); + connect.keys(enumObj).forEach(function (key) { + enumObj[key] = connect.sprintf("%s::%s", prefix, enumObj[key]); }); + return enumObj; }; - - var setSpeakerDevice = function (data) { - if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { - return; - } - var deviceId = data.deviceId; - var remoteAudioElement = document.getElementById('remote-audio'); - try { - logger.info("Trying to set speaker to device " + deviceId); - if (remoteAudioElement && typeof remoteAudioElement.setSinkId === 'function') { - remoteAudioElement.setSinkId(deviceId); - } - } catch (e) { - logger.error("Failed to set speaker to device " + deviceId); - } - - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, - data: { deviceId: deviceId } + connect.makeGenericNamespacedEnum = function (prefix, values, delimiter) { + var enumObj = connect.makeEnum(values); + connect.keys(enumObj).forEach(function (key) { + enumObj[key] = connect.sprintf("%s" + delimiter + "%s", prefix, enumObj[key]); }); - } + return enumObj; + }; - var setMicrophoneDevice = function (data) { - if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { - return; - } - var deviceId = data.deviceId; - var softphoneManager = connect.core.getSoftphoneManager(); - try { - navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: deviceId } } }) - .then(function (newMicrophoneStream) { - var newMicrophoneTrack = newMicrophoneStream.getAudioTracks()[0]; - for (var connectionId in localMediaStream) { - if (localMediaStream.hasOwnProperty(connectionId)) { - var localMedia = localMediaStream[connectionId].stream; - var session = softphoneManager.getSession(connectionId); - //Replace the audio track in the RtcPeerConnection - session._pc.getSenders()[0].replaceTrack(newMicrophoneTrack).then(function () { - //Replace the audio track in the local media stream (for mute / unmute) - softphoneManager.replaceLocalMediaTrack(connectionId, newMicrophoneTrack); - }); - } - } - }); - } catch(e) { - logger.error("Failed to set microphone device " + deviceId); + /** + * Methods to determine browser type and versions, used for softphone initialization. + */ + connect.isChromeBrowser = function () { + return userAgent.indexOf("Chrome") !== -1; + }; + connect.isFirefoxBrowser = function () { + return userAgent.indexOf("Firefox") !== -1; + }; + connect.isOperaBrowser = function () { + return userAgent.indexOf("Opera") !== -1; + }; + connect.getChromeBrowserVersion = function () { + var chromeVersion = userAgent.substring(userAgent.indexOf("Chrome") + 7); + if (chromeVersion) { + return parseFloat(chromeVersion); + } else { + return -1; } - - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, - data: { deviceId: deviceId } - }); - } - - var publishSoftphoneFailureLogs = function (rtcSession, reason) { - if (reason === connect.RTCErrors.ICE_COLLECTION_TIMEOUT) { - var endPointUrl = "\n"; - for (var i = 0; i < rtcSession._iceServers.length; i++) { - for (var j = 0; j < rtcSession._iceServers[i].urls.length; j++) { - endPointUrl = endPointUrl + rtcSession._iceServers[i].urls[j] + "\n"; - } - } - publishError(SoftphoneErrorTypes.ICE_COLLECTION_TIMEOUT, "Ice collection timedout. ", endPointUrl); - } else if (reason === connect.RTCErrors.USER_BUSY) { - publishError(SoftphoneErrorTypes.USER_BUSY_ERROR, - "Softphone call UserBusy error. ", - ""); - } else if (reason === connect.RTCErrors.SIGNALLING_HANDSHAKE_FAILURE) { - publishError(SoftphoneErrorTypes.SIGNALLING_HANDSHAKE_FAILURE, - "Handshaking with Signalling Server " + rtcSession._signalingUri + " failed. ", - rtcSession._signalingUri); - } else if (reason === connect.RTCErrors.GUM_TIMEOUT_FAILURE || reason === connect.RTCErrors.GUM_OTHER_FAILURE) { - publishError(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED, - "Your microphone is not enabled in your browser. ", - ""); - } else if (reason === connect.RTCErrors.SIGNALLING_CONNECTION_FAILURE) { - publishError(SoftphoneErrorTypes.SIGNALLING_CONNECTION_FAILURE, - "URL " + rtcSession._signalingUri + " cannot be reached. ", - rtcSession._signalingUri); - } else if (reason === connect.RTCErrors.CALL_NOT_FOUND) { - // No need to publish any softphone error for this case. CCP UX will handle this case. - logger.error("Softphone call failed due to CallNotFoundException.").sendInternalLogToServer(); + }; + connect.getFirefoxBrowserVersion = function () { + var firefoxVersion = userAgent.substring(userAgent.indexOf("Firefox") + 8); + if (firefoxVersion) { + return parseFloat(firefoxVersion); } else { - publishError(SoftphoneErrorTypes.WEBRTC_ERROR, - "webrtc system error. ", - ""); + return -1; } }; - - /** Parse the JSON encoded web call config into the data it represents. */ - var parseCallConfig = function (serializedConfig) { - // Our underscore is too old for unescape - // https://issues.amazon.com/issues/CSWF-1467 - var decodedJSON = serializedConfig.replace(/"/g, '"'); - return JSON.parse(decodedJSON); + connect.isValidLocale = function (locale) { + var languages = [{ + id: 'en_US', + label: 'English' + }, { + id: 'de_DE', + label: 'Deutsch' + }, { + id: 'es_ES', + label: 'Español' + }, { + id: 'fr_FR', + label: 'Français' + }, { + id: 'ja_JP', + label: '日本語' + }, { + id: 'it_IT', + label: 'Italiano' + }, { + id: 'ko_KR', + label: '한국어' + }, { + id: 'pt_BR', + label: 'Português' + }, { + id: 'zh_CN', + label: '中文(简体)' + }, { + id: 'zh_TW', + label: '中文(繁體)' + }]; + return languages.map(function (language) { + return language.id; + }).includes(locale); }; - - var fetchUserMedia = function (callbacksIn) { - var callbacks = callbacksIn || {}; - callbacks.success = callbacks.success || function () { }; - callbacks.failure = callbacks.failure || function () { }; - - var CONSTRAINT = { - audio: true - }; - - var promise = null; - - if (typeof Promise !== "function") { - callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); - return; - } - - if (typeof navigator.mediaDevices === "object" && typeof navigator.mediaDevices.getUserMedia === "function") { - promise = navigator.mediaDevices.getUserMedia(CONSTRAINT); - - } else if (typeof navigator.webkitGetUserMedia === "function") { - promise = new Promise(function (resolve, reject) { - navigator.webkitGetUserMedia(CONSTRAINT, resolve, reject); - }); - + connect.getOperaBrowserVersion = function () { + var versionOffset = userAgent.indexOf("Opera"); + var operaVersion = userAgent.indexOf("Version") !== -1 ? userAgent.substring(versionOffset + 8) : userAgent.substring(versionOffset + 6); + if (operaVersion) { + return parseFloat(operaVersion); } else { - callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); - return; + return -1; } + }; - promise.then(function (stream) { - var audioTracks = stream.getAudioTracks(); - if (audioTracks && audioTracks.length > 0) { - callbacks.success(stream); - } else { - callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); - } - }, function (err) { - callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); + /** + * Return a map of items in the given list indexed by + * keys determined by the closure provided. + * + * @param iterable A list-like object. + * @param closure A closure to determine the index for the + * items in the iterable. + * @return A map from index to item for each item in the iterable. + */ + connect.index = function (iterable, closure) { + var map = {}; + iterable.forEach(function (item) { + map[closure(item)] = item; }); - return promise; + return map; }; - var publishError = function (errorType, message, endPointUrl) { - logger.error("Softphone error occurred : ", errorType, - message || "").sendInternalLogToServer(); - - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.SOFTPHONE_ERROR, - data: new connect.SoftphoneError(errorType, message, endPointUrl) + /** + * Converts the given array into a map as a set, + * where elements in the array are mapped to 1. + */ + connect.set = function (arrayIn) { + var setMap = {}; + arrayIn.forEach(function (key) { + setMap[key] = 1; }); + return setMap; }; - var publishSessionFailureTelemetryEvent = function (contactId, reason) { - publishTelemetryEvent("Softphone Session Failed", contactId, { - failedReason: reason + /** + * Returns a map for each key in mapB which + * is NOT in mapA. + */ + connect.relativeComplement = function (mapA, mapB) { + var compMap = {}; + connect.keys(mapB).forEach(function (key) { + if (!(key in mapA)) { + compMap[key] = mapB[key]; + } }); + return compMap; }; - var publishTelemetryEvent = function (eventName, contactId, data) { - if (contactId) { - connect.publishMetric({ - name: eventName, - contactId: contactId, - data: data - }); + /** + * Asserts that a premise is true. + */ + connect.assertTrue = function (premise, message) { + if (!premise) { + throw new connect.ValueError(message); } }; - // Publish the contact and agent information in a multiple sessions scenarios - var publishMultipleSessionsEvent = function (eventName, contactId, agentConnectionId) { - publishTelemetryEvent(eventName, contactId, [{ - name: "AgentConnectionId", - value: agentConnectionId - }]); - logger.info("Publish multiple session error metrics", eventName, "contactId " + contactId, "agent connectionId " + agentConnectionId) - .sendInternalLogToServer(); + /** + * Asserts that a value is not null or undefined. + */ + connect.assertNotNull = function (value, name) { + connect.assertTrue(value != null && _typeof(value) !== undefined, connect.sprintf("%s must be provided", name || 'A value')); + return value; + }; + connect.deepcopy = function (src) { + return JSON.parse(JSON.stringify(src)); + }; + connect.deepcopyCrossOriginEvent = function (event) { + var obj = {}; + var listOfAcceptableKeys = COPYABLE_EVENT_FIELDS; + listOfAcceptableKeys.forEach(function (key) { + try { + obj[key] = event[key]; + } catch (e) { + connect.getLog().info("deepcopyCrossOriginEvent failed on key: ", key).sendInternalLogToServer(); + } + }); + return connect.deepcopy(obj); }; - var isBrowserSoftPhoneSupported = function () { - // In Opera, the true version is after "Opera" or after "Version" - if (connect.isOperaBrowser() && connect.getOperaBrowserVersion() > 17) { - return true; - } - // In Chrome, the true version is after "Chrome" - else if (connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 22) { - return true; - } - // In Firefox, the true version is after "Firefox" - else if (connect.isFirefoxBrowser() && connect.getFirefoxBrowserVersion() > 21) { - return true; - } else { - return false; + /** + * Get the current base url of the open page, e.g. if the page is + * https://example.com:9494/oranges, this will be "https://example.com:9494". + */ + connect.getBaseUrl = function () { + var location = global.location; + return connect.sprintf("%s//%s:%s", location.protocol, location.hostname, location.port); + }; + connect.getUrlWithProtocol = function (url) { + var protocol = global.location.protocol; + if (url.substr(0, protocol.length) !== protocol) { + return connect.sprintf("%s//%s", protocol, url); } + return url; }; - var sendSoftphoneMetrics = function (contact) { - var streamStats = timeSeriesStreamStatsBuffer.slice(); - timeSeriesStreamStatsBuffer = []; - if (streamStats.length > 0) { - contact.sendSoftphoneMetrics(streamStats, { - success: function () { - logger.info("sendSoftphoneMetrics success" + JSON.stringify(streamStats)) - .sendInternalLogToServer(); - }, - failure: function (data) { - logger.error("sendSoftphoneMetrics failed.") - .withObject(data) - .sendInternalLogToServer(); - } - }); + /** + * Determine if the current window is in an iframe. + * Courtesy: http://stackoverflow.com/questions/326069/ + */ + connect.isFramed = function () { + try { + return window.self !== window.top; + } catch (e) { + return true; } }; + connect.hasOtherConnectedCCPs = function () { + return connect.numberOfConnectedCCPs > 1; + }; + connect.fetch = function (endpoint, options, milliInterval, maxRetry) { + maxRetry = maxRetry || 5; + milliInterval = milliInterval || 1000; + options = options || {}; + return new Promise(function (resolve, reject) { + function fetchData(maxRetry) { + fetch(endpoint, options).then(function (res) { + if (res.status === connect.HTTP_STATUS_CODES.SUCCESS) { + res.json().then(function (json) { + return resolve(json); + })["catch"](function () { + return resolve({}); + }); + } else if (maxRetry !== 1 && (res.status >= connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR || res.status === connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)) { + setTimeout(function () { + fetchData(--maxRetry); + }, milliInterval); + } else { + reject(res); + } + })["catch"](function (e) { + reject(e); + }); + } + fetchData(maxRetry); + }); + }; - var sendSoftphoneReport = function (contact, report, userAudioStats, remoteAudioStats) { - report.streamStats = [addStreamTypeToStats(userAudioStats, AUDIO_INPUT), - addStreamTypeToStats(remoteAudioStats, AUDIO_OUTPUT)]; - var callReport = { - callStartTime: report.sessionStartTime, - callEndTime: report.sessionEndTime, - gumTimeMillis: report.gumTimeMillis, - initializationTimeMillis: report.initializationTimeMillis, - iceCollectionTimeMillis: report.iceCollectionTimeMillis, - signallingConnectTimeMillis: report.signallingConnectTimeMillis, - handshakingTimeMillis: report.handshakingTimeMillis, - preTalkingTimeMillis: report.preTalkingTimeMillis, - talkingTimeMillis: report.talkingTimeMillis, - cleanupTimeMillis: report.cleanupTimeMillis, - iceCollectionFailure: report.iceCollectionFailure, - signallingConnectionFailure: report.signallingConnectionFailure, - handshakingFailure: report.handshakingFailure, - gumOtherFailure: report.gumOtherFailure, - gumTimeoutFailure: report.gumTimeoutFailure, - createOfferFailure: report.createOfferFailure, - setLocalDescriptionFailure: report.setLocalDescriptionFailure, - userBusyFailure: report.userBusyFailure, - invalidRemoteSDPFailure: report.invalidRemoteSDPFailure, - noRemoteIceCandidateFailure: report.noRemoteIceCandidateFailure, - setRemoteDescriptionFailure: report.setRemoteDescriptionFailure, - softphoneStreamStatistics: report.streamStats - }; - contact.sendSoftphoneReport(callReport, { - success: function () { - logger.info("sendSoftphoneReport success" + JSON.stringify(callReport)) - .sendInternalLogToServer(); + /** + * Calling a function with exponential backoff with full jitter retry strategy + * It will retry calling the function for maximum maxRetry times if it fails. + * Success callback will be called if the function succeeded. + * Failure callback will be called only if the last try failed. + */ + connect.backoff = function (func, milliInterval, maxRetry, callbacks) { + connect.assertTrue(connect.isFunction(func), "func must be a Function"); + var self = this; + var ratio = 2; + func({ + success: function success(data) { + if (callbacks && callbacks.success) { + callbacks.success(data); + } }, - failure: function (data) { - logger.error("sendSoftphoneReport failed.") - .withObject(data) - .sendInternalLogToServer(); + failure: function failure(err, data) { + if (maxRetry > 0) { + var interval = milliInterval * 2 * Math.random(); + global.setTimeout(function () { + self.backoff(func, interval * ratio, --maxRetry, callbacks); + }, interval); + } else { + if (callbacks && callbacks.failure) { + callbacks.failure(err, data); + } + } } }); }; - - var startStatsCollectionJob = function (rtcSession) { - rtpStatsJob = window.setInterval(function () { - rtcSession.getUserAudioStats().then(function (stats) { - var previousUserStats = aggregatedUserAudioStats; - aggregatedUserAudioStats = stats; - timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedUserAudioStats, previousUserStats, AUDIO_INPUT)); - }, function (error) { - logger.debug("Failed to get user audio stats.", error).sendInternalLogToServer(); - }); - rtcSession.getRemoteAudioStats().then(function (stats) { - var previousRemoteStats = aggregatedRemoteAudioStats; - aggregatedRemoteAudioStats = stats; - timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedRemoteAudioStats, previousRemoteStats, AUDIO_OUTPUT)); - }, function (error) { - logger.debug("Failed to get remote audio stats.", error).sendInternalLogToServer(); - }); - }, 1000); + connect.publishMetric = function (metricData) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.CLIENT_METRIC, + data: metricData + }); }; - - var startStatsReportingJob = function (contact) { - reportStatsJob = window.setInterval(function () { - sendSoftphoneMetrics(contact); - }, statsReportingJobIntervalMs); + connect.publishSoftphoneStats = function (stats) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.SOFTPHONE_STATS, + data: stats + }); }; - - var initializeParams = function () { - aggregatedUserAudioStats = null; - aggregatedRemoteAudioStats = null; - timeSeriesStreamStatsBuffer = []; - rtpStatsJob = null; - reportStatsJob = null; + connect.publishSoftphoneReport = function (report) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.SOFTPHONE_REPORT, + data: report + }); + }; + connect.publishClientSideLogs = function (logs) { + var bus = connect.core.getEventBus(); + bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); }; - var getTimeSeriesStats = function (currentStats, previousStats, streamType) { - if (previousStats && currentStats) { - var packetsLost = currentStats.packetsLost > previousStats.packetsLost ? currentStats.packetsLost - previousStats.packetsLost : 0; - var packetsCount = currentStats.packetsCount > previousStats.packetsCount ? currentStats.packetsCount - previousStats.packetsCount : 0; - return new RTPStreamStats(currentStats.timestamp, - packetsLost, - packetsCount, - streamType, - currentStats.audioLevel, - currentStats.jbMilliseconds, - currentStats.rttMilliseconds); + /** + * A wrapper around Window.open() for managing single instance popups. + */ + connect.PopupManager = function () {}; + connect.PopupManager.prototype.open = function (url, name, options) { + var then = this._getLastOpenedTimestamp(name); + var now = new Date().getTime(); + var win = null; + if (now - then > ONE_DAY_MILLIS) { + if (options) { + // default values are chosen to provide a minimum height without scrolling + // and a uniform margin based on the css of the ccp login page + var height = options.height || DEFAULT_POPUP_HEIGHT; + var width = options.width || DEFAULT_POPUP_WIDTH; + var top = options.top || 0; + var left = options.left || 0; + win = window.open('', name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); + if (win.location !== url) { + win = window.open(url, name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); + } + } else { + win = window.open('', name); + if (win.location !== url) { + win = window.open(url, name); + } + } + this._setLastOpenedTimestamp(name, now); + } + return win; + }; + connect.PopupManager.prototype.clear = function (name) { + var key = this._getLocalStorageKey(name); + global.localStorage.removeItem(key); + }; + connect.PopupManager.prototype._getLastOpenedTimestamp = function (name) { + var key = this._getLocalStorageKey(name); + var value = global.localStorage.getItem(key); + if (value) { + return parseInt(value, 10); } else { - return new RTPStreamStats(currentStats.timestamp, - currentStats.packetsLost, - currentStats.packetsCount, - streamType, - currentStats.audioLevel, - currentStats.jbMilliseconds, - currentStats.rttMilliseconds); + return 0; } }; - - var stopJob = function (task) { - if (task !== null) { - window.clearInterval(task); - } - return null; + connect.PopupManager.prototype._setLastOpenedTimestamp = function (name, ts) { + var key = this._getLocalStorageKey(name); + global.localStorage.setItem(key, '' + ts); }; - - var stopJobsAndReport = function (contact, sessionReport) { - rtpStatsJob = stopJob(rtpStatsJob); - reportStatsJob = stopJob(reportStatsJob); - sendSoftphoneReport(contact, sessionReport, addStreamTypeToStats(aggregatedUserAudioStats, AUDIO_INPUT), addStreamTypeToStats(aggregatedRemoteAudioStats, AUDIO_OUTPUT)); - sendSoftphoneMetrics(contact); + connect.PopupManager.prototype._getLocalStorageKey = function (name) { + return "connectPopupManager::" + name; }; /** - * Adding streamtype parameter on top of RTCJS RTStats object. - */ - var RTPStreamStats = function (timestamp, packetsLost, packetsCount, streamType, audioLevel, jitterBufferMillis, roundTripTimeMillis) { - this.softphoneStreamType = streamType; - this.timestamp = timestamp; - this.packetsLost = packetsLost; - this.packetsCount = packetsCount; - this.audioLevel = audioLevel; - this.jitterBufferMillis = jitterBufferMillis; - this.roundTripTimeMillis = roundTripTimeMillis; - }; + * An enumeration of the HTML5 notification permission values. + */ + var NotificationPermission = connect.makeEnum(['granted', 'denied', 'default']); - var addStreamTypeToStats = function (stats, streamType) { - stats = stats || {}; - return new RTPStreamStats(stats.timestamp, stats.packetsLost, stats.packetsCount, streamType, stats.audioLevel); + /** + * A simple engine for showing notification popups. + */ + connect.NotificationManager = function () { + this.queue = []; + this.permission = NotificationPermission.DEFAULT; }; - - var SoftphoneLogger = function (logger) { - this._originalLogger = logger; + connect.NotificationManager.prototype.requestPermission = function () { var self = this; - this._tee = function (level, method) { - return function () { - // call the original logger object to output to browser - //Connect logger follows %s format to print objects to console. - var args = Array.prototype.slice.call(arguments[0]); - var format = ""; - args.forEach(function () { - format = format + " %s"; - }); - return method.apply(self._originalLogger, [connect.LogComponent.SOFTPHONE, format].concat(args)); + if (!("Notification" in global)) { + connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(); + this.permission = NotificationPermission.DENIED; + } else if (global.Notification.permission === NotificationPermission.DENIED) { + connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(); + this.permission = NotificationPermission.DENIED; + } else if (this.permission !== NotificationPermission.GRANTED) { + global.Notification.requestPermission().then(function (permission) { + self.permission = permission; + if (permission === NotificationPermission.GRANTED) { + self._showQueued(); + } else { + self.queue = []; + } + }); + } + }; + connect.NotificationManager.prototype.show = function (title, options) { + if (this.permission === NotificationPermission.GRANTED) { + return this._showImpl({ + title: title, + options: options + }); + } else if (this.permission === NotificationPermission.DENIED) { + connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({ + title: title, + options: options + }); + } else { + var params = { + title: title, + options: options }; - }; + connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(params).sendInternalLogToServer(); + this.queue.push(params); + } }; - - SoftphoneLogger.prototype.debug = function () { - return this._tee(1, this._originalLogger.debug)(arguments); + connect.NotificationManager.prototype._showQueued = function () { + var self = this; + var notifications = this.queue.map(function (params) { + return self._showImpl(params); + }); + this.queue = []; + return notifications; }; - SoftphoneLogger.prototype.info = function () { - return this._tee(2, this._originalLogger.info)(arguments); + connect.NotificationManager.prototype._showImpl = function (params) { + var notification = new global.Notification(params.title, params.options); + if (params.options.clicked) { + notification.onclick = function () { + params.options.clicked.call(notification); + }; + } + return notification; }; - SoftphoneLogger.prototype.log = function () { - return this._tee(3, this._originalLogger.log)(arguments); + connect.BaseError = function (format, args) { + global.Error.call(this, connect.vsprintf(format, args)); }; - SoftphoneLogger.prototype.warn = function () { - return this._tee(4, this._originalLogger.warn)(arguments); + connect.BaseError.prototype = Object.create(Error.prototype); + connect.BaseError.prototype.constructor = connect.BaseError; + connect.ValueError = function () { + var args = Array.prototype.slice.call(arguments, 0); + var format = args.shift(); + connect.BaseError.call(this, format, args); }; - SoftphoneLogger.prototype.error = function () { - return this._tee(5, this._originalLogger.error)(arguments); + connect.ValueError.prototype = Object.create(connect.BaseError.prototype); + connect.ValueError.prototype.constructor = connect.ValueError; + connect.NotImplementedError = function () { + var args = Array.prototype.slice.call(arguments, 0); + var format = args.shift(); + connect.BaseError.call(this, format, args); + }; + connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype); + connect.NotImplementedError.prototype.constructor = connect.NotImplementedError; + connect.StateError = function () { + var args = Array.prototype.slice.call(arguments, 0); + var format = args.shift(); + connect.BaseError.call(this, format, args); + }; + connect.StateError.prototype = Object.create(connect.BaseError.prototype); + connect.StateError.prototype.constructor = connect.StateError; + connect.VoiceIdError = function (type, message, err) { + var error = {}; + error.type = type; + error.message = message; + error.stack = Error(message).stack; + error.err = err; + return error; }; - connect.SoftphoneManager = SoftphoneManager; + // internal use only + connect.isCCP = function () { + var conduit = connect.core.getUpstream(); + return conduit.name === 'ConnectSharedWorkerConduit'; + }; })(); +/***/ }), + +/***/ 744: +/***/ (() => { + /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -28653,40 +11928,32 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect = global.connect || {}; global.connect = connect; global.lily = connect; - connect.worker = {}; - var GET_AGENT_TIMEOUT_MS = 30000; var GET_AGENT_RECOVERY_TIMEOUT_MS = 5000; var GET_AGENT_SUCCESS_TIMEOUT_MS = 100; var LOG_BUFFER_CAP_SIZE = 400; - var CHECK_AUTH_TOKEN_INTERVAL_MS = 300000; // 5 minuts var REFRESH_AUTH_TOKEN_INTERVAL_MS = 10000; // 10 seconds var REFRESH_AUTH_TOKEN_MAX_TRY = 4; - var GET_AGENT_CONFIGURATION_INTERVAL_MS = 30000; /**-----------------------------------------------------------------------*/ - var MasterTopicCoordinator = function () { + var MasterTopicCoordinator = function MasterTopicCoordinator() { this.topicMasterMap = {}; }; - MasterTopicCoordinator.prototype.getMaster = function (topic) { connect.assertNotNull(topic, 'topic'); return this.topicMasterMap[topic] || null; }; - MasterTopicCoordinator.prototype.setMaster = function (topic, id) { connect.assertNotNull(topic, 'topic'); connect.assertNotNull(id, 'id'); this.topicMasterMap[topic] = id; }; - MasterTopicCoordinator.prototype.removeMaster = function (id) { connect.assertNotNull(id, 'id'); var self = this; - connect.entries(this.topicMasterMap).filter(function (entry) { return entry.value === id; }).forEach(function (entry) { @@ -28697,65 +11964,59 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi /**--------------------------------------------------------------- * class WorkerClient extends ClientBase */ - var WorkerClient = function (conduit) { + var WorkerClient = function WorkerClient(conduit) { connect.ClientBase.call(this); this.conduit = conduit; }; WorkerClient.prototype = Object.create(connect.ClientBase.prototype); WorkerClient.prototype.constructor = WorkerClient; - WorkerClient.prototype._callImpl = function (method, params, callbacks) { var self = this; var request_start = new Date().getTime(); - if(connect.containsValue(connect.AgentAppClientMethods, method)) { + if (connect.containsValue(connect.AgentAppClientMethods, method)) { connect.core.getAgentAppClient()._callImpl(method, params, { - success: function (data) { + success: function success(data) { self._recordAPILatency(method, request_start); callbacks.success(data); }, - failure: function (error) { + failure: function failure(error) { self._recordAPILatency(method, request_start, error); callbacks.failure(error); } - }) + }); } else { connect.core.getClient()._callImpl(method, params, { - success: function (data) { + success: function success(data) { self._recordAPILatency(method, request_start); callbacks.success(data); }, - failure: function (error, data) { + failure: function failure(error, data) { self._recordAPILatency(method, request_start, error); callbacks.failure(error, data); }, - authFailure: function () { + authFailure: function authFailure() { self._recordAPILatency(method, request_start); callbacks.authFailure(); }, - accessDenied: function () { + accessDenied: function accessDenied() { callbacks.accessDenied && callbacks.accessDenied(); } }); } - }; - WorkerClient.prototype._recordAPILatency = function (method, request_start, err) { var request_end = new Date().getTime(); var request_time = request_end - request_start; this._sendAPIMetrics(method, request_time, err); }; - WorkerClient.prototype._sendAPIMetrics = function (method, time, err) { this.conduit.sendDownstream(connect.EventType.API_METRIC, { name: method, time: time, - dimensions: [ - { - name: "Category", - value: "API" - } - ], + dimensions: [{ + name: "Category", + value: "API" + }], error: err }); }; @@ -28764,9 +12025,8 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * The object responsible for polling and passing data downstream to all * consumer ports. */ - var ClientEngine = function () { + var ClientEngine = function ClientEngine() { var self = this; - this.multiplexer = new connect.StreamMultiplexer(); this.conduit = new connect.Conduit("AmazonConnectSharedWorker", null, this.multiplexer); this.client = new WorkerClient(this.conduit); @@ -28779,93 +12039,72 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi this.logsBuffer = []; this.suppress = false; this.forceOffline = false; - var webSocketManager = null; - connect.rootLogger = new connect.DownstreamConduitLogger(this.conduit); - this.conduit.onDownstream(connect.EventType.SEND_LOGS, function (logsToUpload) { // Add softphone logs downstream connect.getLog().pushLogsDownstream(logsToUpload); - self.logsBuffer = self.logsBuffer.concat(logsToUpload); //only call API to send logs if buffer reached cap if (self.logsBuffer.length > LOG_BUFFER_CAP_SIZE) { self.handleSendLogsRequest(self.logsBuffer); } }); - this.conduit.onDownstream(connect.EventType.CONFIGURE, function (data) { if (data.authToken && data.authToken !== self.initData.authToken) { self.initData = data; connect.core.init(data); // init only once. if (!webSocketManager) { - - connect.getLog().info("Creating a new Websocket connection for CCP") - .sendInternalLogToServer(); - + connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(); connect.WebSocketManager.setGlobalConfig({ - loggerConfig: { logger: connect.getLog() } + loggerConfig: { + logger: connect.getLog() + } }); - webSocketManager = connect.WebSocketManager.create(); - webSocketManager.onInitFailure(function () { self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE); }); - webSocketManager.onConnectionOpen(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN, response); }); - webSocketManager.onConnectionClose(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE, response); }); - webSocketManager.onConnectionGain(function () { self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED); self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN); }); - webSocketManager.onConnectionLost(function (response) { self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, response); self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST, response); }); - webSocketManager.onSubscriptionUpdate(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, response); }); - webSocketManager.onSubscriptionFailure(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, response); }); - webSocketManager.onAllMessage(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE, response); }); - self.conduit.onDownstream(connect.WebSocketEvents.SEND, function (message) { webSocketManager.sendMessage(message); }); - self.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE, function (topics) { webSocketManager.subscribeTopics(topics); }); - - webSocketManager.init(connect.hitch(self, self.getWebSocketUrl)).then(function(response) { + webSocketManager.init(connect.hitch(self, self.getWebSocketUrl)).then(function (response) { if (response && !response.webSocketConnectionFailed) { // Start polling for agent data. - connect.getLog().info("Kicking off agent polling") - .sendInternalLogToServer(); + connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(); self.pollForAgent(); - - connect.getLog().info("Kicking off config polling") - .sendInternalLogToServer(); - self.pollForAgentConfiguration({ repeatForever: true }); - - connect.getLog().info("Kicking off auth token polling") - .sendInternalLogToServer(); + connect.getLog().info("Kicking off config polling").sendInternalLogToServer(); + self.pollForAgentConfiguration({ + repeatForever: true + }); + connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(); global.setInterval(connect.hitch(self, self.checkAuthToken), CHECK_AUTH_TOKEN_INTERVAL_MS); } else { if (!connect.webSocketInitFailed) { @@ -28875,8 +12114,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi } }); } else { - connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists") - .sendInternalLogToServer(); + connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer(); } } }); @@ -28902,1031 +12140,533 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi var stream = new connect.PortStream(port); self.multiplexer.addStream(stream); port.start(); - var portConduit = new connect.Conduit(stream.getId(), null, stream); - portConduit.sendDownstream(connect.EventType.ACKNOWLEDGE, { id: stream.getId() }); - + portConduit.sendDownstream(connect.EventType.ACKNOWLEDGE, { + id: stream.getId() + }); self.portConduitMap[stream.getId()] = portConduit; - self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(self.portConduitMap).length }); - + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { + length: Object.keys(self.portConduitMap).length + }); if (self.agent !== null) { self.updateAgent(); } - - portConduit.onDownstream(connect.EventType.API_REQUEST, - connect.hitch(self, self.handleAPIRequest, portConduit)); - portConduit.onDownstream(connect.EventType.MASTER_REQUEST, - connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId())); - portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, - connect.hitch(self, self.pollForAgentConfiguration)); + portConduit.onDownstream(connect.EventType.API_REQUEST, connect.hitch(self, self.handleAPIRequest, portConduit)); + portConduit.onDownstream(connect.EventType.MASTER_REQUEST, 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 }); + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { + length: Object.keys(self.portConduitMap).length + }); }); }; }; - ClientEngine.prototype.pollForAgent = function () { var self = this; var onAuthFail = connect.hitch(self, self.handleAuthFail); - this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT, { nextToken: self.nextToken, timeout: GET_AGENT_TIMEOUT_MS }, { - success: function (data) { - try { - self.agent = self.agent || {}; - self.agent.snapshot = data.snapshot; - self.agent.snapshot.localTimestamp = connect.now(); - self.agent.snapshot.skew = self.agent.snapshot.snapshotTimestamp - self.agent.snapshot.localTimestamp; - self.nextToken = data.nextToken; - connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.") - .withObject(data) - .sendInternalLogToServer(); - self.updateAgent(); - } catch (e) { - connect.getLog().error("Long poll failed to update agent.") - .withObject(data) - .withException(e) - .sendInternalLogToServer(); - } finally { - global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_SUCCESS_TIMEOUT_MS); - } - }, - failure: function (err, data) { - try { - connect.getLog().error("Failed to get agent data.") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - - } finally { - global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_RECOVERY_TIMEOUT_MS); - } - }, - authFailure: function () { - onAuthFail(); - }, - accessDenied: connect.hitch(self, self.handleAccessDenied) - - }); - + success: function success(data) { + try { + self.agent = self.agent || {}; + self.agent.snapshot = data.snapshot; + self.agent.snapshot.localTimestamp = connect.now(); + self.agent.snapshot.skew = self.agent.snapshot.snapshotTimestamp - self.agent.snapshot.localTimestamp; + self.nextToken = data.nextToken; + connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(data).sendInternalLogToServer(); + self.updateAgent(); + } catch (e) { + connect.getLog().error("Long poll failed to update agent.").withObject(data).withException(e).sendInternalLogToServer(); + } finally { + global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_SUCCESS_TIMEOUT_MS); + } + }, + failure: function failure(err, data) { + try { + connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + } finally { + global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_RECOVERY_TIMEOUT_MS); + } + }, + authFailure: function authFailure() { + onAuthFail(); + }, + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); }; - ClientEngine.prototype.pollForAgentConfiguration = function (paramsIn) { var self = this; var params = paramsIn || {}; var onAuthFail = connect.hitch(self, self.handleAuthFail); - this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION, {}, { - success: function (data) { + success: function success(data) { var configuration = data.configuration; self.pollForAgentPermissions(configuration); self.pollForAgentStates(configuration); self.pollForDialableCountryCodes(configuration); self.pollForRoutingProfileQueues(configuration); if (params.repeatForever) { - global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration, params), - GET_AGENT_CONFIGURATION_INTERVAL_MS); + global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration, params), GET_AGENT_CONFIGURATION_INTERVAL_MS); } }, - failure: function (err, data) { + failure: function failure(err, data) { try { - connect.getLog().error("Failed to fetch agent configuration data.") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); + connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); } finally { if (params.repeatForever) { - global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration), - GET_AGENT_CONFIGURATION_INTERVAL_MS, params); + global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration), GET_AGENT_CONFIGURATION_INTERVAL_MS, params); } } }, - authFailure: function () { + authFailure: function authFailure() { onAuthFail(); }, accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; - ClientEngine.prototype.pollForAgentStates = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_AGENT_STATES, { nextToken: params.nextToken || null, maxResults: params.maxResults - }, { - success: function (data) { - if (data.nextToken) { - self.pollForAgentStates(configuration, { - states: (params.states || []).concat(data.states), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - - } else { - configuration.agentStates = (params.states || []).concat(data.states); - self.updateAgentConfiguration(configuration); - } - }, - failure: function (err, data) { - connect.getLog().error("Failed to fetch agent states list.") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); + success: function success(data) { + if (data.nextToken) { + self.pollForAgentStates(configuration, { + states: (params.states || []).concat(data.states), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.agentStates = (params.states || []).concat(data.states); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); }; - ClientEngine.prototype.pollForAgentPermissions = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS, { nextToken: params.nextToken || null, maxResults: params.maxResults - }, { - success: function (data) { - if (data.nextToken) { - self.pollForAgentPermissions(configuration, { - permissions: (params.permissions || []).concat(data.permissions), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - - } else { - configuration.permissions = (params.permissions || []).concat(data.permissions); - self.updateAgentConfiguration(configuration); - } - }, - failure: function (err, data) { - connect.getLog().error("Failed to fetch agent permissions list.") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); + success: function success(data) { + if (data.nextToken) { + self.pollForAgentPermissions(configuration, { + permissions: (params.permissions || []).concat(data.permissions), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.permissions = (params.permissions || []).concat(data.permissions); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); }; - ClientEngine.prototype.pollForDialableCountryCodes = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES, { nextToken: params.nextToken || null, maxResults: params.maxResults }, { - success: function (data) { - if (data.nextToken) { - self.pollForDialableCountryCodes(configuration, { - countryCodes: (params.countryCodes || []).concat(data.countryCodes), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - - } else { - configuration.dialableCountries = (params.countryCodes || []).concat(data.countryCodes); - self.updateAgentConfiguration(configuration); - } - }, - failure: function (err, data) { - connect.getLog().error("Failed to fetch dialable country codes list.") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); + success: function success(data) { + if (data.nextToken) { + self.pollForDialableCountryCodes(configuration, { + countryCodes: (params.countryCodes || []).concat(data.countryCodes), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.dialableCountries = (params.countryCodes || []).concat(data.countryCodes); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); }; - ClientEngine.prototype.pollForRoutingProfileQueues = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES, { routingProfileARN: configuration.routingProfile.routingProfileARN, nextToken: params.nextToken || null, maxResults: params.maxResults }, { - success: function (data) { - if (data.nextToken) { - self.pollForRoutingProfileQueues(configuration, { - countryCodes: (params.queues || []).concat(data.queues), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - - } else { - configuration.routingProfile.queues = (params.queues || []).concat(data.queues); - self.updateAgentConfiguration(configuration); - } - }, - failure: function (err, data) { - connect.getLog().error("Failed to fetch routing profile queues list.") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); + success: function success(data) { + if (data.nextToken) { + self.pollForRoutingProfileQueues(configuration, { + countryCodes: (params.queues || []).concat(data.queues), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.routingProfile.queues = (params.queues || []).concat(data.queues); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); }; - ClientEngine.prototype.handleAPIRequest = function (portConduit, request) { var self = this; - this.client.call(request.method, request.params, { - success: function (data) { + success: function success(data) { var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data); portConduit.sendDownstream(response.event, response); }, - failure: function (err, data) { + failure: function failure(err, data) { var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data, JSON.stringify(err)); portConduit.sendDownstream(response.event, response); - connect.getLog().error("'%s' API request failed", request.method) - .withObject({ request: self.filterAuthToken(request), response: response }) - .withException(err) - .sendInternalLogToServer(); - }, - authFailure: connect.hitch(self, self.handleAuthFail) - }); - }; - - /** - * Handle incoming master query or modification requests from connected tab ports. - */ - ClientEngine.prototype.handleMasterRequest = function (portConduit, portId, request) { - var multiplexerConduit = this.conduit; - var response = null; - - switch (request.method) { - case connect.MasterMethods.BECOME_MASTER: - var masterId = this.masterCoord.getMaster(request.params.topic); - var takeOver = Boolean(masterId) && masterId !== portId; - this.masterCoord.setMaster(request.params.topic, portId); - response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { - masterId: portId, - takeOver: takeOver, - topic: request.params.topic - }); - if (takeOver) { - multiplexerConduit.sendDownstream(response.event, response); - } - break; - - case connect.MasterMethods.CHECK_MASTER: - var masterId = this.masterCoord.getMaster(request.params.topic); - if (!masterId && !request.params.shouldNotBecomeMasterIfNone) { - this.masterCoord.setMaster(request.params.topic, portId); - masterId = portId; - } - response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { - masterId: masterId, - isMaster: portId === masterId, - topic: request.params.topic - }); - break; - - default: - throw new Error("Unknown master method: " + request.method); - } - - portConduit.sendDownstream(response.event, response); - }; - - ClientEngine.prototype.updateAgentConfiguration = function (configuration) { - if (configuration.permissions && - configuration.dialableCountries && - configuration.agentStates && - configuration.routingProfile.queues) { - - this.agent = this.agent || {}; - this.agent.configuration = configuration; - this.updateAgent(); - - } else { - connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.") - .sendInternalLogToServer(); - } - }; - - ClientEngine.prototype.updateAgent = function () { - if (!this.agent) { - connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.") - .sendInternalLogToServer(); - - } else if (!this.agent.snapshot) { - connect.getLog().trace("Waiting to update agent until the agent snapshot is available.") - .sendInternalLogToServer(); - - } else if (!this.agent.configuration) { - connect.getLog().trace("Waiting to update agent until the agent configuration is available.") - .sendInternalLogToServer(); - - } else { - // Alias some of the properties for backwards compatibility. - this.agent.snapshot.status = this.agent.state; - - // Sort the contacts on the timestamp - if (this.agent.snapshot.contacts && this.agent.snapshot.contacts.length > 1) { - this.agent.snapshot.contacts.sort(function (contactA, contactB) { - return contactA.state.timestamp.getTime() - contactB.state.timestamp.getTime(); - }); - } - - this.agent.snapshot.contacts.forEach(function (contact) { - contact.status = contact.state; - - contact.connections.forEach(function (connection) { - connection.address = connection.endpoint; - }); - }); - - this.agent.configuration.routingProfile.defaultOutboundQueue.queueId = - this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN; - this.agent.configuration.routingProfile.queues.forEach(function (queue) { - queue.queueId = queue.queueARN; - }); - this.agent.snapshot.contacts.forEach(function (contact) { - //contact.queue is null when monitoring - if (contact.queue !== undefined) { - contact.queue.queueId = contact.queue.queueARN; - } - }); - this.agent.configuration.routingProfile.routingProfileId = - this.agent.configuration.routingProfile.routingProfileARN; - - this.conduit.sendDownstream(connect.AgentEvents.UPDATE, this.agent); - } - }; - -/** - * Provides a websocket url through the create_transport API. - * @returns a promise which, upon success, returns the response from the createTransport API. - */ - ClientEngine.prototype.getWebSocketUrl = function () { - var self = this; - var client = connect.core.getClient(); - var onAuthFail = connect.hitch(self, self.handleAuthFail); - var onAccessDenied = connect.hitch(self, self.handleAccessDenied); - return new Promise(function (resolve, reject) { - client.call(connect.ClientMethods.CREATE_TRANSPORT, { transportType: connect.TRANSPORT_TYPES.WEB_SOCKET }, { - success: function (data) { - connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(); - resolve(data); - }, - failure: function (err, data) { - connect.getLog().error("getWebSocketUrl failed") - .sendInternalLogToServer() - .withObject({ - err: err, - data: data - }); - reject({ - reason: 'getWebSocketUrl failed', - _debug: err - }); - }, - authFailure: function () { - connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(); - reject(Error("Authentication failed while getting getWebSocketUrl")); - onAuthFail(); - }, - accessDenied: function () { - connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(); - reject(Error("Access Denied Failure while getting getWebSocketUrl")); - onAccessDenied(); - } - }); - }); - }; - - - /** - * Send a message downstream to all consumers when we detect that authentication - * against one of our APIs has failed. - */ - ClientEngine.prototype.handleSendLogsRequest = function () { - var self = this; - var logEvents = []; - var logsToSend = self.logsBuffer.slice(); - self.logsBuffer = []; - logsToSend.forEach(function (log) { - logEvents.push({ - timestamp: log.time, - component: log.component, - message: log.text - }); - }); - this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS, { logEvents: logEvents }, { - success: function (data) { - connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer(); - }, - failure: function (err, data) { - connect.getLog().error("SendLogs request failed.") - .withObject(data).withException(err) - .sendInternalLogToServer(); + connect.getLog().error("'%s' API request failed", request.method).withObject({ + request: self.filterAuthToken(request), + response: response + }).withException(err).sendInternalLogToServer(); }, - authFailure: connect.hitch(self, self.handleAuthFail) - }); - }; - - ClientEngine.prototype.handleAuthFail = function () { - var self = this; - self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); - }; - - ClientEngine.prototype.handleAccessDenied = function () { - var self = this; - self.conduit.sendDownstream(connect.EventType.ACCESS_DENIED); - }; - - ClientEngine.prototype.checkAuthToken = function () { - var self = this; - var expirationDate = new Date(self.initData.authTokenExpiration); - var currentTimeStamp = new Date().getTime(); - var thirtyMins = 30 * 60 * 1000; - - // refresh token 30 minutes before expiration - if (expirationDate.getTime() < (currentTimeStamp + thirtyMins)) { - connect.getLog().info("Auth token expires at " + expirationDate + " Start refreshing token with retry.") - .sendInternalLogToServer(); - connect.backoff(connect.hitch(self, self.authorize), REFRESH_AUTH_TOKEN_INTERVAL_MS, REFRESH_AUTH_TOKEN_MAX_TRY); - } - }; - - - ClientEngine.prototype.authorize = function (callbacks) { - var self = this; - connect.core.authorize(this.initData.authorizeEndpoint).then(function (response) { - var expiration = new Date(response.expiration); - connect.getLog().info("Authorization succeeded and the token expires at %s", expiration) - .sendInternalLogToServer(); - self.initData.authToken = response.accessToken; - self.initData.authTokenExpiration = expiration; - connect.core.initClient(self.initData); - connect.core.initAgentAppClient(self.initData); - callbacks.success(); - }).catch(function (response) { - connect.getLog().error("Authorization failed with code %s", response.status) - .sendInternalLogToServer(); - if (response.status === 401) { - self.handleAuthFail(); - } else { - callbacks.failure(); - } - }); - }; - - /** - * Filter the 'authentication' field of the request params from the given API_REQUEST event. - */ - ClientEngine.prototype.filterAuthToken = function (request) { - var new_request = {}; - - for (var keyA in request) { - if (keyA === 'params') { - var new_params = {}; - for (var keyB in request.params) { - if (keyB !== 'authentication') { - new_params[keyB] = request.params[keyB]; - } - } - - new_request.params = new_params; - } else { - new_request[keyA] = request[keyA]; - } - } - - return new_request; - }; - - /**-----------------------------------------------------------------------*/ - connect.worker.main = function () { - connect.worker.clientEngine = new ClientEngine(); + authFailure: connect.hitch(self, self.handleAuthFail) + }); }; -})(); -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - connect.ChatMediaController = function (mediaInfo, metadata) { - var logger = connect.getLog(); - var logComponent = connect.LogComponent.CHAT; - - var createMediaInstance = function () { - publishTelemetryEvent("Chat media controller init", mediaInfo.contactId); - logger.info(logComponent, "Chat media controller init") - .withObject(mediaInfo).sendInternalLogToServer(); - - connect.ChatSession.setGlobalConfig({ - loggerConfig: { - logger: logger - }, - region: metadata.region - }); - - /** Could be also CUSTOMER - For now we are creating only Agent connection media object */ - var controller = connect.ChatSession.create({ - chatDetails: mediaInfo, - type: "AGENT", - websocketManager: connect.core.getWebSocketManager() - }); - - trackChatConnectionStatus(controller); - return controller - .connect() - .then(function (data) { - logger.info(logComponent, "Chat Session Successfully established for contactId %s", mediaInfo.contactId) - .sendInternalLogToServer(); - publishTelemetryEvent("Chat Session Successfully established", mediaInfo.contactId); - return controller; - }) - .catch(function (error) { - logger.error(logComponent, "Chat Session establishement failed for contact %s", mediaInfo.contactId) - .withException(error).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); - throw error; + /** + * Handle incoming master query or modification requests from connected tab ports. + */ + ClientEngine.prototype.handleMasterRequest = function (portConduit, portId, request) { + var multiplexerConduit = this.conduit; + var response = null; + switch (request.method) { + case connect.MasterMethods.BECOME_MASTER: + var masterId = this.masterCoord.getMaster(request.params.topic); + var takeOver = Boolean(masterId) && masterId !== portId; + this.masterCoord.setMaster(request.params.topic, portId); + response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { + masterId: portId, + takeOver: takeOver, + topic: request.params.topic }); - }; - - var publishTelemetryEvent = function (eventName, data) { - connect.publishMetric({ - name: eventName, - contactId: mediaInfo.contactId, - data: data || mediaInfo - }); - }; - - var trackChatConnectionStatus = function (controller) { - controller.onConnectionBroken(function (data) { - logger.error(logComponent, "Chat Session connection broken") - .withException(data).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session connection broken", data); - }); - - controller.onConnectionEstablished(function (data) { - logger.info(logComponent, "Chat Session connection established") - .withObject(data).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session connection established", data); - }); - } - - return { - get: function () { - return createMediaInstance(); - } - } - } -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - connect.MediaFactory = function (params) { - /** controller holder */ - var mediaControllers = {}; - var toBeDestroyed = new Set(); - - var logger = connect.getLog(); - var logComponent = connect.LogComponent.CHAT; - - var metadata = connect.merge({}, params) || {}; - metadata.region = metadata.region || "us-west-2"; // Default it to us-west-2 - - var getMediaController = function (connectionObj) { - var connectionId = connectionObj.getConnectionId(); - var mediaInfo = connectionObj.getMediaInfo(); - /** if we do not have the media info then just reject the request */ - if (!mediaInfo) { - logger.error(logComponent, "Media info does not exist for a media type %s", connectionObj.getMediaType()) - .withObject(connectionObj).sendInternalLogToServer(); - return Promise.reject("Media info does not exist for this connection"); - } - - if (!mediaControllers[connectionId]) { - logger.info(logComponent, "media controller of type %s init", connectionObj.getMediaType()) - .withObject(connectionObj).sendInternalLogToServer(); - switch (connectionObj.getMediaType()) { - case connect.MediaType.CHAT: - return mediaControllers[connectionId] = new connect.ChatMediaController(connectionObj.getMediaInfo(), metadata).get(); - case connect.MediaType.SOFTPHONE: - return mediaControllers[connectionId] = new connect.SoftphoneMediaController(connectionObj.getMediaInfo()).get(); - case connect.MediaType.TASK: - return mediaControllers[connectionId] = new connect.TaskMediaController(connectionObj.getMediaInfo()).get(); - default: - logger.error(logComponent, "Unrecognized media type %s ", connectionObj.getMediaType()) - .sendInternalLogToServer(); - return Promise.reject(); + if (takeOver) { + multiplexerConduit.sendDownstream(response.event, response); } - } else { - return mediaControllers[connectionId]; - } - }; - - /** Check all the active states for the connection */ - var ifConnectionActive = function (connectionObj) { - return connectionObj.isActive(); - }; - - var get = function (connectionObj) { - if (ifConnectionActive(connectionObj)) { - return getMediaController(connectionObj); - } else { - destroy(connectionObj.getConnectionId()); - return Promise.reject("Media Controller is no longer available for this connection"); - } - }; - - var destroy = function (connectionId) { - if (mediaControllers[connectionId] && !toBeDestroyed.has(connectionId)) { - logger.info( - logComponent, - "Destroying mediaController for %s", - connectionId - ); - toBeDestroyed.add(connectionId); - mediaControllers[connectionId] - .then(function() { - if (typeof controller.cleanUp === "function") controller.cleanUp(); - delete mediaControllers[connectionId]; - toBeDestroyed.delete(connectionId); - }) - .catch(function() { - delete mediaControllers[connectionId]; - toBeDestroyed.delete(connectionId); - }); - } - }; - - return { - get: get, - destroy: destroy - }; - } -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - // TODO move softphone implementations here - Wil do this for GA - connect.SoftphoneMediaController = function (mediaInfo) { - return { - get: function () { - return Promise.resolve(mediaInfo) - } + break; + case connect.MasterMethods.CHECK_MASTER: + var masterId = this.masterCoord.getMaster(request.params.topic); + if (!masterId && !request.params.shouldNotBecomeMasterIfNone) { + this.masterCoord.setMaster(request.params.topic, portId); + masterId = portId; + } + response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { + masterId: masterId, + isMaster: portId === masterId, + topic: request.params.topic + }); + break; + default: + throw new Error("Unknown master method: " + request.method); } - } -})(); - -/* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - connect.TaskMediaController = function (mediaInfo) { - var logger = connect.getLog(); - var logComponent = connect.LogComponent.TASK; - - var createMediaInstance = function () { - publishTelemetryEvent("Task media controller init", mediaInfo.contactId); - logger - .info(logComponent, "Task media controller init") - .withObject(mediaInfo); - - var controller = connect.TaskSession.create({ - contactId: mediaInfo.contactId, - initialContactId: mediaInfo.initialContactId, - websocketManager: connect.core.getWebSocketManager(), - }); - - trackTaskConnectionStatus(controller); + portConduit.sendDownstream(response.event, response); + }; + ClientEngine.prototype.updateAgentConfiguration = function (configuration) { + if (configuration.permissions && configuration.dialableCountries && configuration.agentStates && configuration.routingProfile.queues) { + this.agent = this.agent || {}; + this.agent.configuration = configuration; + this.updateAgent(); + } else { + connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer(); + } + }; + ClientEngine.prototype.updateAgent = function () { + if (!this.agent) { + connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer(); + } else if (!this.agent.snapshot) { + connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer(); + } else if (!this.agent.configuration) { + connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer(); + } else { + // Alias some of the properties for backwards compatibility. + this.agent.snapshot.status = this.agent.state; - return controller - .connect() - .then(function () { - logger.info( - logComponent, - "Task Session Successfully established for contactId %s", - mediaInfo.contactId - ); - publishTelemetryEvent( - "Task Session Successfully established", - mediaInfo.contactId - ); - return controller; - }) - .catch(function (error) { - logger - .error( - logComponent, - "Task Session establishement failed for contact %s", - mediaInfo.contactId - ) - .withException(error); - publishTelemetryEvent( - "Chat Session establishement failed", - mediaInfo.contactId, - error - ); - throw error; + // Sort the contacts on the timestamp + if (this.agent.snapshot.contacts && this.agent.snapshot.contacts.length > 1) { + this.agent.snapshot.contacts.sort(function (contactA, contactB) { + return contactA.state.timestamp.getTime() - contactB.state.timestamp.getTime(); + }); + } + this.agent.snapshot.contacts.forEach(function (contact) { + contact.status = contact.state; + contact.connections.forEach(function (connection) { + connection.address = connection.endpoint; }); - }; - - var publishTelemetryEvent = function (eventName, data) { - connect.publishMetric({ - name: eventName, - contactId: mediaInfo.contactId, - data: data || mediaInfo, }); - }; - - var trackTaskConnectionStatus = function (controller) { - controller.onConnectionBroken(function (data) { - logger - .error(logComponent, "Task Session connection broken") - .withException(data); - publishTelemetryEvent("Task Session connection broken", data); + this.agent.configuration.routingProfile.defaultOutboundQueue.queueId = this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN; + this.agent.configuration.routingProfile.queues.forEach(function (queue) { + queue.queueId = queue.queueARN; }); - - controller.onConnectionEstablished(function (data) { - logger - .info(logComponent, "Task Session connection established") - .withObject(data); - publishTelemetryEvent("Task Session connection established", data); + this.agent.snapshot.contacts.forEach(function (contact) { + //contact.queue is null when monitoring + if (contact.queue !== undefined) { + contact.queue.queueId = contact.queue.queueARN; + } }); - }; - - return { - get: function () { - return createMediaInstance(); - }, - }; + this.agent.configuration.routingProfile.routingProfileId = this.agent.configuration.routingProfile.routingProfileARN; + this.conduit.sendDownstream(connect.AgentEvents.UPDATE, this.agent); + } }; -})(); - -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - connect.agentApp = {}; - var APP = { - CCP: 'ccp', + /** + * Provides a websocket url through the create_transport API. + * @returns a promise which, upon success, returns the response from the createTransport API. + */ + ClientEngine.prototype.getWebSocketUrl = function () { + var self = this; + var client = connect.core.getClient(); + var onAuthFail = connect.hitch(self, self.handleAuthFail); + var onAccessDenied = connect.hitch(self, self.handleAccessDenied); + return new Promise(function (resolve, reject) { + client.call(connect.ClientMethods.CREATE_TRANSPORT, { + transportType: connect.TRANSPORT_TYPES.WEB_SOCKET + }, { + success: function success(data) { + connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err, data) { + connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + reject({ + reason: 'getWebSocketUrl failed', + _debug: err + }); + }, + authFailure: function authFailure() { + connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(); + reject(Error("Authentication failed while getting getWebSocketUrl")); + onAuthFail(); + }, + accessDenied: function accessDenied() { + connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(); + reject(Error("Access Denied Failure while getting getWebSocketUrl")); + onAccessDenied(); + } + }); + }); }; - connect.agentApp.initCCP = connect.core.initCCP; - connect.agentApp.isInitialized = function (instanceAlias) {}; - - connect.agentApp.initAppCommunication = function (iframeId, endpoint) { - var iframe = document.getElementById(iframeId); - var iframeConduit = new connect.IFrameConduit(endpoint, window, iframe); - var BROADCAST_TYPE = [ - connect.AgentEvents.UPDATE, - connect.ContactEvents.VIEW, - connect.EventType.ACKNOWLEDGE, - connect.EventType.TERMINATED, - connect.TaskEvents.CREATED - ]; - iframe.addEventListener('load', function (e) { - BROADCAST_TYPE.forEach(function (type) { - connect.core.getUpstream().onUpstream(type, function (data) { - iframeConduit.sendUpstream(type, data); - }); + /** + * Send a message downstream to all consumers when we detect that authentication + * against one of our APIs has failed. + */ + ClientEngine.prototype.handleSendLogsRequest = function () { + var self = this; + var logEvents = []; + var logsToSend = self.logsBuffer.slice(); + self.logsBuffer = []; + logsToSend.forEach(function (log) { + logEvents.push({ + timestamp: log.time, + component: log.component, + message: log.text }); }); + this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS, { + logEvents: logEvents + }, { + success: function success(data) { + connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer(); + }, + failure: function failure(err, data) { + connect.getLog().error("SendLogs request failed.").withObject(data).withException(err).sendInternalLogToServer(); + }, + authFailure: connect.hitch(self, self.handleAuthFail) + }); }; - - var getConnectUrl = function (ccpUrl) { - var pos = ccpUrl.indexOf('ccp-v2'); - return ccpUrl.slice(0, pos - 1); + ClientEngine.prototype.handleAuthFail = function () { + var self = this; + self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); }; - - var signOutThroughCCP = function (ccpUrl) { - var logoutUrl = getConnectUrl(ccpUrl) + '/logout'; - return connect.fetch(logoutUrl, { - credentials: 'include', - }).then(function () { - var eventBus = connect.core.getEventBus(); - eventBus.trigger(connect.EventType.TERMINATE); - return true; - }).catch(function (e) { - connect - .getLog() - .error('An error occured on logout.' + e) - .withException(e); - window.location.href = logoutUrl; - return false; - }); + ClientEngine.prototype.handleAccessDenied = function () { + var self = this; + self.conduit.sendDownstream(connect.EventType.ACCESS_DENIED); }; + ClientEngine.prototype.checkAuthToken = function () { + var self = this; + var expirationDate = new Date(self.initData.authTokenExpiration); + var currentTimeStamp = new Date().getTime(); + var thirtyMins = 30 * 60 * 1000; - var signInThroughinitCCP = function (ccpUrl, container, config) { - var defaultParams = { - ccpUrl: ccpUrl, - ccpLoadTimeout: 10000, - loginPopup: true, - loginUrl: getConnectUrl(ccpUrl) + '/login', - softphone: { - allowFramedSoftphone: true, - disableRingtone: false, + // refresh token 30 minutes before expiration + if (expirationDate.getTime() < currentTimeStamp + thirtyMins) { + connect.getLog().info("Auth token expires at " + expirationDate + " Start refreshing token with retry.").sendInternalLogToServer(); + connect.backoff(connect.hitch(self, self.authorize), REFRESH_AUTH_TOKEN_INTERVAL_MS, REFRESH_AUTH_TOKEN_MAX_TRY); + } + }; + ClientEngine.prototype.authorize = function (callbacks) { + var self = this; + connect.core.authorize(this.initData.authorizeEndpoint).then(function (response) { + var expiration = new Date(response.expiration); + connect.getLog().info("Authorization succeeded and the token expires at %s", expiration).sendInternalLogToServer(); + self.initData.authToken = response.accessToken; + self.initData.authTokenExpiration = expiration; + connect.core.initClient(self.initData); + connect.core.initAgentAppClient(self.initData); + callbacks.success(); + })["catch"](function (response) { + connect.getLog().error("Authorization failed with code %s", response.status).sendInternalLogToServer(); + if (response.status === 401) { + self.handleAuthFail(); + } else { + callbacks.failure(); } - }; - var ccpParams = connect.merge(defaultParams, config.ccpParams); - connect.core.initCCP(container, ccpParams); + }); }; - connect.agentApp.initApp = function (name, containerId, appUrl, config) { - config = config ? config : {}; - var endpoint = appUrl.endsWith('/') ? appUrl : appUrl + '/'; - var onLoad = config.onLoad ? config.onLoad : null; - var registerConfig = { endpoint: endpoint, style: config.style, onLoad: onLoad }; - connect.agentApp.AppRegistry.register(name, registerConfig, document.getElementById(containerId)); - connect.agentApp.AppRegistry.start(name, function (moduleData) { - var endpoint = moduleData.endpoint; - var containerDOM = moduleData.containerDOM; - return { - init: function () { - if (name === APP.CCP) return signInThroughinitCCP(endpoint, containerDOM, config); - return connect.agentApp.initAppCommunication(name, endpoint); - }, - destroy: function () { - if (name === APP.CCP) return signOutThroughCCP(endpoint); - return null; + /** + * Filter the 'authentication' field of the request params from the given API_REQUEST event. + */ + ClientEngine.prototype.filterAuthToken = function (request) { + var new_request = {}; + for (var keyA in request) { + if (keyA === 'params') { + var new_params = {}; + for (var keyB in request.params) { + if (keyB !== 'authentication') { + new_params[keyB] = request.params[keyB]; + } } - }; - }); + new_request.params = new_params; + } else { + new_request[keyA] = request[keyA]; + } + } + return new_request; }; - connect.agentApp.stopApp = function (name) { - return connect.agentApp.AppRegistry.stop(name); + /**-----------------------------------------------------------------------*/ + connect.worker.main = function () { + connect.worker.clientEngine = new ClientEngine(); }; })(); -(function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - var APP = { - CCP: 'ccp', - }; - - function AppRegistry() { - var moduleData = {}; - var makeAppIframe = function (appName, endpoint, style, onLoad) { - var iframe = document.createElement('iframe'); - iframe.src = endpoint; - iframe.style = style || 'width: 100%; height:100%;'; - iframe.id = appName; - iframe['aria-label'] = appName; - iframe.onload = onLoad; - iframe.setAttribute( - "sandbox", - "allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts" - ); - // TODO: Update sandbox option for 3P widget - - return iframe; - }; - - return { - register: function (appName, config, containerDOM) { - moduleData[appName] = { - containerDOM: containerDOM, - endpoint: config.endpoint, - style: config.style, - instance: undefined, - onLoad: config.onLoad, - }; - }, - start: function (appName, creator) { - if (!moduleData[appName]) return; - var containerDOM = moduleData[appName].containerDOM; - var endpoint = moduleData[appName].endpoint; - var style = moduleData[appName].style; - var onLoad = moduleData[appName].onLoad; - if (appName !== APP.CCP) { - var app = makeAppIframe(appName, endpoint, style, onLoad); - containerDOM.appendChild(app); - } - - moduleData[appName].instance = creator(moduleData[appName]); - return moduleData[appName].instance.init(); - }, - stop: function (appName) { - if (!moduleData[appName]) return; - - var data = moduleData[appName]; - var app = data.containerDOM.querySelector('iframe'); - data.containerDOM.removeChild(app); - - var result; - if (data.instance) { - result = data.instance.destroy(); - delete data.instance; - } - - return result; - } - }; - } - - global.connect.agentApp.AppRegistry = AppRegistry(); -})(); +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/amd options */ +/******/ (() => { +/******/ __webpack_require__.amdO = {}; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module used 'module' so it can't be inlined +/******/ __webpack_require__(538); +/******/ __webpack_require__(778); +/******/ __webpack_require__(312); +/******/ __webpack_require__(420); +/******/ __webpack_require__(547); +/******/ __webpack_require__(768); +/******/ __webpack_require__(417); +/******/ __webpack_require__(738); +/******/ __webpack_require__(35); +/******/ __webpack_require__(42); +/******/ __webpack_require__(743); +/******/ __webpack_require__(531); +/******/ __webpack_require__(555); +/******/ __webpack_require__(960); +/******/ __webpack_require__(744); +/******/ __webpack_require__(158); +/******/ __webpack_require__(7); +/******/ __webpack_require__(6); +/******/ __webpack_require__(487); +/******/ __webpack_require__(340); +/******/ var __webpack_exports__ = __webpack_require__(228); +/******/ +/******/ })() +; \ No newline at end of file diff --git a/src/core.js b/src/core.js index 3a9123c2..37554b1c 100644 --- a/src/core.js +++ b/src/core.js @@ -36,6 +36,8 @@ connect.numberOfConnectedCCPs = 0; + var CCP_IFRAME_NAME = 'Amazon Connect CCP'; + /** * @deprecated * This function was only meant for internal use. @@ -751,6 +753,16 @@ .withException(e).sendInternalLogToServer(); } }; + + connect.core._getCCPIframe = function () { + for (var iframe of window.document.getElementsByTagName('iframe')) { + if (iframe.name === CCP_IFRAME_NAME) { + return iframe; + } + } + return null; + } + /**------------------------------------------------------------------------- * Initializes Connect by creating or connecting to the API Shared Worker. @@ -773,6 +785,9 @@ connect.assertNotNull(containerDiv, 'containerDiv'); connect.assertNotNull(params.ccpUrl, 'params.ccpUrl'); + + connect.storageAccess.init(params.ccpUrl, containerDiv, params.storageAccess || {}); + // Create the CCP iframe and append it to the container div. var iframe = document.createElement('iframe'); @@ -780,145 +795,175 @@ iframe.allow = "microphone; autoplay"; iframe.style = "width: 100%; height: 100%"; iframe.title = 'Amazon Connect CCP'; + iframe.name = CCP_IFRAME_NAME; + + //for Storage Access follow the rsa path + if(connect.storageAccess.canRequest()){ + iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); + iframe.addEventListener('load', connect.storageAccess.request); + } + containerDiv.appendChild(iframe); + // Build the upstream conduit communicating with the CCP iframe. + var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); + + // Set the global upstream conduit for external use. + connect.core.upstream = conduit; + // Initialize the event bus and agent data providers. // NOTE: Setting logEvents here to FALSE in order to avoid duplicating // events which are logged in CCP. connect.core.eventBus = new connect.EventBus({ logEvents: false }); + + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); connect.core.mediaFactory = new connect.MediaFactory(params); - // Build the upstream conduit communicating with the CCP iframe. - var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); - - // Let CCP know if iframe is visible - iframe.onload = setTimeout(function() { - var style = window.getComputedStyle(iframe, null); - var data = { - display: style.display, - offsetWidth: iframe.offsetWidth, - offsetHeight: iframe.offsetHeight, - clientRectsLength: iframe.getClientRects().length - }; - conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); - }, 10000); - - // Set the global upstream conduit for external use. - connect.core.upstream = conduit; - - // Init webSocketProvider - connect.core.webSocketProvider = new WebSocketProvider(); - conduit.onAllUpstream(connect.core.getEventBus().bridge()); - - // Initialize the keepalive manager. - connect.core.keepaliveManager = new KeepaliveManager(conduit, - connect.core.getEventBus(), - params.ccpSynTimeout || CCP_SYN_TIMEOUT, - params.ccpAckTimeout || CCP_ACK_TIMEOUT) - ; - connect.core.iframeRefreshInterval = null; - - // Allow 5 sec (default) before receiving the first ACK from the CCP. - connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { - connect.core.ccpLoadTimeoutInstance = null; - connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); - }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); - connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); - connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); - - // Once we receive the first ACK, setup our upstream API client and establish - // the SYN/ACK refresh flow. - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { - connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); - connect.core.client = new connect.UpstreamConduitClient(conduit); - connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); - connect.core.portStreamId = data.id; - - if (params.softphone || params.chat || params.pageOptions) { - // 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 - }); - } - - if (connect.core.ccpLoadTimeoutInstance) { - global.clearTimeout(connect.core.ccpLoadTimeoutInstance); + if (connect.storageAccess.canRequest()) { + // Create the Iframe and load the RSA banner and append it to the container div. + connect.storageAccess.setupRequestHandlers({ onGrant: setupInitCCP }); + }else{ + setupInitCCP(); + } + + function setupInitCCP() { + + // Let CCP know if iframe is visible + iframe.onload = setTimeout(function() { + var style = window.getComputedStyle(iframe, null); + var data = { + display: style.display, + offsetWidth: iframe.offsetWidth, + offsetHeight: iframe.offsetHeight, + clientRectsLength: iframe.getClientRects().length + }; + conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); + }, 10000); + + // Init webSocketProvider + connect.core.webSocketProvider = new WebSocketProvider(); + + conduit.onAllUpstream(connect.core.getEventBus().bridge()); + + // Initialize the keepalive manager. + connect.core.keepaliveManager = new KeepaliveManager(conduit, + connect.core.getEventBus(), + params.ccpSynTimeout || CCP_SYN_TIMEOUT, + params.ccpAckTimeout || CCP_ACK_TIMEOUT) + ; + connect.core.iframeRefreshInterval = null; + + // Allow 5 sec (default) before receiving the first ACK from the CCP. + connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { connect.core.ccpLoadTimeoutInstance = null; - } + connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); + }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); - conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { streamsVersion: connect.version }); - - connect.core.keepaliveManager.start(); - this.unsubscribe(); + connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); + connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); + + // Once we receive the first ACK, setup our upstream API client and establish + // the SYN/ACK refresh flow. + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { + connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); + connect.core.client = new connect.UpstreamConduitClient(conduit); + connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); + connect.core.portStreamId = data.id; - connect.core.initialized = true; - connect.core.getEventBus().trigger(connect.EventType.INIT); - }); - - // Add any logs from the upstream to our own logger. - conduit.onUpstream(connect.EventType.LOG, function (logEntry) { - if (logEntry.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); - } - }); - - // Pop a login page when we encounter an ACK timeout. - connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { - // loginPopup is true by default, only false if explicitly set to false. - if (params.loginPopup !== false) { - try { - var loginUrl = getLoginUrl(params); - connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(); - // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT - if (params.loginUrl) { - connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); - } - connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions); - } catch (e) { - connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer(); + if (params.softphone || params.chat || params.pageOptions) { + // 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 + }); } - } - - if (connect.core.iframeRefreshInterval == null) { - connect.core.iframeRefreshInterval = window.setInterval(function () { - iframe.src = params.ccpUrl; - }, CCP_IFRAME_REFRESH_INTERVAL); - - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { - this.unsubscribe(); - global.clearInterval(connect.core.iframeRefreshInterval); - connect.core.iframeRefreshInterval = null; - connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); - if ((params.loginPopupAutoClose || (params.loginOptions && params.loginOptions.autoClose)) && connect.core.loginWindow) { - connect.core.loginWindow.close(); - connect.core.loginWindow = null; + + if (connect.core.ccpLoadTimeoutInstance) { + global.clearTimeout(connect.core.ccpLoadTimeoutInstance); + connect.core.ccpLoadTimeoutInstance = null; + } + + conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { streamsVersion: connect.version }); + + connect.core.keepaliveManager.start(); + this.unsubscribe(); + + connect.core.initialized = true; + connect.core.getEventBus().trigger(connect.EventType.INIT); + }); + + // Add any logs from the upstream to our own logger. + conduit.onUpstream(connect.EventType.LOG, function (logEntry) { + if (logEntry.loggerId !== connect.getLog().getLoggerId()) { + connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + } + }); + + // Pop a login page when we encounter an ACK timeout. + connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { + // loginPopup is true by default, only false if explicitly set to false. + if (params.loginPopup !== false) { + try { + var loginUrl = getLoginUrl(params); + connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(); + // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT + if (params.loginUrl) { + connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); + } + connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions); + } catch (e) { + connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer(); } - }); - } - }); - - if (params.onViewContact) { - connect.core.onViewContact(params.onViewContact); - } + } + + if (connect.core.iframeRefreshInterval == null) { + connect.core.iframeRefreshInterval = window.setInterval(function () { - conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { - connect.numberOfConnectedCCPs = data.length; - }); + if(connect.storageAccess.canRequest()){ + iframe.removeEventListener('load', connect.storageAccess.request); + iframe.addEventListener('load', connect.storageAccess.request); + iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); + }else{ + iframe.src = params.ccpUrl; + } - conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { - if (data && data.domainId) { - connect.core.voiceIdDomainId = data.domainId; + }, CCP_IFRAME_REFRESH_INTERVAL); + + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { + this.unsubscribe(); + global.clearInterval(connect.core.iframeRefreshInterval); + connect.core.iframeRefreshInterval = null; + connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); + if ((params.loginPopupAutoClose || (params.loginOptions && params.loginOptions.autoClose)) && connect.core.loginWindow) { + connect.core.loginWindow.close(); + connect.core.loginWindow = null; + } + }); + } + }); + + if (params.onViewContact) { + connect.core.onViewContact(params.onViewContact); } - }); - // keep the softphone params for external use - connect.core.softphoneParams = params.softphone; + conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { + connect.numberOfConnectedCCPs = data.length; + }); + + conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { + if (data && data.domainId) { + connect.core.voiceIdDomainId = data.domainId; + } + }); + + // keep the softphone params for external use + connect.core.softphoneParams = params.softphone; + } }; /**-----------------------------------------------------------------------*/ diff --git a/src/request-storage-access.js b/src/request-storage-access.js new file mode 100644 index 00000000..65af1465 --- /dev/null +++ b/src/request-storage-access.js @@ -0,0 +1,392 @@ +/** + * Module which gets used for the Request storage access + * Exposes init, hasAccess, request and onRequest methods. + * utilizes core post message technique to communicate back to the parent which invokes the storage access + * + * @usage - Used by initCCP and customer can make use of onRequest callbacks , this will be called even before agent login + * + * Example - + * connect.storageAccess.onRequest({ + * onInit(){}, + * onDeny(){}, + * onGrant(){} + * }); + * + * There are 4 lifecycle methods in the storage access check + * + * a) Request - StreamJS would request for storage access check to the embedded Connect hosted storage access banner + * b) Init - Storage access banner inits the access check and sends back the current access state with hasAccess set to true or false + * this is the step where we show the actual RSA banner to agents and for custom use cases hidden container will be shown + * c) Grant [optional] - Executes when Agent/user accepts storage access or already given grant + * d) Deny [optional] - Executes when Agent/user deny the storage access/ + * + * In a positive flow - we should expect Request, Init, Grant and negative Request, Init, Deny + * + * Chrome Implementation of RSA API can be found here - https://github.com/cfredric/chrome-storage-access-api + */ +(function () { + const global = this || globalThis; + const connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + + const requestStorageAccessPath = "/request-storage-access"; + /** + * Configurable options exposed via initCCP + * By default canRequest will be set to false to make this as a explicit opt in + */ + const defaultStorageAccessParams = { + /* Config which controls the opt out/in - we expect customers to explicitely opt in. */ + canRequest: true, + /* ["custom", "default"] - decides the rsa page view */ + mode: "default", + custom: { + /** + * Only applicable for custom type RSA page and these messages should be localized by customers + * + * title: 'Cookie Notice', + * header: 'Please provide access' + * + */ + }, + }; + + let storageParams = {}; + let originalCCPUrl = ""; + let rsaContainer = null; + let onGrantCallbackInvoked = false; + let requesthandlerUnsubscriber; + + const storageAccessEvents = { + INIT: "storageAccess::init", + GRANTED: "storageAccess::granted", + DENIED: "storageAccess::denied", + REQUEST: "storageAccess::request", + }; + + const initStorageParams = (params = {}) => { + params.custom = params.custom || {}; + storageParams = { + ...defaultStorageAccessParams, + ...params, + custom: { + ...defaultStorageAccessParams.custom, + ...params.custom, + }, + }; + storageParams.canRequest = !( + storageParams.canRequest === "false" || storageParams.canRequest === false + ); + }; + + const resetStorageAccessState = () => { + storageParams = {}; + originalCCPUrl = ""; + rsaContainer = null; + }; + + /** + * Handle display none/block properties for the RTSA container, if customer have different settings like height, opacity, positions etc configured they are encouraged to use + * onRequest Callback handle to reset the same. + * */ + const getRSAContainer = () => ({ + show: () => { + rsaContainer.style.display = "block"; + }, + hide: () => { + rsaContainer.style.display = "none"; + }, + }); + + /** + * Custom Mode will show minimalistic UI - without any Connect references or Connect headers + * This will allow fully Custom CCPs to use banner and use minimal real estate to show the storage access Content + * */ + const isCustomRequestAccessMode = () => + storageParams && storageParams.mode !== "default"; + + const isConnectDomain = (origin) => + origin.match(/.connect.aws.a2z.com|.my.connect.aws|.awsapps.com/); + + /** + * Given the URL, this method generates the prefixed connect domain request storage access URL + * @param {string} url + * @returns {string} + */ + const getRsaUrlWithprefix = (url) => { + const { origin, pathname } = new URL(url); + if (origin.match(/.awsapps.com/)) { + let prefix = "connect"; + if (pathname.startsWith("/connect-gamma")) { + prefix = "connect-gamma"; + } + return `${origin}/${prefix}${requestStorageAccessPath}`; + } else { + return `${origin}${requestStorageAccessPath}`; + } + }; + + const isLocalhost = (url) => url.match(/^https?:\/\/localhost/); + + /** + * Fetches the landat path for request storage access page to navigate. This is typically CCP path or channel view + * @returns {string} + */ + const getlandAtPath = () => { + if (!originalCCPUrl) { + throw new Error( + "[StorageAccess] [getlandAtPath] Invoke connect.storageAccess.init first" + ); + } + + if (isConnectDomain(originalCCPUrl) || isLocalhost(originalCCPUrl)) { + const { pathname } = new URL(originalCCPUrl); + return pathname; + } + + return "/connect/ccp-v2"; + }; + + /** + * + * Method which returns the relative request-storage-access page path. + * Validates against localhost and connect domains and returns prefixed path + * @returns {string} + */ + const getRequestStorageAccessUrl = () => { + // ccpUrl may contain non standard direct SSO URLs in which case we may ask customers to provide instanceUrl as part of storage access params + + if (!originalCCPUrl) { + throw new Error( + "[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first" + ); + } + + if (isConnectDomain(originalCCPUrl)) { + return getRsaUrlWithprefix(originalCCPUrl); + } else if (isLocalhost(originalCCPUrl)) { + connect.getLog().info(`[StorageAccess] [CCP] Local testing`); + return `${originalCCPUrl}${requestStorageAccessPath}`; + } else if ( + storageParams.instanceUrl && + isConnectDomain(storageParams.instanceUrl) + ) { + connect + .getLog() + .info( + `[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ${storageParams.instanceUrl}` + ); + + return getRsaUrlWithprefix(storageParams.instanceUrl); + } else if ( + storageParams.instanceUrl && + isLocalhost(storageParams.instanceUrl) + ) { + connect + .getLog() + .info(`[StorageAccess] [getRequestStorageAccessUrl] Local testing`); + return `${storageParams.instanceUrl}${requestStorageAccessPath}`; + } else { + connect + .getLog() + .error( + `[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters` + ); + // FIXME - For test cases to succeed passing original parameter back instead throw an error by fixing all the CCP URL parameters accross the tests. + throw new Error( + `[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL` + ); + } + }; + + /** + * Method which allows customers to listen on Storage access request and it's state changes + * @param {Object} consists of callbacks for the onInit, onDeny and onGrants + */ + const onRequestHandler = ({ onInit, onDeny, onGrant }) => { + function handleUpstreamMessages({ data, source }) { + const iframeContainer = connect.core._getCCPIframe(); + if (iframeContainer.contentWindow !== source) { + // disabling the logs for now + // connect.getLog().error('[StorageAccess][onRequestHandler] Request Coming from unknown domain %s', origin); + return false; + } + + if (connect.core.initialized) { + window.removeEventListener("message", handleUpstreamMessages); + } + + switch (data.event) { + case storageAccessEvents.INIT: { + connect + .getLog() + .info(`[StorageAccess][INIT] message recieved`) + .withObject(data); + if (onInit) { + onInit(data); + } + break; + } + + case storageAccessEvents.GRANTED: { + connect + .getLog() + .info(`[StorageAccess][GRANTED] message recieved`) + .withObject(data); + if (onGrant) { + onGrant(data); + } + break; + } + + case storageAccessEvents.DENIED: { + connect + .getLog() + .info(`[StorageAccess][DENIED] message recieved`) + .withObject(data); + if (onDeny) { + onDeny(data); + } + break; + } + + default: { + // Make sure to clean up the handler as soon as the access is granted. + if (connect.core.initialized) { + window.removeEventListener("message", handleUpstreamMessages); + } + break; + } + } + } + // do this only if canRequest is set to true + if (storageParams.canRequest) { + window.addEventListener("message", handleUpstreamMessages); + } + + return { + unsubscribe: () => { + window.removeEventListener("message", handleUpstreamMessages); + }, + }; + }; + + /** + * setupRequestHandlers - method which attaches post message handlers and let the initCCP flow to continue. + * In case of custom CCPs - it also does hide/show the container. + * @param {*} param0 + */ + const setupRequestHandlers = ({ onGrant: onGrantCallback }) => { + if (requesthandlerUnsubscriber) { + requesthandlerUnsubscriber.unsubscribe(); + } + + requesthandlerUnsubscriber = onRequestHandler({ + onInit: (messageData) => { + console.log( + "%c[INIT]", + "background:lime; color: black; font-size:large" + ); + connect + .getLog() + .info(`[StorageAccess][onInit] callback executed`) + .withObject(messageData?.data); + + if (!messageData?.data.hasAccess && isCustomRequestAccessMode()) { + getRSAContainer().show(); + } + }, + + onDeny: () => { + console.log( + "%c[DENIED]", + "background:lime; color: black; font-size:large" + ); + connect.getLog().info(`[StorageAccess][onDeny] callback executed`); + if (isCustomRequestAccessMode()) { + getRSAContainer().show(); + } + }, + + onGrant: () => { + console.log( + "%c[Granted]", + "background:lime; color: black; font-size:large" + ); + connect.getLog().info(`[StorageAccess][onGrant] callback executed`); + if (isCustomRequestAccessMode()) { + getRSAContainer().hide(); + } + // Invoke onGrantCallback only once as it setsup initCCP callbacks and events + if (!onGrantCallbackInvoked) { + onGrantCallback(); + onGrantCallbackInvoked = true; + } + }, + }); + }; + + connect.storageAccess = Object.freeze({ + /** + * Checks wther user has opted out for storage Access checks or not + * @returns {boolean} + */ + canRequest: () => storageParams.canRequest, + + /** + * Mainly used by Tests, by default storage access is enabled for all + */ + optOutFromRequestAccess: () => { + defaultStorageAccessParams.canRequest = false; + }, + + /** + * Mainly used by Tests + */ + optInForRequestAccess: () => { + defaultStorageAccessParams.canRequest = true; + }, + + /** + * Method which inits the Storage Access module with Customer paramters. + * and generates request storage access URL and apply customization to the default paramters + * @param {*} params - storage access params + * @param {*} container - Container where CCP is being shown + * @returns {{canRequest, requestAccessPageurl}} + */ + init: (ccpUrl, containerDiv, params = {}) => { + connect.assertNotNull(ccpUrl, "ccpUrl"); + connect.assertNotNull(containerDiv, "container"); + rsaContainer = containerDiv; + originalCCPUrl = ccpUrl; + initStorageParams(params); + connect + .getLog() + .info( + `[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ${ccpUrl} - ${ + !storageParams.canRequest + ? "user has opted out, skipping request storage access" + : "Proceeding with requesting storage access" + }` + ) + .withObject(storageParams); + }, + + setupRequestHandlers, + getRequestStorageAccessUrl, + storageAccessEvents, + resetStorageAccessState, + getStorageAccessParams: () => storageParams, + onRequest: onRequestHandler, + request: () => { + const iframeContainer = connect.core._getCCPIframe(); + iframeContainer.contentWindow.postMessage( + { + event: storageAccessEvents.REQUEST, + data: { ...storageParams, landat: getlandAtPath() }, + }, + "*" + ); + }, + }); +})(); diff --git a/test/unit/request-storage-access.spec.js b/test/unit/request-storage-access.spec.js new file mode 100644 index 00000000..b9c21067 --- /dev/null +++ b/test/unit/request-storage-access.spec.js @@ -0,0 +1,379 @@ +const { expect } = require("chai"); + +require("../unit/test-setup.js"); + +/** + * Todo of all the test cases which will be handled as part of a separate CR + */ +describe("Request Storage Access module", () => { + let ccpUrl, container, iframe, sandbox, postMessageSpy; + + if (typeof window === "undefined") { + jsdom({ url: "http://localhost" }); + } + + before(() => { + sandbox = sinon.createSandbox(); + connect.storageAccess.optInForRequestAccess(); + }); + + beforeEach(() => { + ccpUrl = "https://test122.awsapps.com/connect/ccp-v2"; + container = document.createElement("div"); + iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + postMessageSpy = sandbox.spy(); + }); + + afterEach(() => { + sandbox.restore(); + document.body.removeChild(iframe); + }); + + function mockMessageFromIframe(data = {}) { + sandbox.replace(window, "addEventListener", (type, callback) => { + console.log("mockMessageFromIframe", data); + callback({ + data: data, + source: window, + origin: ccpUrl, + }); + }); + } + + function createCcpIframeStub() { + sandbox.replace(connect.core, "_getCCPIframe", () => { + console.log("fake iframe "); + return iframe; + }); + } + + describe("Init method", () => { + it("should throw a ValueError if we call without the parameter", function () { + assert.throws( + () => connect.storageAccess.init(null, container), + connect.ValueError + ); + assert.throws( + () => connect.storageAccess.init(ccpUrl), + connect.ValueError + ); + }); + + it("Should return canRequest true with no additional settings from customers and they will be opted in by default", () => { + connect.storageAccess.init(ccpUrl, container); + expect(connect.storageAccess.canRequest()).to.be.true; + }); + + it("Should return canRequest false with explicit customer opt out", () => { + connect.storageAccess.init(ccpUrl, container, { + canRequest: false, + }); + expect(connect.storageAccess.canRequest()).to.be.false; + }); + + it('Should return canRequest false with explicit customer opt out with string value "false"', () => { + connect.storageAccess.init(ccpUrl, container, { + canRequest: "false", + }); + expect(connect.storageAccess.canRequest()).to.be.false; + }); + + it('Should return canRequest true with customer config "true"', () => { + connect.storageAccess.init(ccpUrl, container, { + canRequest: "true", + }); + expect(connect.storageAccess.canRequest()).to.be.true; + }); + + it("Should apply custom params based on the storage access custom paramters", () => { + let customParams = { + header: "myHeader", + canRequest: true, + title: "title", + style: { + "primary-color": "green", + }, + mode: "custom", + custom: { + denyBannerButtonText: "Try again", + }, + }; + connect.storageAccess.init(ccpUrl, container, customParams); + + expect(connect.storageAccess.canRequest()).to.be.true; + expect(connect.storageAccess.getStorageAccessParams()).to.deep.equal( + customParams + ); + }); + }); + + describe("getRequestStorageAccessUrl method", () => { + it("should return requestAccessPageurl for new domain", () => { + connect.storageAccess.init( + "https://test122.my.connect.aws/ccp-v2", + container + ); + + expect(connect.storageAccess.getRequestStorageAccessUrl()).to.be.equal( + "https://test122.my.connect.aws/request-storage-access" + ); + }); + it("should return requestAccessPageurl for old domain", () => { + connect.storageAccess.init( + "https://test122.awsapps.com/connect/ccp-v2", + container + ); + expect(connect.storageAccess.getRequestStorageAccessUrl()).to.be.equal( + "https://test122.awsapps.com/connect/request-storage-access" + ); + }); + + it("should return requestAccessPageurl as instanceUrl if ccpURL doesnt match the connect domains", () => { + connect.storageAccess.init( + "https://test122.com/connect/ccp-v2", + container, + { + instanceUrl: "https://test.awsapps.com", + } + ); + expect(connect.storageAccess.getRequestStorageAccessUrl()).to.be.equal( + "https://test.awsapps.com/connect/request-storage-access" + ); + }); + + it("should return requestAccessPageurl if ccpUrl being localhost", () => { + connect.storageAccess.init("https://localhost:3000", container); + expect(connect.storageAccess.getRequestStorageAccessUrl()).to.be.equal( + "https://localhost:3000/request-storage-access" + ); + }); + + it("should return requestAccessPageurl if instanceUrl being localhost", () => { + connect.storageAccess.init( + "https://test122.com/connect/ccp-v2", + container, + { + instanceUrl: "https://localhost:9000", + } + ); + expect(connect.storageAccess.getRequestStorageAccessUrl()).to.be.equal( + "https://localhost:9000/request-storage-access" + ); + }); + + it("should throw error if no valid connect URLs being provided to initCCP call", () => { + connect.storageAccess.init( + "https://test122.com/connect/ccp-v2", + container, + { + instanceUrl: "https://localhossst:9000", + } + ); + + assert.throws( + () => { + connect.storageAccess.getRequestStorageAccessUrl(); + }, + Error, + "[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL" + ); + }); + + it("should throw error if getRequestStorageAccessUrl called before init", () => { + connect.storageAccess.resetStorageAccessState(); + assert.throws( + () => { + connect.storageAccess.getRequestStorageAccessUrl(); + }, + Error, + "[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first" + ); + }); + }); + + describe("Request method", () => { + let onGrantSpy; + + beforeEach(() => { + onGrantSpy = sandbox.spy(); + createCcpIframeStub(); + sandbox.replaceGetter(iframe, "contentWindow", () => window); + sandbox.replace(window, "postMessage", postMessageSpy); + }); + + it("Should trigger REQUEST post message and invoke onGrant callback", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.GRANTED, + data: {}, + }); + + connect.storageAccess.init(ccpUrl, container); + connect.storageAccess.setupRequestHandlers({ onGrant: onGrantSpy }); + connect.storageAccess.request(); + + expect(postMessageSpy.called).to.be.true; + let storageAccessRequestArgs = postMessageSpy.getCall(0).args[0]; + console.log(storageAccessRequestArgs); + expect(storageAccessRequestArgs.event).to.be.equals( + "storageAccess::request" + ); + expect(storageAccessRequestArgs.data.landat).to.be.equals( + "/connect/ccp-v2" + ); + + expect(onGrantSpy.called).to.be.true; + connect.storageAccess.request(); + + /** Should be called only once */ + expect(onGrantSpy.calledTwice).not.to.be.true; + }); + + it("Should hide container if no access for custom types", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.GRANTED, + data: {}, + }); + + connect.storageAccess.init(ccpUrl, container, { mode: "custom" }); + connect.storageAccess.setupRequestHandlers({ onGrant: onGrantSpy }); + connect.storageAccess.request(); + + expect(postMessageSpy.called).to.be.true; + + expect(container.style.display).to.be.equals("none"); + }); + + it("Should display container if no access for custom types", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.DENIED, + data: {}, + }); + + connect.storageAccess.init(ccpUrl, container, { mode: "custom" }); + connect.storageAccess.setupRequestHandlers({ onGrant: onGrantSpy }); + connect.storageAccess.request(); + + expect(postMessageSpy.called).to.be.true; + + expect(container.style.display).to.be.equals("block"); + }); + }); + + describe("OnRequestHandlers", () => { + let removeListerStub; + let onInitSpy, onDenySpy, onGrantSpy; + + beforeEach(() => { + onInitSpy = sandbox.spy(); + onDenySpy = sandbox.spy(); + onGrantSpy = sandbox.spy(); + removeListerStub = sandbox.stub(window, "removeEventListener"); + createCcpIframeStub(); + sandbox.replaceGetter(iframe, "contentWindow", () => window); + sandbox.replace(window, "postMessage", postMessageSpy); + connect.storageAccess.init(ccpUrl, container); + }); + + it("Should execute onInit callback", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.INIT, + data: { + hasAccess: true, + }, + }); + + connect.storageAccess.onRequest({ + onInit: onInitSpy, + onDeny: onDenySpy, + onGrant: onGrantSpy, + }); + + expect(onInitSpy.called).to.be.true; + expect( + onInitSpy.calledWith({ + event: "storageAccess::init", + data: { hasAccess: true }, + }) + ).to.be.true; + }); + + it("Should execute onDeny callback", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.DENIED, + data: { + hasAccess: true, + }, + }); + + connect.storageAccess.onRequest({ + onInit: onInitSpy, + onDeny: onDenySpy, + onGrant: onGrantSpy, + }); + + expect(onDenySpy.called).to.be.true; + }); + + it("Should execute onGrant callback", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.GRANTED, + data: { + hasAccess: true, + }, + }); + + connect.storageAccess.onRequest({ + onInit: onInitSpy, + onDeny: onDenySpy, + onGrant: onGrantSpy, + }); + + expect(onGrantSpy.called).to.be.true; + }); + it("Should remove onRequestHandler event listener as soon as ccp is initialized", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.GRANTED, + data: { + hasAccess: true, + }, + }); + + connect.storageAccess.onRequest({ + onInit: onInitSpy, + onDeny: onDenySpy, + onGrant: onGrantSpy, + }); + + expect(onGrantSpy.called).to.be.true; + + sandbox.stub(connect.core, "initialized").value(true); + + connect.storageAccess.onRequest({ + onInit: onInitSpy, + onDeny: onDenySpy, + onGrant: onGrantSpy, + }); + expect(removeListerStub.called).to.be.true; + }); + + it("Should remove onRequestHandler after invoking unsubscribe", () => { + mockMessageFromIframe({ + event: connect.storageAccess.storageAccessEvents.GRANTED, + data: { + hasAccess: true, + }, + }); + + let unsubscriber = connect.storageAccess.onRequest({ + onInit: onInitSpy, + onDeny: onDenySpy, + onGrant: onGrantSpy, + }); + + expect(onGrantSpy.called).to.be.true; + unsubscriber.unsubscribe(); + expect(removeListerStub.called).to.be.true; + }); + }); +}); diff --git a/test/unit/test-setup.js b/test/unit/test-setup.js index b54e4ec9..a2fdd901 100644 --- a/test/unit/test-setup.js +++ b/test/unit/test-setup.js @@ -27,6 +27,7 @@ global.AWS = { before(() => { global.sinon.stub(connect.Agent.prototype, "_getResourceId").returns("id"); + connect.storageAccess.optOutFromRequestAccess(); }); after(() => { global.sinon.restore(); diff --git a/webpack/common.js b/webpack/common.js new file mode 100644 index 00000000..f73978f2 --- /dev/null +++ b/webpack/common.js @@ -0,0 +1,17 @@ +module.exports = { + commonConfig: { + module: { + rules: [ + { + test: /\.ts(x)?$/, + loader: 'ts-loader', + exclude: /node_modules/, + }, + ], + }, + resolve: { + extensions: ['.tsx', '.ts', '.js'], + }, + mode: 'production', + }, +}; diff --git a/webpack/connect-streams-min.config.js b/webpack/connect-streams-min.config.js new file mode 100644 index 00000000..6c230009 --- /dev/null +++ b/webpack/connect-streams-min.config.js @@ -0,0 +1,27 @@ +const webpack = require('webpack'); +const path = require('path'); +const TerserPlugin = require('terser-webpack-plugin'); +const { commonConfig } = require('./common'); + +const minimizedConfig = Object.assign({}, commonConfig, { + entry: ['./release/connect-streams.js'], + output: { + path: path.resolve(__dirname, '../release'), + filename: 'connect-streams-min.js', + }, + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + format: { + comments: false, + }, + }, + extractComments: false, + }), + ], + }, +}); + +module.exports = [minimizedConfig]; diff --git a/webpack/connect-streams.config.js b/webpack/connect-streams.config.js new file mode 100644 index 00000000..de23ba73 --- /dev/null +++ b/webpack/connect-streams.config.js @@ -0,0 +1,63 @@ +const webpack = require("webpack"); +const ReplacePlugin = require("webpack-plugin-replace"); +const path = require("path"); +const { commonConfig } = require("./common"); + +const config = Object.assign({}, commonConfig, { + entry: [ + "./src/aws-client.js", + "./src/sprintf.js", + "./src/log.js", + "./src/util.js", + "./src/event.js", + "./src/streams.js", + "./src/client.js", + "./src/transitions.js", + "./src/api.js", + "./src/lib/amazon-connect-websocket-manager.js", + "./src/request-storage-access.js", + "./src/core.js", + "./src/ringtone.js", + "./src/softphone.js", + "./src/worker.js", + "./src/mediaControllers/chat.js", + "./src/mediaControllers/factory.js", + "./src/mediaControllers/softphone.js", + "./src/mediaControllers/task.js", + "./src/agent-app/agent-app.js", + "./src/agent-app/app-registry.js", + ], + output: { + path: path.resolve(__dirname, "../release"), + filename: "connect-streams.js", + clean: true, + }, + optimization: { + minimize: false, + }, + plugins: [ + new ReplacePlugin({ + include: "core.js", + + values: { + STREAMS_VERSION: process.env.npm_package_version, + }, + }), + ], + module: { + rules: [ + { + test: /\.m?js$/, + include: path.resolve(__dirname, "../src"), + use: { + loader: "babel-loader", + options: { + presets: ["@babel/preset-typescript", "@babel/preset-env"], + }, + }, + }, + ], + }, +}); + +module.exports = [config]; From 0f30f3758a69eae4070e3d2d63b9daad487377a1 Mon Sep 17 00:00:00 2001 From: jagadeeeshaby Date: Thu, 21 Sep 2023 22:33:07 -0700 Subject: [PATCH 2/3] Remove prettier config --- .prettierignore | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 .prettierignore diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index eeb97745..00000000 --- a/.prettierignore +++ /dev/null @@ -1,21 +0,0 @@ -**/src/lib/* -**/src/md5.js -**/src/aws-client.js -**/src/core.js -**/src/event.js -**/src/log.js -**/src/ringtone.js -**/src/sprintf.js -**/src/transitions.js -**/src/util.js -**/src/worker.js -**/src/client.js -**/src/api.js -**/src/drCoordinator/* -**/src/agent-app/* -**/src/index.d.ts -**/src/softphone.js -**/src/task.js -**/src/streams.js -**/src/userMediaProvider.js -**/test/* \ No newline at end of file From aae36fc7d21ed47e5b5cc3570741e11ec1bf8e66 Mon Sep 17 00:00:00 2001 From: jagadeeeshaby Date: Thu, 21 Sep 2023 22:54:39 -0700 Subject: [PATCH 3/3] Formatting changes --- src/core.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core.js b/src/core.js index 37554b1c..81a7ee7c 100644 --- a/src/core.js +++ b/src/core.js @@ -798,7 +798,7 @@ iframe.name = CCP_IFRAME_NAME; //for Storage Access follow the rsa path - if(connect.storageAccess.canRequest()){ + if(connect.storageAccess.canRequest()) { iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); iframe.addEventListener('load', connect.storageAccess.request); } @@ -822,10 +822,10 @@ - if (connect.storageAccess.canRequest()) { + if (connect.storageAccess.canRequest()) { // Create the Iframe and load the RSA banner and append it to the container div. connect.storageAccess.setupRequestHandlers({ onGrant: setupInitCCP }); - }else{ + } else { setupInitCCP(); }