From 243ee78bff962dcf8c5d625b6f221e511176fbf7 Mon Sep 17 00:00:00 2001 From: Seiya Kobayashi Date: Fri, 12 Aug 2022 15:14:17 +0000 Subject: [PATCH] Releasing Version 2.3.0 --- .crux_template.md | 28 - CHANGELOG.md | 5 + Documentation.md | 4 +- README.md | 2 + package-lock.json | 5140 ++++++- package.json | 5 +- release/connect-streams-min.js | 2 +- release/connect-streams.js | 12701 +++++++++------- src/agent-app/agent-app.js | 2 +- src/agent-app/app-registry.js | 2 +- src/api.js | 98 +- src/aws-client.js | 9252 ++++++----- src/client.js | 2 +- src/core.js | 11 +- src/event.js | 3 +- src/index.d.ts | 7 + src/lib/amazon-connect-websocket-manager.js | 2 +- .../amazon-connect-websocket-manager.js.map | 2 +- src/log.js | 2 +- src/mediaControllers/chat.js | 2 +- src/mediaControllers/factory.js | 2 +- src/mediaControllers/softphone.js | 2 +- src/mediaControllers/task.js | 2 +- src/ringtone.js | 2 +- src/softphone.js | 2 +- src/sprintf.js | 2 +- src/streams.js | 2 +- src/transitions.js | 2 +- src/util.js | 46 +- src/worker.js | 2 +- test/unit/connections.spec.js | 2 +- test/unit/core.spec.js | 59 +- 32 files changed, 17078 insertions(+), 10319 deletions(-) delete mode 100644 .crux_template.md diff --git a/.crux_template.md b/.crux_template.md deleted file mode 100644 index 8bdc61c4..00000000 --- a/.crux_template.md +++ /dev/null @@ -1,28 +0,0 @@ -**Describe the change** - - -**If the answer is no to any question below this line, feel free to leave it blank.** - -### Engineering impact considerations - -1. Are you submitting this change without the necessary corresponding integration tests? If so, why? - -1. Is this change unsafe to deploy to production? If so, why? - -1. Please consider [all Streams use cases](https://quip-amazon.com/VsiUAiiQ30pA/RCA-Mute-Button-Intuit#TZH9CAE8NFs). Do you think this change will behave differently in one or more of [these use cases](https://quip-amazon.com/VsiUAiiQ30pA/RCA-Mute-Button-Intuit#TZH9CAE8NFs)? If so, why? Have you tested those scenarios? - -1. Does this change send logs to the server ([LilaxLogsProcessorService](https://code.amazon.com/packages/LilaxLogsProcessorServiceLambda/trees/mainline)) using `sendInternalLogToServer` or `sendInternalLogEntryToServer`? If so, have you ensured that there is no PII (Name, login, phone number, auth token etc.) in the logs? - -*Keep in mind that Streams is a third party package and as such, you will need to manually build these changes into our version set ([AmazonConnectCCPStaticWebsite/development](https://code.amazon.com/version-sets/AmazonConnectCCPStaticWebsite/development)) before these changes are pushed through the pipeline.* - -### Product team considerations - -**If the answer to any of these questions is yes, please alert the product team.** - -1. Will this change impact agent behavior? If so, has it been cleared by the product team? - -1. Will this change require new product documentation? - -1. Will this change introduce improvements that customers should know about? - - diff --git a/CHANGELOG.md b/CHANGELOG.md index 490461d4..17b16400 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # CHANGELOG.md +## 2.3.0 +- Fix an issue in Streams’ Voice ID APIs that may have led to incorrect values being set against the generatedSpeakerID field in the VoiceIdResult segment of Connect Contact Trace Records (CTRs). +- Make StreamsJS compatible with strict mode +- Fix an issue that connect.ValueError and connect.StateError don't print error message properly + ## 2.2.0 Added functions: * `contact.getChannelContext` method to get the channel context for the contact. See Documentation.md for more details diff --git a/Documentation.md b/Documentation.md index 76163fbf..aab4c49e 100644 --- a/Documentation.md +++ b/Documentation.md @@ -12,6 +12,8 @@ Run `npm run release` to generate new release files. Full instructions for build In version 1.x, we also support `make` for legacy builds. This option was removed in version 2.x. # Important Announcements +1. August 2022 - 2.3.0 + * This patch fixes an issue in Streams’ Voice ID APIs that may have led to incorrect values being set against the generatedSpeakerID field in the VoiceIdResult segment of Connect Contact Trace Records (CTRs). This occurred in some scenarios where you call either enrollSpeakerInVoiceId(), evaluateSpeakerWithVoiceId(), or updateVoiceIdSpeakerId() in your custom CCP integration code. If you are using Voice ID and consuming Voice ID CTRs, please upgrade to this version. 1. Jan 2022 - 2.0.0 * Multiple calls to `initCCP` will no longer append multiple embedded CCPs to the window, and only the first call to `initCCP` will succeed. Please note that the use-case of initializing multiple CCPs has never been supported by Streams, and this change has been added to prevent unpredictable behavior arising from such cases. * `agent.onContactPending` has been removed. Please use `contact.onPending` instead. `connect.onError` now triggers. Previously, this api did not work at all. Please be aware that, if you have application logic within this function, its behavior has changed. See its entry in documentation.md for more details. @@ -716,7 +718,7 @@ agent.connect(endpoint, { } }); ``` -Creates an outbound contact to the given endpoint. You can optionally provide a `queueARN` to associate the contact with a queue. +Creates an outbound contact to the given endpoint. Only phone number endpoints are supported. You can optionally provide a `queueARN` to associate the contact with a queue. Optional success and failure callbacks can be provided to determine if the operation was successful. diff --git a/README.md b/README.md index bb3b4cb9..7c28ccdd 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ Run `npm run release` to generate new release files. Full instructions for build In version 1.x, we also support `make` for legacy builds. This option was removed in version 2.x. # Important Announcements +1. August 2022 - 2.3.0 + * This patch fixes an issue in Streams’ Voice ID APIs that may have led to incorrect values being set against the generatedSpeakerID field in the VoiceIdResult segment of Connect Contact Trace Records (CTRs). This occurred in some scenarios where you call either enrollSpeakerInVoiceId(), evaluateSpeakerWithVoiceId(), or updateVoiceIdSpeakerId() in your custom CCP integration code. If you are using Voice ID and consuming Voice ID CTRs, please upgrade to this version. 1. Jan 2022 - 2.0.0 * Multiple calls to `initCCP` will no longer append multiple embedded CCPs to the window, and only the first call to `initCCP` will succeed. Please note that the use-case of initializing multiple CCPs with `initCCP` has never been supported by Streams, and this change has been added to prevent unpredictable behavior arising from such cases. * `agent.onContactPending` has been removed. Please use `contact.onPending` instead. `connect.onError` now triggers. Previously, this api did not work at all. Please be aware that, if you have application logic within this function, its behavior has changed. See its entry in documentation.md for more details. diff --git a/package-lock.json b/package-lock.json index c3bbc3af..01624d9a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,45 +1,4290 @@ { "name": "amazon-connect-streams", - "version": "2.2.0", - "lockfileVersion": 1, + "version": "2.3.0", + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "amazon-connect-streams", + "version": "2.3.0", + "license": "Apache-2.0", + "devDependencies": { + "chai": "^4.1.2", + "jshint": "^2.9.7", + "mocha": "^9.1.3", + "mocha-jsdom": "^2.0.0", + "nyc": "^15.1.0", + "pump": "^3.0.0", + "sinon": "^9.0.0", + "terser-webpack-plugin": "^5.2.5", + "typescript": "^4.2.4", + "webpack": "^5.64.4", + "webpack-cli": "^4.9.1", + "webpack-plugin-replace": "^1.2.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.2.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.18.8", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.18.10", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.10", + "@babel/helper-compilation-targets": "^7.18.9", + "@babel/helper-module-transforms": "^7.18.9", + "@babel/helpers": "^7.18.9", + "@babel/parser": "^7.18.10", + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.18.10", + "@babel/types": "^7.18.10", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.18.12", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.10", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping": { + "version": "0.3.2", + "dev": true, + "license": "MIT", + "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/@babel/helper-compilation-targets": { + "version": "7.18.9", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.18.8", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.20.2", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.18.9", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.18.9", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.18.6", + "@babel/types": "^7.18.9" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.18.9", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.18.6", + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.18.10", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.18.9", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/parser": { + "version": "7.18.11", + "dev": true, + "license": "MIT", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/template": { + "version": "7.18.10", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.18.6", + "@babel/parser": "^7.18.10", + "@babel/types": "^7.18.10" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.18.11", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.10", + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-function-name": "^7.18.9", + "@babel/helper-hoist-variables": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/parser": "^7.18.11", + "@babel/types": "^7.18.10", + "debug": "^4.1.0", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.18.10", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.18.10", + "@babel/helper-validator-identifier": "^7.18.6", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@discoveryjs/json-ext": { + "version": "0.5.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "dev": true, + "license": "ISC", + "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", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "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", + "dev": true, + "license": "MIT", + "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", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "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", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "node_modules/@jridgewell/source-map/node_modules/@jridgewell/gen-mapping": { + "version": "0.3.2", + "dev": true, + "license": "MIT", + "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/sourcemap-codec": { + "version": "1.4.14", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@sinonjs/commons": { + "version": "1.8.3", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "6.0.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^1.7.0" + } + }, + "node_modules/@sinonjs/samsam": { + "version": "5.3.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^1.6.0", + "lodash.get": "^4.4.2", + "type-detect": "^4.0.8" + } + }, + "node_modules/@sinonjs/text-encoding": { + "version": "0.7.2", + "dev": true, + "license": "(Unlicense OR Apache-2.0)" + }, + "node_modules/@types/eslint": { + "version": "8.4.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "0.0.51", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.11", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "18.7.1", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/promise-all-settled": { + "version": "1.1.2", + "dev": true, + "license": "ISC" + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/helper-numbers": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.1", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.1", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.11.1", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.1", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.1", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.1", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/helper-wasm-section": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-opt": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "@webassemblyjs/wast-printer": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.11.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webpack-cli/configtest": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "peerDependencies": { + "webpack": "4.x.x || 5.x.x", + "webpack-cli": "4.x.x" + } + }, + "node_modules/@webpack-cli/info": { + "version": "1.5.0", + "dev": true, + "license": "MIT", + "dependencies": { + "envinfo": "^7.7.3" + }, + "peerDependencies": { + "webpack-cli": "4.x.x" + } + }, + "node_modules/@webpack-cli/serve": { + "version": "1.7.0", + "dev": true, + "license": "MIT", + "peerDependencies": { + "webpack-cli": "4.x.x" + }, + "peerDependenciesMeta": { + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/abab": { + "version": "2.0.6", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/acorn": { + "version": "5.7.4", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-globals": { + "version": "4.3.4", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^6.0.1", + "acorn-walk": "^6.0.1" + } + }, + "node_modules/acorn-globals/node_modules/acorn": { + "version": "6.4.2", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "6.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "dev": true, + "license": "MIT", + "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" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "dev": true, + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.2", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-transform": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "default-require-extensions": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/archy": { + "version": "1.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/array-equal": { + "version": "1.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/asn1": { + "version": "0.2.6", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/async-limiter": { + "version": "1.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "dev": true, + "license": "MIT" + }, + "node_modules/aws-sign2": { + "version": "0.7.0", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "*" + } + }, + "node_modules/aws4": { + "version": "1.11.0", + "dev": true, + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browser-process-hrtime": { + "version": "1.0.0", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/browser-stdout": { + "version": "1.3.1", + "dev": true, + "license": "ISC" + }, + "node_modules/browserslist": { + "version": "4.21.3", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001370", + "electron-to-chromium": "^1.4.202", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.5" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "dev": true, + "license": "MIT" + }, + "node_modules/caching-transform": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "hasha": "^5.0.0", + "make-dir": "^3.0.0", + "package-hash": "^4.0.0", + "write-file-atomic": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001375", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/caseless": { + "version": "0.12.0", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/chai": { + "version": "4.3.6", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^3.0.1", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/check-error": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT", + "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" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cli": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "exit": "0.1.2", + "glob": "^7.1.1" + }, + "engines": { + "node": ">=0.2.5" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/clone-deep": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "dev": true, + "license": "MIT" + }, + "node_modules/colorette": { + "version": "2.0.19", + "dev": true, + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "dev": true, + "license": "MIT" + }, + "node_modules/commondir": { + "version": "1.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/console-browserify": { + "version": "1.1.0", + "dev": true, + "dependencies": { + "date-now": "^0.1.4" + } + }, + "node_modules/convert-source-map": { + "version": "1.8.0", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.1" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssom": { + "version": "0.3.8", + "dev": true, + "license": "MIT" + }, + "node_modules/cssstyle": { + "version": "1.4.0", + "dev": true, + "license": "MIT", + "dependencies": { + "cssom": "0.3.x" + } + }, + "node_modules/dashdash": { + "version": "1.14.1", + "dev": true, + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/data-urls": { + "version": "1.1.0", + "dev": true, + "license": "MIT", + "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", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, + "node_modules/date-now": { + "version": "0.1.4", + "dev": true + }, + "node_modules/debug": { + "version": "4.3.3", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "dev": true, + "license": "MIT" + }, + "node_modules/decamelize": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deep-eql": { + "version": "3.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "dev": true, + "license": "MIT" + }, + "node_modules/default-require-extensions": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "strip-bom": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/diff": { + "version": "5.0.0", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dom-serializer": { + "version": "0.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "entities": "^2.0.0" + } + }, + "node_modules/dom-serializer/node_modules/domelementtype": { + "version": "2.3.0", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "2.2.0", + "dev": true, + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "1.3.1", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/domexception": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "webidl-conversions": "^4.0.2" + } + }, + "node_modules/domhandler": { + "version": "2.3.0", + "dev": true, + "dependencies": { + "domelementtype": "1" + } + }, + "node_modules/domutils": { + "version": "1.5.1", + "dev": true, + "dependencies": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, + "node_modules/ecc-jsbn": { + "version": "0.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.4.217", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "dev": true, + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.10.0", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/entities": { + "version": "1.0.0", + "dev": true, + "license": "BSD-like" + }, + "node_modules/envinfo": { + "version": "7.8.1", + "dev": true, + "license": "MIT", + "bin": { + "envinfo": "dist/cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/es-module-lexer": { + "version": "0.9.3", + "dev": true, + "license": "MIT" + }, + "node_modules/es6-error": { + "version": "4.1.1", + "dev": true, + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/escodegen": { + "version": "1.14.3", + "dev": true, + "license": "BSD-2-Clause", + "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" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/exit": { + "version": "0.1.2", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/extsprintf": { + "version": "1.3.0", + "dev": true, + "engines": [ + "node >=0.6.0" + ], + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "dev": true, + "license": "MIT" + }, + "node_modules/fastest-levenshtein": { + "version": "1.0.16", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4.9.1" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-cache-dir": { + "version": "3.3.2", + "dev": true, + "license": "MIT", + "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" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "dev": true, + "license": "BSD-3-Clause", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/foreground-child": { + "version": "2.0.0", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/forever-agent": { + "version": "0.6.1", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "*" + } + }, + "node_modules/form-data": { + "version": "2.3.3", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/fromentries": { + "version": "1.3.2", + "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" + } + ], + "license": "MIT" + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/function-bind": { + "version": "1.1.1", + "dev": true, + "license": "MIT" + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-func-name": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/getpass": { + "version": "0.1.7", + "dev": true, + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/globals": { + "version": "11.12.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.10", + "dev": true, + "license": "ISC" + }, + "node_modules/growl": { + "version": "1.10.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.x" + } + }, + "node_modules/har-schema": { + "version": "2.0.0", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=4" + } + }, + "node_modules/har-validator": { + "version": "5.1.5", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/has": { + "version": "1.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasha": { + "version": "5.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "is-stream": "^2.0.0", + "type-fest": "^0.8.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/he": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^1.0.1" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/htmlparser2": { + "version": "3.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "1", + "domhandler": "2.3", + "domutils": "1.5", + "entities": "1.0", + "readable-stream": "1.1" + } + }, + "node_modules/http-signature": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.3.7" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/import-local": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "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" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "dev": true, + "license": "ISC" + }, + "node_modules/interpret": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.10.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-plain-obj": { + "version": "2.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "dev": true, + "license": "MIT", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-windows": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isarray": { + "version": "0.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/isobject": { + "version": "3.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isstream": { + "version": "0.1.2", + "dev": true, + "license": "MIT" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.0", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-hook": { + "version": "3.0.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "append-transform": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "4.0.3", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.7.5", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.0.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-processinfo": { + "version": "2.0.3", + "dev": true, + "license": "ISC", + "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" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.1.5", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbn": { + "version": "0.1.1", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "11.12.0", + "dev": true, + "license": "MIT", + "dependencies": { + "abab": "^2.0.0", + "acorn": "^5.5.3", + "acorn-globals": "^4.1.0", + "array-equal": "^1.0.0", + "cssom": ">= 0.3.2 < 0.4.0", + "cssstyle": "^1.0.0", + "data-urls": "^1.0.0", + "domexception": "^1.0.1", + "escodegen": "^1.9.1", + "html-encoding-sniffer": "^1.0.2", + "left-pad": "^1.3.0", + "nwsapi": "^2.0.7", + "parse5": "4.0.0", + "pn": "^1.1.0", + "request": "^2.87.0", + "request-promise-native": "^1.0.5", + "sax": "^1.2.4", + "symbol-tree": "^3.2.2", + "tough-cookie": "^2.3.4", + "w3c-hr-time": "^1.0.1", + "webidl-conversions": "^4.0.2", + "whatwg-encoding": "^1.0.3", + "whatwg-mimetype": "^2.1.0", + "whatwg-url": "^6.4.1", + "ws": "^5.2.0", + "xml-name-validator": "^3.0.0" + } + }, + "node_modules/jsesc": { + "version": "2.5.2", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/jshint": { + "version": "2.13.5", + "dev": true, + "license": "MIT", + "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", + "strip-json-comments": "1.0.x" + }, + "bin": { + "jshint": "bin/jshint" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema": { + "version": "0.4.0", + "dev": true, + "license": "(AFL-2.1 OR BSD-3-Clause)" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "dev": true, + "license": "ISC" + }, + "node_modules/json5": { + "version": "2.2.1", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsprim": { + "version": "1.4.2", + "dev": true, + "license": "MIT", + "dependencies": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/just-extend": { + "version": "4.2.1", + "dev": true, + "license": "MIT" + }, + "node_modules/kind-of": { + "version": "6.0.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/left-pad": { + "version": "1.3.0", + "dev": true, + "license": "WTFPL" + }, + "node_modules/levn": { + "version": "0.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.flattendeep": { + "version": "4.4.0", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.get": { + "version": "4.4.2", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.sortby": { + "version": "4.7.0", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loupe": { + "version": "2.3.4", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.0" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.0.8", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha": { + "version": "9.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@ungap/promise-all-settled": "1.1.2", + "ansi-colors": "4.1.1", + "browser-stdout": "1.3.1", + "chokidar": "3.5.3", + "debug": "4.3.3", + "diff": "5.0.0", + "escape-string-regexp": "4.0.0", + "find-up": "5.0.0", + "glob": "7.2.0", + "growl": "1.10.5", + "he": "1.2.0", + "js-yaml": "4.1.0", + "log-symbols": "4.1.0", + "minimatch": "4.2.1", + "ms": "2.1.3", + "nanoid": "3.3.1", + "serialize-javascript": "6.0.0", + "strip-json-comments": "3.1.1", + "supports-color": "8.1.1", + "which": "2.0.2", + "workerpool": "6.2.0", + "yargs": "16.2.0", + "yargs-parser": "20.2.4", + "yargs-unparser": "2.0.0" + }, + "bin": { + "_mocha": "bin/_mocha", + "mocha": "bin/mocha" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mochajs" + } + }, + "node_modules/mocha-jsdom": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "jsdom": "^11.11.0" + }, + "peerDependencies": { + "mocha": "*" + } + }, + "node_modules/mocha/node_modules/glob": { + "version": "7.2.0", + "dev": true, + "license": "ISC", + "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" + } + }, + "node_modules/mocha/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha/node_modules/minimatch": { + "version": "4.2.1", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mocha/node_modules/strip-json-comments": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.1", + "dev": true, + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "dev": true, + "license": "MIT" + }, + "node_modules/nise": { + "version": "4.1.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^1.7.0", + "@sinonjs/fake-timers": "^6.0.0", + "@sinonjs/text-encoding": "^0.7.1", + "just-extend": "^4.0.2", + "path-to-regexp": "^1.7.0" + } + }, + "node_modules/node-preload": { + "version": "0.2.1", + "dev": true, + "license": "MIT", + "dependencies": { + "process-on-spawn": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/node-releases": { + "version": "2.0.6", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nwsapi": { + "version": "2.2.1", + "dev": true, + "license": "MIT" + }, + "node_modules/nyc": { + "version": "15.1.0", + "dev": true, + "license": "ISC", + "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" + } + }, + "node_modules/nyc/node_modules/cliui": { + "version": "6.0.0", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/nyc/node_modules/find-up": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/nyc/node_modules/locate-path": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/nyc/node_modules/p-limit": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nyc/node_modules/p-locate": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/nyc/node_modules/wrap-ansi": { + "version": "6.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/nyc/node_modules/y18n": { + "version": "4.0.3", + "dev": true, + "license": "ISC" + }, + "node_modules/nyc/node_modules/yargs": { + "version": "15.4.1", + "dev": true, + "license": "MIT", + "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", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/oauth-sign": { + "version": "0.9.0", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "*" + } + }, + "node_modules/once": { + "version": "1.4.0", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optionator": { + "version": "0.8.3", + "dev": true, + "license": "MIT", + "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" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-map": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/package-hash": { + "version": "4.0.0", + "dev": true, + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.15", + "hasha": "^5.0.0", + "lodash.flattendeep": "^4.4.0", + "release-zalgo": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/parse5": { + "version": "4.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/path-exists": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "dev": true, + "license": "MIT" + }, + "node_modules/path-to-regexp": { + "version": "1.8.0", + "dev": true, + "license": "MIT", + "dependencies": { + "isarray": "0.0.1" + } + }, + "node_modules/pathval": { + "version": "1.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/performance-now": { + "version": "2.1.0", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/find-up": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/locate-path": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/p-limit": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-dir/node_modules/p-locate": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pn": { + "version": "1.1.0", + "dev": true, + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.1.2", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/process-on-spawn": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "fromentries": "^1.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/psl": { + "version": "1.9.0", + "dev": true, + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.5.3", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readable-stream": { + "version": "1.1.14", + "dev": true, + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/rechoir": { + "version": "0.7.1", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve": "^1.9.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/release-zalgo": { + "version": "1.0.0", + "dev": true, + "license": "ISC", + "dependencies": { + "es6-error": "^4.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/request": { + "version": "2.88.2", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/request-promise-core": { + "version": "1.1.4", + "dev": true, + "license": "ISC", + "dependencies": { + "lodash": "^4.17.19" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "request": "^2.34" + } + }, + "node_modules/request-promise-native": { + "version": "1.0.9", + "dev": true, + "license": "ISC", + "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" + } + }, + "node_modules/request/node_modules/uuid": { + "version": "3.4.0", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/resolve": { + "version": "1.22.1", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "dev": true, + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.2.4", + "dev": true, + "license": "ISC" + }, + "node_modules/schema-utils": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "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" + } + }, + "node_modules/semver": { + "version": "6.3.0", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "dev": true, + "license": "ISC" + }, + "node_modules/sinon": { + "version": "9.2.4", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@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" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/sinon" + } + }, + "node_modules/sinon/node_modules/diff": { + "version": "4.0.2", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/sinon/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/spawn-wrap": { + "version": "2.0.0", + "dev": true, + "license": "ISC", + "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" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/sshpk": { + "version": "1.17.0", + "dev": true, + "license": "MIT", + "dependencies": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stealthy-require": { + "version": "1.1.1", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string_decoder": { + "version": "0.10.31", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width": { + "version": "4.2.3", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "1.0.4", + "dev": true, + "license": "MIT", + "bin": { + "strip-json-comments": "cli.js" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/supports-color": { + "version": "8.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.2.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/terser": { + "version": "5.14.2", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.2", + "acorn": "^8.5.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.7", + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.0", + "terser": "^5.7.2" + }, + "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 + } + } + }, + "node_modules/terser/node_modules/acorn": { + "version": "8.8.0", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tough-cookie": { + "version": "2.5.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tr46": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "dev": true, + "license": "Unlicense" + }, + "node_modules/type-check": { + "version": "0.3.2", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.8.1", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=8" + } + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "dev": true, + "license": "MIT", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/typescript": { + "version": "4.7.4", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.0.5", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + }, + "bin": { + "browserslist-lint": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/verror": { + "version": "1.10.0", + "dev": true, + "engines": [ + "node >=0.6.0" + ], + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "node_modules/verror/node_modules/core-util-is": { + "version": "1.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/w3c-hr-time": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "browser-process-hrtime": "^1.0.0" + } + }, + "node_modules/watchpack": { + "version": "2.4.0", + "dev": true, + "license": "MIT", + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webidl-conversions": { + "version": "4.0.2", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/webpack": { + "version": "5.74.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/eslint-scope": "^3.7.3", + "@types/estree": "^0.0.51", + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/wasm-edit": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "acorn": "^8.7.1", + "acorn-import-assertions": "^1.7.6", + "browserslist": "^4.14.5", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.10.0", + "es-module-lexer": "^0.9.0", + "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.1.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.1.3", + "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 + } + } + }, + "node_modules/webpack-cli": { + "version": "4.10.0", + "dev": true, + "license": "MIT", + "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 + } + } + }, + "node_modules/webpack-cli/node_modules/commander": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/webpack-merge": { + "version": "5.8.0", + "dev": true, + "license": "MIT", + "dependencies": { + "clone-deep": "^4.0.1", + "wildcard": "^2.0.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/webpack-plugin-replace": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/webpack-sources": { + "version": "3.2.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack/node_modules/acorn": { + "version": "8.8.0", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/webpack/node_modules/acorn-import-assertions": { + "version": "1.8.0", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/whatwg-encoding": { + "version": "1.0.5", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.4.24" + } + }, + "node_modules/whatwg-mimetype": { + "version": "2.3.0", + "dev": true, + "license": "MIT" + }, + "node_modules/whatwg-url": { + "version": "6.5.0", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, + "node_modules/which": { + "version": "2.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-module": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/wildcard": { + "version": "2.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/word-wrap": { + "version": "1.2.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/workerpool": { + "version": "6.2.0", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "dev": true, + "license": "MIT", + "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" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "dev": true, + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "3.0.3", + "dev": true, + "license": "ISC", + "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", + "dev": true, + "license": "MIT", + "dependencies": { + "async-limiter": "~1.0.0" + } + }, + "node_modules/xml-name-validator": { + "version": "3.0.0", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/y18n": { + "version": "5.0.8", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.4", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-unparser": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "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", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yargs-unparser/node_modules/decamelize": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + }, "dependencies": { "@ampproject/remapping": { - "version": "2.1.2", - "integrity": "sha512-hoyByceqwKirw7w3Z7gnIIZC3Wx3J484Y3L/cMpXFbr7d9ZQj2mODrirNzcJa+SM3UlpWXYvKV4RlRpFXlWgXg==", + "version": "2.2.0", "dev": true, "requires": { - "@jridgewell/trace-mapping": "^0.3.0" + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" } }, "@babel/code-frame": { - "version": "7.16.7", - "integrity": "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==", + "version": "7.18.6", "dev": true, "requires": { - "@babel/highlight": "^7.16.7" + "@babel/highlight": "^7.18.6" } }, "@babel/compat-data": { - "version": "7.17.7", - "integrity": "sha512-p8pdE6j0a29TNGebNm7NzYZWB3xVZJBZ7XGs42uAKzQo8VQ3F0By/cQCtUEABwIqw5zo6WA4NbmxsfzADzMKnQ==", + "version": "7.18.8", "dev": true }, "@babel/core": { - "version": "7.17.9", - "integrity": "sha512-5ug+SfZCpDAkVp9SFIZAzlW18rlzsOcJGaetCjkySnrXXDUw9AR8cDUm1iByTmdWM6yxX6/zycaV76w3YTF2gw==", + "version": "7.18.10", "dev": true, "requires": { "@ampproject/remapping": "^2.1.0", - "@babel/code-frame": "^7.16.7", - "@babel/generator": "^7.17.9", - "@babel/helper-compilation-targets": "^7.17.7", - "@babel/helper-module-transforms": "^7.17.7", - "@babel/helpers": "^7.17.9", - "@babel/parser": "^7.17.9", - "@babel/template": "^7.16.7", - "@babel/traverse": "^7.17.9", - "@babel/types": "^7.17.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.10", + "@babel/helper-compilation-targets": "^7.18.9", + "@babel/helper-module-transforms": "^7.18.9", + "@babel/helpers": "^7.18.9", + "@babel/parser": "^7.18.10", + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.18.10", + "@babel/types": "^7.18.10", "convert-source-map": "^1.7.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -48,130 +4293,121 @@ } }, "@babel/generator": { - "version": "7.17.9", - "integrity": "sha512-rAdDousTwxbIxbz5I7GEQ3lUip+xVCXooZNbsydCWs3xA7ZsYOv+CFRdzGxRX78BmQHu9B1Eso59AOZQOJDEdQ==", + "version": "7.18.12", "dev": true, "requires": { - "@babel/types": "^7.17.0", - "jsesc": "^2.5.1", - "source-map": "^0.5.0" + "@babel/types": "^7.18.10", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" }, "dependencies": { - "source-map": { - "version": "0.5.7", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true + "@jridgewell/gen-mapping": { + "version": "0.3.2", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + } } } }, "@babel/helper-compilation-targets": { - "version": "7.17.7", - "integrity": "sha512-UFzlz2jjd8kroj0hmCFV5zr+tQPi1dpC2cRsDV/3IEW8bJfCPrPpmcSN6ZS8RqIq4LXcmpipCQFPddyFA5Yc7w==", + "version": "7.18.9", "dev": true, "requires": { - "@babel/compat-data": "^7.17.7", - "@babel/helper-validator-option": "^7.16.7", - "browserslist": "^4.17.5", + "@babel/compat-data": "^7.18.8", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.20.2", "semver": "^6.3.0" } }, "@babel/helper-environment-visitor": { - "version": "7.16.7", - "integrity": "sha512-SLLb0AAn6PkUeAfKJCCOl9e1R53pQlGAfc4y4XuMRZfqeMYLE0dM1LMhqbGAlGQY0lfw5/ohoYWAe9V1yibRag==", - "dev": true, - "requires": { - "@babel/types": "^7.16.7" - } + "version": "7.18.9", + "dev": true }, "@babel/helper-function-name": { - "version": "7.17.9", - "integrity": "sha512-7cRisGlVtiVqZ0MW0/yFB4atgpGLWEHUVYnb448hZK4x+vih0YO5UoS11XIYtZYqHd0dIPMdUSv8q5K4LdMnIg==", + "version": "7.18.9", "dev": true, "requires": { - "@babel/template": "^7.16.7", - "@babel/types": "^7.17.0" + "@babel/template": "^7.18.6", + "@babel/types": "^7.18.9" } }, "@babel/helper-hoist-variables": { - "version": "7.16.7", - "integrity": "sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg==", + "version": "7.18.6", "dev": true, "requires": { - "@babel/types": "^7.16.7" + "@babel/types": "^7.18.6" } }, "@babel/helper-module-imports": { - "version": "7.16.7", - "integrity": "sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg==", + "version": "7.18.6", "dev": true, "requires": { - "@babel/types": "^7.16.7" + "@babel/types": "^7.18.6" } }, "@babel/helper-module-transforms": { - "version": "7.17.7", - "integrity": "sha512-VmZD99F3gNTYB7fJRDTi+u6l/zxY0BE6OIxPSU7a50s6ZUQkHwSDmV92FfM+oCG0pZRVojGYhkR8I0OGeCVREw==", + "version": "7.18.9", "dev": true, "requires": { - "@babel/helper-environment-visitor": "^7.16.7", - "@babel/helper-module-imports": "^7.16.7", - "@babel/helper-simple-access": "^7.17.7", - "@babel/helper-split-export-declaration": "^7.16.7", - "@babel/helper-validator-identifier": "^7.16.7", - "@babel/template": "^7.16.7", - "@babel/traverse": "^7.17.3", - "@babel/types": "^7.17.0" + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.18.6", + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" } }, "@babel/helper-simple-access": { - "version": "7.17.7", - "integrity": "sha512-txyMCGroZ96i+Pxr3Je3lzEJjqwaRC9buMUgtomcrLe5Nd0+fk1h0LLA+ixUF5OW7AhHuQ7Es1WcQJZmZsz2XA==", + "version": "7.18.6", "dev": true, "requires": { - "@babel/types": "^7.17.0" + "@babel/types": "^7.18.6" } }, "@babel/helper-split-export-declaration": { - "version": "7.16.7", - "integrity": "sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw==", + "version": "7.18.6", "dev": true, "requires": { - "@babel/types": "^7.16.7" + "@babel/types": "^7.18.6" } }, + "@babel/helper-string-parser": { + "version": "7.18.10", + "dev": true + }, "@babel/helper-validator-identifier": { - "version": "7.16.7", - "integrity": "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==", + "version": "7.18.6", "dev": true }, "@babel/helper-validator-option": { - "version": "7.16.7", - "integrity": "sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ==", + "version": "7.18.6", "dev": true }, "@babel/helpers": { - "version": "7.17.9", - "integrity": "sha512-cPCt915ShDWUEzEp3+UNRktO2n6v49l5RSnG9M5pS24hA+2FAc5si+Pn1i4VVbQQ+jh+bIZhPFQOJOzbrOYY1Q==", + "version": "7.18.9", "dev": true, "requires": { - "@babel/template": "^7.16.7", - "@babel/traverse": "^7.17.9", - "@babel/types": "^7.17.0" + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" } }, "@babel/highlight": { - "version": "7.17.9", - "integrity": "sha512-J9PfEKCbFIv2X5bjTMiZu6Vf341N05QIY+d6FvVKynkG1S7G0j3I0QoRtWIrXhZ+/Nlb5Q0MzqL7TokEJ5BNHg==", + "version": "7.18.6", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.16.7", + "@babel/helper-validator-identifier": "^7.18.6", "chalk": "^2.0.0", "js-tokens": "^4.0.0" }, "dependencies": { "ansi-styles": { "version": "3.2.1", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "requires": { "color-convert": "^1.9.0" @@ -179,7 +4415,6 @@ }, "chalk": { "version": "2.4.2", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "requires": { "ansi-styles": "^3.2.1", @@ -189,7 +4424,6 @@ }, "color-convert": { "version": "1.9.3", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, "requires": { "color-name": "1.1.3" @@ -197,22 +4431,18 @@ }, "color-name": { "version": "1.1.3", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, "escape-string-regexp": { "version": "1.0.5", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "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" @@ -221,54 +4451,49 @@ } }, "@babel/parser": { - "version": "7.17.9", - "integrity": "sha512-vqUSBLP8dQHFPdPi9bc5GK9vRkYHJ49fsZdtoJ8EQ8ibpwk5rPKfvNIwChB0KVXcIjcepEBBd2VHC5r9Gy8ueg==", + "version": "7.18.11", "dev": true }, "@babel/template": { - "version": "7.16.7", - "integrity": "sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w==", + "version": "7.18.10", "dev": true, "requires": { - "@babel/code-frame": "^7.16.7", - "@babel/parser": "^7.16.7", - "@babel/types": "^7.16.7" + "@babel/code-frame": "^7.18.6", + "@babel/parser": "^7.18.10", + "@babel/types": "^7.18.10" } }, "@babel/traverse": { - "version": "7.17.9", - "integrity": "sha512-PQO8sDIJ8SIwipTPiR71kJQCKQYB5NGImbOviK8K+kg5xkNSYXLBupuX9QhatFowrsvo9Hj8WgArg3W7ijNAQw==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.16.7", - "@babel/generator": "^7.17.9", - "@babel/helper-environment-visitor": "^7.16.7", - "@babel/helper-function-name": "^7.17.9", - "@babel/helper-hoist-variables": "^7.16.7", - "@babel/helper-split-export-declaration": "^7.16.7", - "@babel/parser": "^7.17.9", - "@babel/types": "^7.17.0", + "version": "7.18.11", + "dev": true, + "requires": { + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.10", + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-function-name": "^7.18.9", + "@babel/helper-hoist-variables": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/parser": "^7.18.11", + "@babel/types": "^7.18.10", "debug": "^4.1.0", "globals": "^11.1.0" } }, "@babel/types": { - "version": "7.17.0", - "integrity": "sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw==", + "version": "7.18.10", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.16.7", + "@babel/helper-string-parser": "^7.18.10", + "@babel/helper-validator-identifier": "^7.18.6", "to-fast-properties": "^2.0.0" } }, "@discoveryjs/json-ext": { "version": "0.5.7", - "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==", "dev": true }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", "dev": true, "requires": { "camelcase": "^5.3.1", @@ -280,20 +4505,13 @@ "dependencies": { "argparse": { "version": "1.0.10", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, "requires": { "sprintf-js": "~1.0.2" } }, - "camelcase": { - "version": "5.3.1", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, "find-up": { "version": "4.1.0", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { "locate-path": "^5.0.0", @@ -302,7 +4520,6 @@ }, "js-yaml": { "version": "3.14.1", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", "dev": true, "requires": { "argparse": "^1.0.7", @@ -311,7 +4528,6 @@ }, "locate-path": { "version": "5.0.0", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { "p-locate": "^4.1.0" @@ -319,7 +4535,6 @@ }, "p-limit": { "version": "2.3.0", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { "p-try": "^2.0.0" @@ -327,7 +4542,6 @@ }, "p-locate": { "version": "4.1.0", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { "p-limit": "^2.2.0" @@ -337,22 +4551,49 @@ }, "@istanbuljs/schema": { "version": "0.1.3", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", "dev": true }, + "@jridgewell/gen-mapping": { + "version": "0.1.1", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, "@jridgewell/resolve-uri": { - "version": "3.0.5", - "integrity": "sha512-VPeQ7+wH0itvQxnG+lIzWgkysKIr3L9sslimFW55rHMdGu/qCQ5z5h9zq4gI8uBtqkpHhsF4Z/OwExufUCThew==", + "version": "3.1.0", "dev": true }, + "@jridgewell/set-array": { + "version": "1.1.2", + "dev": true + }, + "@jridgewell/source-map": { + "version": "0.3.2", + "dev": true, + "requires": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "dependencies": { + "@jridgewell/gen-mapping": { + "version": "0.3.2", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + } + } + } + }, "@jridgewell/sourcemap-codec": { - "version": "1.4.11", - "integrity": "sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg==", + "version": "1.4.14", "dev": true }, "@jridgewell/trace-mapping": { - "version": "0.3.4", - "integrity": "sha512-vFv9ttIedivx0ux3QSjhgtCVjPZd5l46ZOMDSCwnH1yUO2e964gO8LZGyv2QkqcgR6TnBU1v+1IFqmeoG+0UJQ==", + "version": "0.3.15", "dev": true, "requires": { "@jridgewell/resolve-uri": "^3.0.3", @@ -361,7 +4602,6 @@ }, "@sinonjs/commons": { "version": "1.8.3", - "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", "dev": true, "requires": { "type-detect": "4.0.8" @@ -369,7 +4609,6 @@ }, "@sinonjs/fake-timers": { "version": "6.0.1", - "integrity": "sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA==", "dev": true, "requires": { "@sinonjs/commons": "^1.7.0" @@ -377,7 +4616,6 @@ }, "@sinonjs/samsam": { "version": "5.3.1", - "integrity": "sha512-1Hc0b1TtyfBu8ixF/tpfSHTVWKwCBLY4QJbkgnE7HcwyvT2xArDxb4K7dMgqRm3szI+LJbzmW/s4xxEhv6hwDg==", "dev": true, "requires": { "@sinonjs/commons": "^1.6.0", @@ -386,13 +4624,11 @@ } }, "@sinonjs/text-encoding": { - "version": "0.7.1", - "integrity": "sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==", + "version": "0.7.2", "dev": true }, "@types/eslint": { - "version": "8.4.1", - "integrity": "sha512-GE44+DNEyxxh2Kc6ro/VkIj+9ma0pO0bwv9+uHSyBrikYOHr8zYcdPvnBOp1aw8s+CjRvuSx7CyWqRrNFQ59mA==", + "version": "8.4.5", "dev": true, "requires": { "@types/estree": "*", @@ -400,8 +4636,7 @@ } }, "@types/eslint-scope": { - "version": "3.7.3", - "integrity": "sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g==", + "version": "3.7.4", "dev": true, "requires": { "@types/eslint": "*", @@ -410,27 +4645,22 @@ }, "@types/estree": { "version": "0.0.51", - "integrity": "sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==", "dev": true }, "@types/json-schema": { "version": "7.0.11", - "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", "dev": true }, "@types/node": { - "version": "17.0.24", - "integrity": "sha512-aveCYRQbgTH9Pssp1voEP7HiuWlD2jW2BO56w+bVrJn04i61yh6mRfoKO6hEYQD9vF+W8Chkwc6j1M36uPkx4g==", + "version": "18.7.1", "dev": true }, "@ungap/promise-all-settled": { "version": "1.1.2", - "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==", "dev": true }, "@webassemblyjs/ast": { "version": "1.11.1", - "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==", "dev": true, "requires": { "@webassemblyjs/helper-numbers": "1.11.1", @@ -439,22 +4669,18 @@ }, "@webassemblyjs/floating-point-hex-parser": { "version": "1.11.1", - "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==", "dev": true }, "@webassemblyjs/helper-api-error": { "version": "1.11.1", - "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==", "dev": true }, "@webassemblyjs/helper-buffer": { "version": "1.11.1", - "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==", "dev": true }, "@webassemblyjs/helper-numbers": { "version": "1.11.1", - "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==", "dev": true, "requires": { "@webassemblyjs/floating-point-hex-parser": "1.11.1", @@ -464,12 +4690,10 @@ }, "@webassemblyjs/helper-wasm-bytecode": { "version": "1.11.1", - "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==", "dev": true }, "@webassemblyjs/helper-wasm-section": { "version": "1.11.1", - "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==", "dev": true, "requires": { "@webassemblyjs/ast": "1.11.1", @@ -480,7 +4704,6 @@ }, "@webassemblyjs/ieee754": { "version": "1.11.1", - "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==", "dev": true, "requires": { "@xtuc/ieee754": "^1.2.0" @@ -488,7 +4711,6 @@ }, "@webassemblyjs/leb128": { "version": "1.11.1", - "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==", "dev": true, "requires": { "@xtuc/long": "4.2.2" @@ -496,12 +4718,10 @@ }, "@webassemblyjs/utf8": { "version": "1.11.1", - "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==", "dev": true }, "@webassemblyjs/wasm-edit": { "version": "1.11.1", - "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==", "dev": true, "requires": { "@webassemblyjs/ast": "1.11.1", @@ -516,7 +4736,6 @@ }, "@webassemblyjs/wasm-gen": { "version": "1.11.1", - "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==", "dev": true, "requires": { "@webassemblyjs/ast": "1.11.1", @@ -528,7 +4747,6 @@ }, "@webassemblyjs/wasm-opt": { "version": "1.11.1", - "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==", "dev": true, "requires": { "@webassemblyjs/ast": "1.11.1", @@ -539,7 +4757,6 @@ }, "@webassemblyjs/wasm-parser": { "version": "1.11.1", - "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==", "dev": true, "requires": { "@webassemblyjs/ast": "1.11.1", @@ -552,7 +4769,6 @@ }, "@webassemblyjs/wast-printer": { "version": "1.11.1", - "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==", "dev": true, "requires": { "@webassemblyjs/ast": "1.11.1", @@ -560,46 +4776,40 @@ } }, "@webpack-cli/configtest": { - "version": "1.1.1", - "integrity": "sha512-1FBc1f9G4P/AxMqIgfZgeOTuRnwZMten8E7zap5zgpPInnCrP8D4Q81+4CWIch8i/Nf7nXjP0v6CjjbHOrXhKg==", - "dev": true + "version": "1.2.0", + "dev": true, + "requires": {} }, "@webpack-cli/info": { - "version": "1.4.1", - "integrity": "sha512-PKVGmazEq3oAo46Q63tpMr4HipI3OPfP7LiNOEJg963RMgT0rqheag28NCML0o3GIzA3DmxP1ZIAv9oTX1CUIA==", + "version": "1.5.0", "dev": true, "requires": { "envinfo": "^7.7.3" } }, "@webpack-cli/serve": { - "version": "1.6.1", - "integrity": "sha512-gNGTiTrjEVQ0OcVnzsRSqTxaBSr+dmTfm+qJsCDluky8uhdLWep7Gcr62QsAKHTMxjCS/8nEITsmFAhfIx+QSw==", - "dev": true + "version": "1.7.0", + "dev": true, + "requires": {} }, "@xtuc/ieee754": { "version": "1.2.0", - "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", "dev": true }, "@xtuc/long": { "version": "4.2.2", - "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", "dev": true }, "abab": { - "version": "2.0.5", - "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", + "version": "2.0.6", "dev": true }, "acorn": { "version": "5.7.4", - "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", "dev": true }, "acorn-globals": { "version": "4.3.4", - "integrity": "sha512-clfQEh21R+D0leSbUdWf3OcfqyaCSAQ8Ryq00bofSekfr9W8u1jyYZo6ir0xu9Gtcf7BjcHJpnbZH7JOCpP60A==", "dev": true, "requires": { "acorn": "^6.0.1", @@ -608,24 +4818,16 @@ "dependencies": { "acorn": { "version": "6.4.2", - "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", "dev": true } } }, - "acorn-import-assertions": { - "version": "1.8.0", - "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==", - "dev": true - }, "acorn-walk": { "version": "6.2.0", - "integrity": "sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA==", "dev": true }, "aggregate-error": { "version": "3.1.0", - "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", "dev": true, "requires": { "clean-stack": "^2.0.0", @@ -634,7 +4836,6 @@ }, "ajv": { "version": "6.12.6", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "requires": { "fast-deep-equal": "^3.1.1", @@ -645,22 +4846,19 @@ }, "ajv-keywords": { "version": "3.5.2", - "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", - "dev": true + "dev": true, + "requires": {} }, "ansi-colors": { "version": "4.1.1", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", "dev": true }, "ansi-regex": { "version": "5.0.1", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { "version": "4.3.0", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { "color-convert": "^2.0.1" @@ -668,7 +4866,6 @@ }, "anymatch": { "version": "3.1.2", - "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", "dev": true, "requires": { "normalize-path": "^3.0.0", @@ -677,7 +4874,6 @@ }, "append-transform": { "version": "2.0.0", - "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", "dev": true, "requires": { "default-require-extensions": "^3.0.0" @@ -685,22 +4881,18 @@ }, "archy": { "version": "1.0.0", - "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", "dev": true }, "argparse": { "version": "2.0.1", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, "array-equal": { "version": "1.0.0", - "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", "dev": true }, "asn1": { "version": "0.2.6", - "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", "dev": true, "requires": { "safer-buffer": "~2.1.0" @@ -708,42 +4900,34 @@ }, "assert-plus": { "version": "1.0.0", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true }, "assertion-error": { "version": "1.1.0", - "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", "dev": true }, "async-limiter": { "version": "1.0.1", - "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==", "dev": true }, "asynckit": { "version": "0.4.0", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "dev": true }, "aws-sign2": { "version": "0.7.0", - "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", "dev": true }, "aws4": { "version": "1.11.0", - "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", "dev": true }, "balanced-match": { "version": "1.0.2", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, "bcrypt-pbkdf": { "version": "1.0.2", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", "dev": true, "requires": { "tweetnacl": "^0.14.3" @@ -751,12 +4935,10 @@ }, "binary-extensions": { "version": "2.2.0", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", "dev": true }, "brace-expansion": { "version": "1.1.11", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, "requires": { "balanced-match": "^1.0.0", @@ -765,7 +4947,6 @@ }, "braces": { "version": "3.0.2", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "dev": true, "requires": { "fill-range": "^7.0.1" @@ -773,34 +4954,28 @@ }, "browser-process-hrtime": { "version": "1.0.0", - "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, "browser-stdout": { "version": "1.3.1", - "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", "dev": true }, "browserslist": { - "version": "4.20.2", - "integrity": "sha512-CQOBCqp/9pDvDbx3xfMi+86pr4KXIf2FDkTTdeuYw8OxS9t898LA1Khq57gtufFILXpfgsSx5woNgsBgvGjpsA==", + "version": "4.21.3", "dev": true, "requires": { - "caniuse-lite": "^1.0.30001317", - "electron-to-chromium": "^1.4.84", - "escalade": "^3.1.1", - "node-releases": "^2.0.2", - "picocolors": "^1.0.0" + "caniuse-lite": "^1.0.30001370", + "electron-to-chromium": "^1.4.202", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.5" } }, "buffer-from": { "version": "1.1.2", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, "caching-transform": { "version": "4.0.0", - "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", "dev": true, "requires": { "hasha": "^5.0.0", @@ -810,23 +4985,19 @@ } }, "camelcase": { - "version": "6.3.0", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "version": "5.3.1", "dev": true }, "caniuse-lite": { - "version": "1.0.30001332", - "integrity": "sha512-10T30NYOEQtN6C11YGg411yebhvpnC6Z102+B95eAsN0oB6KUs01ivE8u+G6FMIRtIrVlYXhL+LUwQ3/hXwDWw==", + "version": "1.0.30001375", "dev": true }, "caseless": { "version": "0.12.0", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", "dev": true }, "chai": { "version": "4.3.6", - "integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==", "dev": true, "requires": { "assertion-error": "^1.1.0", @@ -840,7 +5011,6 @@ }, "chalk": { "version": "4.1.2", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "requires": { "ansi-styles": "^4.1.0", @@ -849,7 +5019,6 @@ "dependencies": { "supports-color": { "version": "7.2.0", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -859,12 +5028,10 @@ }, "check-error": { "version": "1.0.2", - "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", "dev": true }, "chokidar": { "version": "3.5.3", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", "dev": true, "requires": { "anymatch": "~3.1.2", @@ -879,17 +5046,14 @@ }, "chrome-trace-event": { "version": "1.0.3", - "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", "dev": true }, "clean-stack": { "version": "2.2.0", - "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", "dev": true }, "cli": { "version": "1.0.1", - "integrity": "sha1-IoF1NPJL+klQw01TLUjsvGIbjBQ=", "dev": true, "requires": { "exit": "0.1.2", @@ -898,7 +5062,6 @@ }, "cliui": { "version": "7.0.4", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "requires": { "string-width": "^4.2.0", @@ -908,7 +5071,6 @@ }, "clone-deep": { "version": "4.0.1", - "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", "dev": true, "requires": { "is-plain-object": "^2.0.4", @@ -918,7 +5080,6 @@ }, "color-convert": { "version": "2.0.1", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { "color-name": "~1.1.4" @@ -926,17 +5087,14 @@ }, "color-name": { "version": "1.1.4", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "colorette": { - "version": "2.0.16", - "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==", + "version": "2.0.19", "dev": true }, "combined-stream": { "version": "1.0.8", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, "requires": { "delayed-stream": "~1.0.0" @@ -944,22 +5102,18 @@ }, "commander": { "version": "2.20.3", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "dev": true }, "commondir": { "version": "1.0.1", - "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", "dev": true }, "concat-map": { "version": "0.0.1", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, "console-browserify": { "version": "1.1.0", - "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", "dev": true, "requires": { "date-now": "^0.1.4" @@ -967,27 +5121,17 @@ }, "convert-source-map": { "version": "1.8.0", - "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", "dev": true, "requires": { "safe-buffer": "~5.1.1" - }, - "dependencies": { - "safe-buffer": { - "version": "5.1.2", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true - } } }, "core-util-is": { "version": "1.0.3", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "dev": true }, "cross-spawn": { "version": "7.0.3", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "requires": { "path-key": "^3.1.0", @@ -997,12 +5141,10 @@ }, "cssom": { "version": "0.3.8", - "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true }, "cssstyle": { "version": "1.4.0", - "integrity": "sha512-GBrLZYZ4X4x6/QEoBnIrqb8B/f5l4+8me2dkom/j1Gtbxy0kBv6OGzKuAsGM75bkGwGAFkt56Iwg28S3XTZgSA==", "dev": true, "requires": { "cssom": "0.3.x" @@ -1010,7 +5152,6 @@ }, "dashdash": { "version": "1.14.1", - "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", "dev": true, "requires": { "assert-plus": "^1.0.0" @@ -1018,7 +5159,6 @@ }, "data-urls": { "version": "1.1.0", - "integrity": "sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==", "dev": true, "requires": { "abab": "^2.0.0", @@ -1028,7 +5168,6 @@ "dependencies": { "whatwg-url": { "version": "7.1.0", - "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==", "dev": true, "requires": { "lodash.sortby": "^4.7.0", @@ -1040,12 +5179,10 @@ }, "date-now": { "version": "0.1.4", - "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", "dev": true }, "debug": { "version": "4.3.3", - "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", "dev": true, "requires": { "ms": "2.1.2" @@ -1053,19 +5190,16 @@ "dependencies": { "ms": { "version": "2.1.2", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true } } }, "decamelize": { - "version": "4.0.0", - "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", + "version": "1.2.0", "dev": true }, "deep-eql": { "version": "3.0.1", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", "dev": true, "requires": { "type-detect": "^4.0.0" @@ -1073,12 +5207,10 @@ }, "deep-is": { "version": "0.1.4", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, "default-require-extensions": { "version": "3.0.0", - "integrity": "sha512-ek6DpXq/SCpvjhpFsLFRVtIxJCRw6fUR42lYMVZuUMK7n8eMz4Uh5clckdBjEpLhn/gEBZo7hDJnJcwdKLKQjg==", "dev": true, "requires": { "strip-bom": "^4.0.0" @@ -1086,17 +5218,14 @@ }, "delayed-stream": { "version": "1.0.0", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", "dev": true }, "diff": { "version": "5.0.0", - "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", "dev": true }, "dom-serializer": { "version": "0.2.2", - "integrity": "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g==", "dev": true, "requires": { "domelementtype": "^2.0.1", @@ -1105,24 +5234,20 @@ "dependencies": { "domelementtype": { "version": "2.3.0", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", "dev": true }, "entities": { "version": "2.2.0", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", "dev": true } } }, "domelementtype": { "version": "1.3.1", - "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", "dev": true }, "domexception": { "version": "1.0.1", - "integrity": "sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==", "dev": true, "requires": { "webidl-conversions": "^4.0.2" @@ -1130,7 +5255,6 @@ }, "domhandler": { "version": "2.3.0", - "integrity": "sha1-LeWaCCLVAn+r/28DLCsloqir5zg=", "dev": true, "requires": { "domelementtype": "1" @@ -1138,7 +5262,6 @@ }, "domutils": { "version": "1.5.1", - "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", "dev": true, "requires": { "dom-serializer": "0", @@ -1147,7 +5270,6 @@ }, "ecc-jsbn": { "version": "0.1.2", - "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", "dev": true, "requires": { "jsbn": "~0.1.0", @@ -1155,26 +5277,22 @@ } }, "electron-to-chromium": { - "version": "1.4.108", - "integrity": "sha512-/36KkMuL6+WTrodVlOjtHhH9Ro7BgRaQrh0bfKckwDtdRSjTBuZCOddeXxzK1PkwphoeTxGUFVT9xnmvQ7xEdw==", + "version": "1.4.217", "dev": true }, "emoji-regex": { "version": "8.0.0", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "end-of-stream": { "version": "1.4.4", - "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", "dev": true, "requires": { "once": "^1.4.0" } }, "enhanced-resolve": { - "version": "5.9.3", - "integrity": "sha512-Bq9VSor+kjvW3f9/MiiR4eE3XYgOl7/rS8lnSxbRbF3kS0B2r+Y9w5krBWxZgDxASVZbdYrn5wT4j/Wb0J9qow==", + "version": "5.10.0", "dev": true, "requires": { "graceful-fs": "^4.2.4", @@ -1183,37 +5301,30 @@ }, "entities": { "version": "1.0.0", - "integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY=", "dev": true }, "envinfo": { "version": "7.8.1", - "integrity": "sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==", "dev": true }, "es-module-lexer": { "version": "0.9.3", - "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==", "dev": true }, "es6-error": { "version": "4.1.1", - "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", "dev": true }, "escalade": { "version": "3.1.1", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", "dev": true }, "escape-string-regexp": { "version": "4.0.0", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true }, "escodegen": { "version": "1.14.3", - "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", "dev": true, "requires": { "esprima": "^4.0.1", @@ -1225,7 +5336,6 @@ }, "eslint-scope": { "version": "5.1.1", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "requires": { "esrecurse": "^4.3.0", @@ -1234,12 +5344,10 @@ }, "esprima": { "version": "4.0.1", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true }, "esrecurse": { "version": "4.3.0", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "requires": { "estraverse": "^5.2.0" @@ -1247,80 +5355,52 @@ "dependencies": { "estraverse": { "version": "5.3.0", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true } } }, "estraverse": { "version": "4.3.0", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true }, "esutils": { "version": "2.0.3", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true }, "events": { "version": "3.3.0", - "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", "dev": true }, - "execa": { - "version": "5.1.1", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "requires": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - } - }, "exit": { "version": "0.1.2", - "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", "dev": true }, "extend": { "version": "3.0.2", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, "extsprintf": { "version": "1.3.0", - "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", "dev": true }, "fast-deep-equal": { "version": "3.1.3", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, "fast-json-stable-stringify": { "version": "2.1.0", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, "fast-levenshtein": { "version": "2.0.6", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, "fastest-levenshtein": { - "version": "1.0.12", - "integrity": "sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow==", + "version": "1.0.16", "dev": true }, "fill-range": { "version": "7.0.1", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "dev": true, "requires": { "to-regex-range": "^5.0.1" @@ -1328,7 +5408,6 @@ }, "find-cache-dir": { "version": "3.3.2", - "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", "dev": true, "requires": { "commondir": "^1.0.1", @@ -1338,7 +5417,6 @@ }, "find-up": { "version": "5.0.0", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "requires": { "locate-path": "^6.0.0", @@ -1347,12 +5425,10 @@ }, "flat": { "version": "5.0.2", - "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", "dev": true }, "foreground-child": { "version": "2.0.0", - "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, "requires": { "cross-spawn": "^7.0.0", @@ -1361,12 +5437,10 @@ }, "forever-agent": { "version": "0.6.1", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", "dev": true }, "form-data": { "version": "2.3.3", - "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", "dev": true, "requires": { "asynckit": "^0.4.0", @@ -1376,74 +5450,62 @@ }, "fromentries": { "version": "1.3.2", - "integrity": "sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg==", "dev": true }, "fs.realpath": { "version": "1.0.0", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, - "fsevents": { - "version": "2.3.2", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "optional": true - }, "function-bind": { "version": "1.1.1", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, "gensync": { "version": "1.0.0-beta.2", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", "dev": true }, "get-caller-file": { "version": "2.0.5", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "get-func-name": { "version": "2.0.0", - "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", "dev": true }, "get-package-type": { "version": "0.1.0", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true - }, - "get-stream": { - "version": "6.0.1", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", "dev": true }, "getpass": { "version": "0.1.7", - "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", "dev": true, "requires": { "assert-plus": "^1.0.0" } }, "glob": { - "version": "7.2.0", - "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "version": "7.2.3", "dev": true, "requires": { "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" + }, + "dependencies": { + "minimatch": { + "version": "3.1.2", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + } } }, "glob-parent": { "version": "5.1.2", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "requires": { "is-glob": "^4.0.1" @@ -1451,32 +5513,26 @@ }, "glob-to-regexp": { "version": "0.4.1", - "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", "dev": true }, "globals": { "version": "11.12.0", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", "dev": true }, "graceful-fs": { "version": "4.2.10", - "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", "dev": true }, "growl": { "version": "1.10.5", - "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", "dev": true }, "har-schema": { "version": "2.0.0", - "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", "dev": true }, "har-validator": { "version": "5.1.5", - "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", "dev": true, "requires": { "ajv": "^6.12.3", @@ -1485,7 +5541,6 @@ }, "has": { "version": "1.0.3", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, "requires": { "function-bind": "^1.1.1" @@ -1493,12 +5548,10 @@ }, "has-flag": { "version": "4.0.0", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, "hasha": { "version": "5.2.2", - "integrity": "sha512-Hrp5vIK/xr5SkeN2onO32H0MgNZ0f17HRNH39WfL0SYUNOTZ5Lz1TJ8Pajo/87dYGEFlLMm7mIc/k/s6Bvz9HQ==", "dev": true, "requires": { "is-stream": "^2.0.0", @@ -1507,12 +5560,10 @@ }, "he": { "version": "1.2.0", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", "dev": true }, "html-encoding-sniffer": { "version": "1.0.2", - "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", "dev": true, "requires": { "whatwg-encoding": "^1.0.1" @@ -1520,12 +5571,10 @@ }, "html-escaper": { "version": "2.0.2", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, "htmlparser2": { "version": "3.8.3", - "integrity": "sha1-mWwosZFRaovoZQGn15dX5ccMEGg=", "dev": true, "requires": { "domelementtype": "1", @@ -1537,7 +5586,6 @@ }, "http-signature": { "version": "1.2.0", - "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", "dev": true, "requires": { "assert-plus": "^1.0.0", @@ -1545,14 +5593,8 @@ "sshpk": "^1.7.0" } }, - "human-signals": { - "version": "2.1.0", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true - }, "iconv-lite": { "version": "0.4.24", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, "requires": { "safer-buffer": ">= 2.1.2 < 3" @@ -1560,7 +5602,6 @@ }, "import-local": { "version": "3.1.0", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", "dev": true, "requires": { "pkg-dir": "^4.2.0", @@ -1569,17 +5610,14 @@ }, "imurmurhash": { "version": "0.1.4", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", "dev": true }, "indent-string": { "version": "4.0.0", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", "dev": true }, "inflight": { "version": "1.0.6", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "requires": { "once": "^1.3.0", @@ -1588,25 +5626,21 @@ }, "inherits": { "version": "2.0.4", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, "interpret": { "version": "2.2.0", - "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==", "dev": true }, "is-binary-path": { "version": "2.1.0", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dev": true, "requires": { "binary-extensions": "^2.0.0" } }, "is-core-module": { - "version": "2.8.1", - "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", + "version": "2.10.0", "dev": true, "requires": { "has": "^1.0.3" @@ -1614,17 +5648,14 @@ }, "is-extglob": { "version": "2.1.1", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "is-glob": { "version": "4.0.3", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "requires": { "is-extglob": "^2.1.1" @@ -1632,17 +5663,14 @@ }, "is-number": { "version": "7.0.0", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, "is-plain-obj": { "version": "2.1.0", - "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", "dev": true }, "is-plain-object": { "version": "2.0.4", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", "dev": true, "requires": { "isobject": "^3.0.1" @@ -1650,52 +5678,42 @@ }, "is-stream": { "version": "2.0.1", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true }, "is-typedarray": { "version": "1.0.0", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", "dev": true }, "is-unicode-supported": { "version": "0.1.0", - "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", "dev": true }, "is-windows": { "version": "1.0.2", - "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", "dev": true }, "isarray": { "version": "0.0.1", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", "dev": true }, "isexe": { "version": "2.0.0", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, "isobject": { "version": "3.0.1", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", "dev": true }, "isstream": { "version": "0.1.2", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", "dev": true }, "istanbul-lib-coverage": { "version": "3.2.0", - "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", "dev": true }, "istanbul-lib-hook": { "version": "3.0.0", - "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", "dev": true, "requires": { "append-transform": "^2.0.0" @@ -1703,7 +5721,6 @@ }, "istanbul-lib-instrument": { "version": "4.0.3", - "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", "dev": true, "requires": { "@babel/core": "^7.7.5", @@ -1713,22 +5730,19 @@ } }, "istanbul-lib-processinfo": { - "version": "2.0.2", - "integrity": "sha512-kOwpa7z9hme+IBPZMzQ5vdQj8srYgAtaRqeI48NGmAQ+/5yKiHLV0QbYqQpxsdEF0+w14SoB8YbnHKcXE2KnYw==", + "version": "2.0.3", "dev": true, "requires": { "archy": "^1.0.0", - "cross-spawn": "^7.0.0", - "istanbul-lib-coverage": "^3.0.0-alpha.1", - "make-dir": "^3.0.0", + "cross-spawn": "^7.0.3", + "istanbul-lib-coverage": "^3.2.0", "p-map": "^3.0.0", "rimraf": "^3.0.0", - "uuid": "^3.3.3" + "uuid": "^8.3.2" } }, "istanbul-lib-report": { "version": "3.0.0", - "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", "dev": true, "requires": { "istanbul-lib-coverage": "^3.0.0", @@ -1738,7 +5752,6 @@ "dependencies": { "supports-color": { "version": "7.2.0", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -1748,7 +5761,6 @@ }, "istanbul-lib-source-maps": { "version": "4.0.1", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", "dev": true, "requires": { "debug": "^4.1.1", @@ -1757,8 +5769,7 @@ } }, "istanbul-reports": { - "version": "3.1.4", - "integrity": "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==", + "version": "3.1.5", "dev": true, "requires": { "html-escaper": "^2.0.0", @@ -1767,7 +5778,6 @@ }, "jest-worker": { "version": "27.5.1", - "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", "dev": true, "requires": { "@types/node": "*", @@ -1777,12 +5787,10 @@ }, "js-tokens": { "version": "4.0.0", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true }, "js-yaml": { "version": "4.1.0", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, "requires": { "argparse": "^2.0.1" @@ -1790,12 +5798,10 @@ }, "jsbn": { "version": "0.1.1", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", "dev": true }, "jsdom": { "version": "11.12.0", - "integrity": "sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==", "dev": true, "requires": { "abab": "^2.0.0", @@ -1828,12 +5834,10 @@ }, "jsesc": { "version": "2.5.2", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "dev": true }, "jshint": { - "version": "2.13.4", - "integrity": "sha512-HO3bosL84b2qWqI0q+kpT/OpRJwo0R4ivgmxaO848+bo10rc50SkPnrtwSFXttW0ym4np8jbJvLwk5NziB7jIw==", + "version": "2.13.5", "dev": true, "requires": { "cli": "~1.0.0", @@ -1845,34 +5849,28 @@ "strip-json-comments": "1.0.x" } }, - "json-parse-better-errors": { - "version": "1.0.2", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "json-parse-even-better-errors": { + "version": "2.3.1", "dev": true }, "json-schema": { "version": "0.4.0", - "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", "dev": true }, "json-schema-traverse": { "version": "0.4.1", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, "json-stringify-safe": { "version": "5.0.1", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", "dev": true }, "json5": { "version": "2.2.1", - "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", "dev": true }, "jsprim": { "version": "1.4.2", - "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", "dev": true, "requires": { "assert-plus": "1.0.0", @@ -1883,22 +5881,18 @@ }, "just-extend": { "version": "4.2.1", - "integrity": "sha512-g3UB796vUFIY90VIv/WX3L2c8CS2MdWUww3CNrYmqza1Fg0DURc2K/O4YrnklBdQarSJ/y8JnJYDGc+1iumQjg==", "dev": true }, "kind-of": { "version": "6.0.3", - "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "dev": true }, "left-pad": { "version": "1.3.0", - "integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==", "dev": true }, "levn": { "version": "0.3.0", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", "dev": true, "requires": { "prelude-ls": "~1.1.2", @@ -1907,12 +5901,10 @@ }, "loader-runner": { "version": "4.3.0", - "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", "dev": true }, "locate-path": { "version": "6.0.0", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "requires": { "p-locate": "^5.0.0" @@ -1920,27 +5912,22 @@ }, "lodash": { "version": "4.17.21", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, "lodash.flattendeep": { "version": "4.4.0", - "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=", "dev": true }, "lodash.get": { "version": "4.4.2", - "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", "dev": true }, "lodash.sortby": { "version": "4.7.0", - "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", "dev": true }, "log-symbols": { "version": "4.1.0", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", "dev": true, "requires": { "chalk": "^4.1.0", @@ -1949,7 +5936,6 @@ }, "loupe": { "version": "2.3.4", - "integrity": "sha512-OvKfgCC2Ndby6aSTREl5aCCPTNIzlDfQZvZxNUrBrihDhL3xcrYegTblhmEiCrg2kKQz4XsFIaemE5BF4ybSaQ==", "dev": true, "requires": { "get-func-name": "^2.0.0" @@ -1957,7 +5943,6 @@ }, "make-dir": { "version": "3.1.0", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", "dev": true, "requires": { "semver": "^6.0.0" @@ -1965,30 +5950,21 @@ }, "merge-stream": { "version": "2.0.0", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, "mime-db": { "version": "1.52.0", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true }, "mime-types": { "version": "2.1.35", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "requires": { "mime-db": "1.52.0" } }, - "mimic-fn": { - "version": "2.1.0", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true - }, "minimatch": { "version": "3.0.8", - "integrity": "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q==", "dev": true, "requires": { "brace-expansion": "^1.1.7" @@ -1996,7 +5972,6 @@ }, "mocha": { "version": "9.2.2", - "integrity": "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g==", "dev": true, "requires": { "@ungap/promise-all-settled": "1.1.2", @@ -2025,9 +6000,29 @@ "yargs-unparser": "2.0.0" }, "dependencies": { + "glob": { + "version": "7.2.0", + "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" + }, + "dependencies": { + "minimatch": { + "version": "3.1.2", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + } + } + }, "minimatch": { "version": "4.2.1", - "integrity": "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g==", "dev": true, "requires": { "brace-expansion": "^1.1.7" @@ -2035,14 +6030,12 @@ }, "strip-json-comments": { "version": "3.1.1", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true } } }, "mocha-jsdom": { "version": "2.0.0", - "integrity": "sha512-+3D++FPXHXEesbBD7Q/r4dkc3XzVFMPLJVIECaQ685dj9qKQYzliqX8IXyIUbUL4x1QfgD9h8Zao8cn03NKKEA==", "dev": true, "requires": { "jsdom": "^11.11.0" @@ -2050,22 +6043,18 @@ }, "ms": { "version": "2.1.3", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true }, "nanoid": { "version": "3.3.1", - "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==", "dev": true }, "neo-async": { "version": "2.6.2", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, "nise": { "version": "4.1.0", - "integrity": "sha512-eQMEmGN/8arp0xsvGoQ+B1qvSkR73B1nWSCh7nOt5neMCtwcQVYQGdzQMhcNscktTsWB54xnlSQFzOAPJD8nXA==", "dev": true, "requires": { "@sinonjs/commons": "^1.7.0", @@ -2077,38 +6066,25 @@ }, "node-preload": { "version": "0.2.1", - "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", "dev": true, "requires": { "process-on-spawn": "^1.0.0" } }, "node-releases": { - "version": "2.0.3", - "integrity": "sha512-maHFz6OLqYxz+VQyCAtA3PTX4UP/53pa05fyDNc9CwjvJ0yEh6+xBwKsgCxMNhS8taUKBFYxfuiaD9U/55iFaw==", + "version": "2.0.6", "dev": true }, "normalize-path": { "version": "3.0.0", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "dev": true }, - "npm-run-path": { - "version": "4.0.1", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "requires": { - "path-key": "^3.0.0" - } - }, "nwsapi": { - "version": "2.2.0", - "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", + "version": "2.2.1", "dev": true }, "nyc": { "version": "15.1.0", - "integrity": "sha512-jMW04n9SxKdKi1ZMGhvUTHBN0EICCRkHemEoE5jm6mTYcqcdas0ATzgUgejlQUHMvpnOZqGB5Xxsv9KxJW1j8A==", "dev": true, "requires": { "@istanbuljs/load-nyc-config": "^1.0.0", @@ -2140,14 +6116,8 @@ "yargs": "^15.0.2" }, "dependencies": { - "camelcase": { - "version": "5.3.1", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, "cliui": { "version": "6.0.0", - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, "requires": { "string-width": "^4.2.0", @@ -2155,14 +6125,8 @@ "wrap-ansi": "^6.2.0" } }, - "decamelize": { - "version": "1.2.0", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - }, "find-up": { "version": "4.1.0", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { "locate-path": "^5.0.0", @@ -2171,7 +6135,6 @@ }, "locate-path": { "version": "5.0.0", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { "p-locate": "^4.1.0" @@ -2179,7 +6142,6 @@ }, "p-limit": { "version": "2.3.0", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { "p-try": "^2.0.0" @@ -2187,7 +6149,6 @@ }, "p-locate": { "version": "4.1.0", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { "p-limit": "^2.2.0" @@ -2195,7 +6156,6 @@ }, "wrap-ansi": { "version": "6.2.0", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { "ansi-styles": "^4.0.0", @@ -2205,12 +6165,10 @@ }, "y18n": { "version": "4.0.3", - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yargs": { "version": "15.4.1", - "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { "cliui": "^6.0.0", @@ -2228,7 +6186,6 @@ }, "yargs-parser": { "version": "18.1.3", - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "requires": { "camelcase": "^5.0.0", @@ -2239,28 +6196,17 @@ }, "oauth-sign": { "version": "0.9.0", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", "dev": true }, "once": { "version": "1.4.0", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "requires": { "wrappy": "1" } }, - "onetime": { - "version": "5.1.2", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "requires": { - "mimic-fn": "^2.1.0" - } - }, "optionator": { "version": "0.8.3", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", "dev": true, "requires": { "deep-is": "~0.1.3", @@ -2273,7 +6219,6 @@ }, "p-limit": { "version": "3.1.0", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "requires": { "yocto-queue": "^0.1.0" @@ -2281,7 +6226,6 @@ }, "p-locate": { "version": "5.0.0", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, "requires": { "p-limit": "^3.0.2" @@ -2289,7 +6233,6 @@ }, "p-map": { "version": "3.0.0", - "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", "dev": true, "requires": { "aggregate-error": "^3.0.0" @@ -2297,12 +6240,10 @@ }, "p-try": { "version": "2.2.0", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, "package-hash": { "version": "4.0.0", - "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", "dev": true, "requires": { "graceful-fs": "^4.1.15", @@ -2313,32 +6254,26 @@ }, "parse5": { "version": "4.0.0", - "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", "dev": true }, "path-exists": { "version": "4.0.0", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "path-is-absolute": { "version": "1.0.1", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "dev": true }, "path-key": { "version": "3.1.1", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true }, "path-parse": { "version": "1.0.7", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, "path-to-regexp": { "version": "1.8.0", - "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", "dev": true, "requires": { "isarray": "0.0.1" @@ -2346,27 +6281,22 @@ }, "pathval": { "version": "1.1.1", - "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", "dev": true }, "performance-now": { "version": "2.1.0", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", "dev": true }, "picocolors": { "version": "1.0.0", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", "dev": true }, "picomatch": { "version": "2.3.1", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true }, "pkg-dir": { "version": "4.2.0", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, "requires": { "find-up": "^4.0.0" @@ -2374,7 +6304,6 @@ "dependencies": { "find-up": { "version": "4.1.0", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { "locate-path": "^5.0.0", @@ -2383,7 +6312,6 @@ }, "locate-path": { "version": "5.0.0", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { "p-locate": "^4.1.0" @@ -2391,7 +6319,6 @@ }, "p-limit": { "version": "2.3.0", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { "p-try": "^2.0.0" @@ -2399,7 +6326,6 @@ }, "p-locate": { "version": "4.1.0", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { "p-limit": "^2.2.0" @@ -2409,30 +6335,25 @@ }, "pn": { "version": "1.1.0", - "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", "dev": true }, "prelude-ls": { "version": "1.1.2", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", "dev": true }, "process-on-spawn": { "version": "1.0.0", - "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", "dev": true, "requires": { "fromentries": "^1.2.0" } }, "psl": { - "version": "1.8.0", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "version": "1.9.0", "dev": true }, "pump": { "version": "3.0.0", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "dev": true, "requires": { "end-of-stream": "^1.1.0", @@ -2441,17 +6362,14 @@ }, "punycode": { "version": "2.1.1", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, "qs": { "version": "6.5.3", - "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", "dev": true }, "randombytes": { "version": "2.1.0", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", "dev": true, "requires": { "safe-buffer": "^5.1.0" @@ -2459,7 +6377,6 @@ }, "readable-stream": { "version": "1.1.14", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", "dev": true, "requires": { "core-util-is": "~1.0.0", @@ -2470,7 +6387,6 @@ }, "readdirp": { "version": "3.6.0", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, "requires": { "picomatch": "^2.2.1" @@ -2478,7 +6394,6 @@ }, "rechoir": { "version": "0.7.1", - "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", "dev": true, "requires": { "resolve": "^1.9.0" @@ -2486,7 +6401,6 @@ }, "release-zalgo": { "version": "1.0.0", - "integrity": "sha1-CXALflB0Mpc5Mw5TXFqQ+2eFFzA=", "dev": true, "requires": { "es6-error": "^4.0.1" @@ -2494,7 +6408,6 @@ }, "request": { "version": "2.88.2", - "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", "dev": true, "requires": { "aws-sign2": "~0.7.0", @@ -2517,11 +6430,16 @@ "tough-cookie": "~2.5.0", "tunnel-agent": "^0.6.0", "uuid": "^3.3.2" + }, + "dependencies": { + "uuid": { + "version": "3.4.0", + "dev": true + } } }, "request-promise-core": { "version": "1.1.4", - "integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==", "dev": true, "requires": { "lodash": "^4.17.19" @@ -2529,7 +6447,6 @@ }, "request-promise-native": { "version": "1.0.9", - "integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==", "dev": true, "requires": { "request-promise-core": "1.1.4", @@ -2539,27 +6456,23 @@ }, "require-directory": { "version": "2.1.1", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, "require-main-filename": { "version": "2.0.0", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "resolve": { - "version": "1.22.0", - "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", + "version": "1.22.1", "dev": true, "requires": { - "is-core-module": "^2.8.1", + "is-core-module": "^2.9.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" } }, "resolve-cwd": { "version": "3.0.0", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", "dev": true, "requires": { "resolve-from": "^5.0.0" @@ -2567,35 +6480,29 @@ }, "resolve-from": { "version": "5.0.0", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true }, "rimraf": { "version": "3.0.2", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { "glob": "^7.1.3" } }, "safe-buffer": { - "version": "5.2.1", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "version": "5.1.2", "dev": true }, "safer-buffer": { "version": "2.1.2", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, "sax": { "version": "1.2.4", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", "dev": true }, "schema-utils": { "version": "3.1.1", - "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", "dev": true, "requires": { "@types/json-schema": "^7.0.8", @@ -2605,12 +6512,10 @@ }, "semver": { "version": "6.3.0", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true }, "serialize-javascript": { "version": "6.0.0", - "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", "dev": true, "requires": { "randombytes": "^2.1.0" @@ -2618,12 +6523,10 @@ }, "set-blocking": { "version": "2.0.0", - "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, "shallow-clone": { "version": "3.0.1", - "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", "dev": true, "requires": { "kind-of": "^6.0.2" @@ -2631,7 +6534,6 @@ }, "shebang-command": { "version": "2.0.0", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "requires": { "shebang-regex": "^3.0.0" @@ -2639,17 +6541,14 @@ }, "shebang-regex": { "version": "3.0.0", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, "signal-exit": { "version": "3.0.7", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, "sinon": { "version": "9.2.4", - "integrity": "sha512-zljcULZQsJxVra28qIAL6ow1Z9tpattkCTEJR4RBP3TGc00FcttsP5pK284Nas5WjMZU5Yzy3kAIp3B3KRf5Yg==", "dev": true, "requires": { "@sinonjs/commons": "^1.8.1", @@ -2662,12 +6561,10 @@ "dependencies": { "diff": { "version": "4.0.2", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", "dev": true }, "supports-color": { "version": "7.2.0", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -2677,12 +6574,10 @@ }, "source-map": { "version": "0.6.1", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, "source-map-support": { "version": "0.5.21", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, "requires": { "buffer-from": "^1.0.0", @@ -2691,7 +6586,6 @@ }, "spawn-wrap": { "version": "2.0.0", - "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", "dev": true, "requires": { "foreground-child": "^2.0.0", @@ -2704,12 +6598,10 @@ }, "sprintf-js": { "version": "1.0.3", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, "sshpk": { "version": "1.17.0", - "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", "dev": true, "requires": { "asn1": "~0.2.3", @@ -2725,12 +6617,14 @@ }, "stealthy-require": { "version": "1.1.1", - "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", + "dev": true + }, + "string_decoder": { + "version": "0.10.31", "dev": true }, "string-width": { "version": "4.2.3", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { "emoji-regex": "^8.0.0", @@ -2738,14 +6632,8 @@ "strip-ansi": "^6.0.1" } }, - "string_decoder": { - "version": "0.10.31", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - }, "strip-ansi": { "version": "6.0.1", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { "ansi-regex": "^5.0.1" @@ -2753,22 +6641,14 @@ }, "strip-bom": { "version": "4.0.0", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true - }, - "strip-final-newline": { - "version": "2.0.0", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", "dev": true }, "strip-json-comments": { "version": "1.0.4", - "integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E=", "dev": true }, "supports-color": { "version": "8.1.1", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -2776,57 +6656,45 @@ }, "supports-preserve-symlinks-flag": { "version": "1.0.0", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "dev": true }, "symbol-tree": { "version": "3.2.4", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, "tapable": { "version": "2.2.1", - "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", "dev": true }, "terser": { - "version": "5.12.1", - "integrity": "sha512-NXbs+7nisos5E+yXwAD+y7zrcTkMqb0dEJxIGtSKPdCBzopf7ni4odPul2aechpV7EXNvOudYOX2bb5tln1jbQ==", + "version": "5.14.2", "dev": true, "requires": { + "@jridgewell/source-map": "^0.3.2", "acorn": "^8.5.0", "commander": "^2.20.0", - "source-map": "~0.7.2", "source-map-support": "~0.5.20" }, "dependencies": { "acorn": { - "version": "8.7.0", - "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", - "dev": true - }, - "source-map": { - "version": "0.7.3", - "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "version": "8.8.0", "dev": true } } }, "terser-webpack-plugin": { - "version": "5.3.1", - "integrity": "sha512-GvlZdT6wPQKbDNW/GDQzZFg/j4vKU96yl2q6mcUkzKOgW4gwf1Z8cZToUCrz31XHlPWH8MVb1r2tFtdDtTGJ7g==", + "version": "5.3.3", "dev": true, "requires": { + "@jridgewell/trace-mapping": "^0.3.7", "jest-worker": "^27.4.5", "schema-utils": "^3.1.1", "serialize-javascript": "^6.0.0", - "source-map": "^0.6.1", "terser": "^5.7.2" } }, "test-exclude": { "version": "6.0.0", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", "dev": true, "requires": { "@istanbuljs/schema": "^0.1.2", @@ -2836,12 +6704,10 @@ }, "to-fast-properties": { "version": "2.0.0", - "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", "dev": true }, "to-regex-range": { "version": "5.0.1", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, "requires": { "is-number": "^7.0.0" @@ -2849,7 +6715,6 @@ }, "tough-cookie": { "version": "2.5.0", - "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", "dev": true, "requires": { "psl": "^1.1.28", @@ -2858,7 +6723,6 @@ }, "tr46": { "version": "1.0.1", - "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", "dev": true, "requires": { "punycode": "^2.1.0" @@ -2866,7 +6730,6 @@ }, "tunnel-agent": { "version": "0.6.0", - "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", "dev": true, "requires": { "safe-buffer": "^5.0.1" @@ -2874,12 +6737,10 @@ }, "tweetnacl": { "version": "0.14.5", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", "dev": true }, "type-check": { "version": "0.3.2", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", "dev": true, "requires": { "prelude-ls": "~1.1.2" @@ -2887,43 +6748,44 @@ }, "type-detect": { "version": "4.0.8", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true }, "type-fest": { "version": "0.8.1", - "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true }, "typedarray-to-buffer": { "version": "3.1.5", - "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", "dev": true, "requires": { "is-typedarray": "^1.0.0" } }, "typescript": { - "version": "4.6.3", - "integrity": "sha512-yNIatDa5iaofVozS/uQJEl3JRWLKKGJKh6Yaiv0GLGSuhpFJe7P3SbHZ8/yjAHRQwKRoA6YZqlfjXWmVzoVSMw==", + "version": "4.7.4", "dev": true }, + "update-browserslist-db": { + "version": "1.0.5", + "dev": true, + "requires": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + } + }, "uri-js": { "version": "4.4.1", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, "requires": { "punycode": "^2.1.0" } }, "uuid": { - "version": "3.4.0", - "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "version": "8.3.2", "dev": true }, "verror": { "version": "1.10.0", - "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", "dev": true, "requires": { "assert-plus": "^1.0.0", @@ -2933,22 +6795,19 @@ "dependencies": { "core-util-is": { "version": "1.0.2", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true } } }, "w3c-hr-time": { "version": "1.0.2", - "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", "dev": true, "requires": { "browser-process-hrtime": "^1.0.0" } }, "watchpack": { - "version": "2.3.1", - "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==", + "version": "2.4.0", "dev": true, "requires": { "glob-to-regexp": "^0.4.1", @@ -2957,12 +6816,10 @@ }, "webidl-conversions": { "version": "4.0.2", - "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", "dev": true }, "webpack": { - "version": "5.72.0", - "integrity": "sha512-qmSmbspI0Qo5ld49htys8GY9XhS9CGqFoHTsOVAnjBdg0Zn79y135R+k4IR4rKK6+eKaabMhJwiVB7xw0SJu5w==", + "version": "5.74.0", "dev": true, "requires": { "@types/eslint-scope": "^3.7.3", @@ -2970,46 +6827,49 @@ "@webassemblyjs/ast": "1.11.1", "@webassemblyjs/wasm-edit": "1.11.1", "@webassemblyjs/wasm-parser": "1.11.1", - "acorn": "^8.4.1", + "acorn": "^8.7.1", "acorn-import-assertions": "^1.7.6", "browserslist": "^4.14.5", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.9.2", + "enhanced-resolve": "^5.10.0", "es-module-lexer": "^0.9.0", "eslint-scope": "5.1.1", "events": "^3.2.0", "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.2.9", - "json-parse-better-errors": "^1.0.2", + "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.1.0", "tapable": "^2.1.1", "terser-webpack-plugin": "^5.1.3", - "watchpack": "^2.3.1", + "watchpack": "^2.4.0", "webpack-sources": "^3.2.3" }, "dependencies": { "acorn": { - "version": "8.7.0", - "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", + "version": "8.8.0", "dev": true + }, + "acorn-import-assertions": { + "version": "1.8.0", + "dev": true, + "requires": {} } } }, "webpack-cli": { - "version": "4.9.2", - "integrity": "sha512-m3/AACnBBzK/kMTcxWHcZFPrw/eQuY4Df1TxvIWfWM2x7mRqBQCqKEd96oCUa9jkapLBaFfRce33eGDb4Pr7YQ==", + "version": "4.10.0", "dev": true, "requires": { "@discoveryjs/json-ext": "^0.5.0", - "@webpack-cli/configtest": "^1.1.1", - "@webpack-cli/info": "^1.4.1", - "@webpack-cli/serve": "^1.6.1", + "@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", - "execa": "^5.0.0", + "cross-spawn": "^7.0.3", "fastest-levenshtein": "^1.0.12", "import-local": "^3.0.2", "interpret": "^2.2.0", @@ -3019,14 +6879,12 @@ "dependencies": { "commander": { "version": "7.2.0", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", "dev": true } } }, "webpack-merge": { "version": "5.8.0", - "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==", "dev": true, "requires": { "clone-deep": "^4.0.1", @@ -3035,17 +6893,14 @@ }, "webpack-plugin-replace": { "version": "1.2.0", - "integrity": "sha512-1HA3etHpJW55qonJqv84o5w5GY7iqF8fqSHpTWdNwarj1llkkt4jT4QSvYs1hoaU8Lu5akDnq/spHHO5mXwo1w==", "dev": true }, "webpack-sources": { "version": "3.2.3", - "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", "dev": true }, "whatwg-encoding": { "version": "1.0.5", - "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", "dev": true, "requires": { "iconv-lite": "0.4.24" @@ -3053,12 +6908,10 @@ }, "whatwg-mimetype": { "version": "2.3.0", - "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", "dev": true }, "whatwg-url": { "version": "6.5.0", - "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", "dev": true, "requires": { "lodash.sortby": "^4.7.0", @@ -3068,7 +6921,6 @@ }, "which": { "version": "2.0.2", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "requires": { "isexe": "^2.0.0" @@ -3076,27 +6928,22 @@ }, "which-module": { "version": "2.0.0", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, "wildcard": { "version": "2.0.0", - "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==", "dev": true }, "word-wrap": { "version": "1.2.3", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", "dev": true }, "workerpool": { "version": "6.2.0", - "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==", "dev": true }, "wrap-ansi": { "version": "7.0.0", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "requires": { "ansi-styles": "^4.0.0", @@ -3106,12 +6953,10 @@ }, "wrappy": { "version": "1.0.2", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, "write-file-atomic": { "version": "3.0.3", - "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", "dev": true, "requires": { "imurmurhash": "^0.1.4", @@ -3122,7 +6967,6 @@ }, "ws": { "version": "5.2.3", - "integrity": "sha512-jZArVERrMsKUatIdnLzqvcfydI85dvd/Fp1u/VOpfdDWQ4c9qWXe+VIeAbQ5FrDwciAkr+lzofXLz3Kuf26AOA==", "dev": true, "requires": { "async-limiter": "~1.0.0" @@ -3130,17 +6974,14 @@ }, "xml-name-validator": { "version": "3.0.0", - "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", "dev": true }, "y18n": { "version": "5.0.8", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true }, "yargs": { "version": "16.2.0", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, "requires": { "cliui": "^7.0.2", @@ -3154,23 +6995,30 @@ }, "yargs-parser": { "version": "20.2.4", - "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", "dev": true }, "yargs-unparser": { "version": "2.0.0", - "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", "dev": true, "requires": { "camelcase": "^6.0.0", "decamelize": "^4.0.0", "flat": "^5.0.2", "is-plain-obj": "^2.1.0" + }, + "dependencies": { + "camelcase": { + "version": "6.3.0", + "dev": true + }, + "decamelize": { + "version": "4.0.0", + "dev": true + } } }, "yocto-queue": { "version": "0.1.0", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true } } diff --git a/package.json b/package.json index 8c5b89b4..ebb62ea8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "amazon-connect-streams", - "version": "2.2.0", + "version": "2.3.0", "description": "Amazon Connect Streams Library", "engines": { "node": ">=12.0.0" @@ -49,6 +49,5 @@ "webpack": "^5.64.4", "webpack-cli": "^4.9.1", "webpack-plugin-replace": "^1.2.0" - }, - "dependencies": {} + } } diff --git a/release/connect-streams-min.js b/release/connect-streams-min.js index a0122afa..5c1948d6 100644 --- a/release/connect-streams-min.js +++ b/release/connect-streams-min.js @@ -1 +1 @@ -(()=>{var e={821:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.agentApp={};var n="ccp";t.agentApp.initCCP=t.core.initCCP,t.agentApp.isInitialized=function(e){},t.agentApp.initAppCommunication=function(e,n){var r=document.getElementById(e),o=new t.IFrameConduit(n,window,r),i=[t.AgentEvents.UPDATE,t.ContactEvents.VIEW,t.EventType.ACKNOWLEDGE,t.EventType.TERMINATED,t.TaskEvents.CREATED];r.addEventListener("load",(function(e){i.forEach((function(e){t.core.getUpstream().onUpstream(e,(function(t){o.sendUpstream(e,t)}))}))}))};var r=function(e){var t=e.indexOf("ccp-v2");return e.slice(0,t-1)};t.agentApp.initApp=function(e,o,i,s){s=s||{};var a=i.endsWith("/")?i:i+"/",c=s.onLoad?s.onLoad:null,u={endpoint:a,style:s.style,onLoad:c};t.agentApp.AppRegistry.register(e,u,document.getElementById(o)),t.agentApp.AppRegistry.start(e,(function(o){var i=o.endpoint,a=o.containerDOM;return{init:function(){return e===n?(s.ccpParams=s.ccpParams?s.ccpParams:{},s.style&&(s.ccpParams.style=s.style),function(e,n,o){var i={ccpUrl:e,ccpLoadTimeout:1e4,loginPopup:!0,loginUrl:r(e)+"/login",softphone:{allowFramedSoftphone:!0,disableRingtone:!1}},s=t.merge(i,o.ccpParams);t.core.initCCP(n,s)}(i,a,s)):t.agentApp.initAppCommunication(e,i)},destroy:function(){return e===n?(o=r(i)+"/logout",t.fetch(o,{credentials:"include"}).then((function(){return t.core.getEventBus().trigger(t.EventType.TERMINATE),!0})).catch((function(e){return t.getLog().error("An error occured on logout."+e).withException(e),window.location.href=o,!1}))):null;var o}}}))},t.agentApp.stopApp=function(e){return t.agentApp.AppRegistry.stop(e)}}()},500:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t;var n,r="ccp";e.connect.agentApp.AppRegistry=(n={},{register:function(e,t,r){n[e]={containerDOM:r,endpoint:t.endpoint,style:t.style,instance:void 0,onLoad:t.onLoad}},start:function(e,t){if(n[e]){var o=n[e].containerDOM,i=n[e].endpoint,s=n[e].style,a=n[e].onLoad;if(e!==r){var c=function(e,t,n,r){var o=document.createElement("iframe");return o.src=t,o.style=n||"width: 100%; height:100%;",o.id=e,o["aria-label"]=e,o.onload=r,o.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),o}(e,i,s,a);o.appendChild(c)}return n[e].instance=t(n[e]),n[e].instance.init()}},stop:function(e){if(n[e]){var t,r=n[e],o=r.containerDOM.querySelector("iframe");return r.containerDOM.removeChild(o),r.instance&&(t=r.instance.destroy(),delete r.instance),t}}})}()},965:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.AgentStateType=t.makeEnum(["init","routable","not_routable","offline"]),t.AgentStatusType=t.AgentStateType,t.AgentAvailStates=t.makeEnum(["Init","Busy","AfterCallWork","CallingCustomer","Dialing","Joining","PendingAvailable","PendingBusy"]),t.AgentErrorStates=t.makeEnum(["Error","AgentHungUp","BadAddressAgent","BadAddressCustomer","Default","FailedConnectAgent","FailedConnectCustomer","InvalidLocale","LineEngagedAgent","LineEngagedCustomer","MissedCallAgent","MissedCallCustomer","MultipleCcpWindows","RealtimeCommunicationError"]),t.EndpointType=t.makeEnum(["phone_number","agent","queue"]),t.AddressType=t.EndpointType,t.ConnectionType=t.makeEnum(["agent","inbound","outbound","monitoring"]),t.ConnectionStateType=t.makeEnum(["init","connecting","connected","hold","disconnected"]),t.ConnectionStatusType=t.ConnectionStateType,t.CONNECTION_ACTIVE_STATES=t.set([t.ConnectionStateType.CONNECTING,t.ConnectionStateType.CONNECTED,t.ConnectionStateType.HOLD]),t.ContactStateType=t.makeEnum(["init","incoming","pending","connecting","connected","missed","error","ended"]),t.ContactStatusType=t.ContactStateType,t.CONTACT_ACTIVE_STATES=t.makeEnum(["incoming","pending","connecting","connected"]),t.ContactType=t.makeEnum(["voice","queue_callback","chat","task"]),t.ContactInitiationMethod=t.makeEnum(["inbound","outbound","transfer","queue_transfer","callback","api","disconnect"]),t.ContactRecordingVoiceTrackConfig=t.makeEnum(["ALL","TO_AGENT","FROM_AGENT"]),t.ChannelType=t.makeEnum(["VOICE","CHAT","TASK"]),t.MediaType=t.makeEnum(["softphone","chat","task"]),t.SoftphoneCallType=t.makeEnum(["audio_video","video_only","audio_only","none"]),t.SoftphoneErrorTypes=t.makeEnum(["unsupported_browser","microphone_not_shared","signalling_handshake_failure","signalling_connection_failure","ice_collection_timeout","user_busy_error","webrtc_error","realtime_communication_error","other"]),t.VoiceIdErrorTypes=t.makeEnum(["no_speaker_id_found","speaker_id_not_enrolled","get_speaker_id_failed","get_speaker_status_failed","opt_out_speaker_failed","opt_out_speaker_in_lcms_failed","delete_speaker_failed","start_session_failed","evaluate_speaker_failed","session_not_exists","describe_session_failed","enroll_speaker_failed","update_speaker_id_failed","update_speaker_id_in_lcms_failed","not_supported_on_conference_calls","enroll_speaker_timeout","evaluate_speaker_timeout","get_domain_id_failed","no_domain_id_found"]),t.CTIExceptions=t.makeEnum(["AccessDeniedException","InvalidStateException","BadEndpointException","InvalidAgentARNException","InvalidConfigurationException","InvalidContactTypeException","PaginationException","RefreshTokenExpiredException","SendDataFailedException","UnauthorizedException","QuotaExceededException"]),t.VoiceIdStreamingStatus=t.makeEnum(["ONGOING","ENDED","PENDING_CONFIGURATION"]),t.VoiceIdAuthenticationDecision=t.makeEnum(["ACCEPT","REJECT","NOT_ENOUGH_SPEECH","SPEAKER_NOT_ENROLLED","SPEAKER_OPTED_OUT","SPEAKER_ID_NOT_PROVIDED","SPEAKER_EXPIRED"]),t.VoiceIdFraudDetectionDecision=t.makeEnum(["NOT_ENOUGH_SPEECH","HIGH_RISK","LOW_RISK"]),t.ContactFlowAuthenticationDecision=t.makeEnum(["Authenticated","NotAuthenticated","Inconclusive","NotEnrolled","OptedOut","NotEnabled","Error"]),t.ContactFlowFraudDetectionDecision=t.makeEnum(["HighRisk","LowRisk","Inconclusive","NotEnabled","Error"]),t.VoiceIdEnrollmentRequestStatus=t.makeEnum(["NOT_ENOUGH_SPEECH","IN_PROGRESS","COMPLETED","FAILED"]),t.VoiceIdSpeakerStatus=t.makeEnum(["OPTED_OUT","ENROLLED","PENDING"]),t.VoiceIdConstants={EVALUATE_SESSION_DELAY:1e4,EVALUATION_MAX_POLL_TIMES:24,EVALUATION_POLLING_INTERVAL:5e3,ENROLLMENT_MAX_POLL_TIMES:120,ENROLLMENT_POLLING_INTERVAL:5e3,START_SESSION_DELAY:8e3},t.AgentPermissions={OUTBOUND_CALL:"outboundCall",VOICE_ID:"voiceId",CONTACT_RECORDING:"contactRecording"};var n=function(){if(!t.agent.initialized)throw new t.StateError("The agent is not yet initialized!")};n.prototype._getData=function(){return t.core.getAgentDataProvider().getAgentData()},n.prototype._createContactAPI=function(e){return new t.Contact(e.contactId)},n.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(t.AgentEvents.REFRESH,e)},n.prototype.onRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ROUTABLE,e)},n.prototype.onNotRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.NOT_ROUTABLE,e)},n.prototype.onOffline=function(e){t.core.getEventBus().subscribe(t.AgentEvents.OFFLINE,e)},n.prototype.onError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ERROR,e)},n.prototype.onSoftphoneError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.SOFTPHONE_ERROR,e)},n.prototype.onWebSocketConnectionLost=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e)},n.prototype.onWebSocketConnectionGained=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED,e)},n.prototype.onAfterCallWork=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ACW,e)},n.prototype.onStateChange=function(e){t.core.getEventBus().subscribe(t.AgentEvents.STATE_CHANGE,e)},n.prototype.onMuteToggle=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.MUTE_TOGGLE,e)},n.prototype.onLocalMediaStreamCreated=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,e)},n.prototype.onSpeakerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,e)},n.prototype.onMicrophoneDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,e)},n.prototype.onRingerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.RINGER_DEVICE_CHANGED,e)},n.prototype.mute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!0}})},n.prototype.unmute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!1}})},n.prototype.setSpeakerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_SPEAKER_DEVICE,data:{deviceId:e}})},n.prototype.setMicrophoneDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_MICROPHONE_DEVICE,data:{deviceId:e}})},n.prototype.setRingerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_RINGER_DEVICE,data:{deviceId:e}})},n.prototype.getState=function(){return this._getData().snapshot.state},n.prototype.getNextState=function(){return this._getData().snapshot.nextState},n.prototype.getAvailabilityState=function(){return this._getData().snapshot.agentAvailabilityState},n.prototype.getStatus=n.prototype.getState,n.prototype.getStateDuration=function(){return t.now()-this._getData().snapshot.state.startTimestamp.getTime()+t.core.getSkew()},n.prototype.getStatusDuration=n.prototype.getStateDuration,n.prototype.getPermissions=function(){return this.getConfiguration().permissions},n.prototype.getContacts=function(e){var t=this;return this._getData().snapshot.contacts.map((function(e){return t._createContactAPI(e)})).filter((function(t){return!e||t.getType()===e}))},n.prototype.getConfiguration=function(){return this._getData().configuration},n.prototype.getAgentStates=function(){return this.getConfiguration().agentStates},n.prototype.getRoutingProfile=function(){return this.getConfiguration().routingProfile},n.prototype.getChannelConcurrency=function(e){var n=this.getRoutingProfile().channelConcurrencyMap;return n||(n=Object.keys(t.ChannelType).reduce((function(e,n){return"TASK"!==n&&(e[t.ChannelType[n]]=1),e}),{})),e?n[e]||0:n},n.prototype.getName=function(){return this.getConfiguration().name},n.prototype.getExtension=function(){return this.getConfiguration().extension},n.prototype.getDialableCountries=function(){return this.getConfiguration().dialableCountries},n.prototype.isSoftphoneEnabled=function(){return this.getConfiguration().softphoneEnabled},n.prototype.setConfiguration=function(e,n){var r=t.core.getClient();e&&e.agentPreferences&&e.agentPreferences.LANGUAGE&&!e.agentPreferences.locale&&(e.agentPreferences.locale=e.agentPreferences.LANGUAGE),e&&e.agentPreferences&&!t.isValidLocale(e.agentPreferences.locale)?n&&n.failure&&n.failure(t.AgentErrorStates.INVALID_LOCALE):r.call(t.ClientMethods.UPDATE_AGENT_CONFIGURATION,{configuration:t.assertNotNull(e,"configuration")},{success:function(e){t.core.getUpstream().sendUpstream(t.EventType.RELOAD_AGENT_CONFIGURATION),n.success&&n.success(e)},failure:n&&n.failure})},n.prototype.setState=function(e,n,r){t.core.getClient().call(t.ClientMethods.PUT_AGENT_STATE,{state:t.assertNotNull(e,"state"),enqueueNextState:r&&!!r.enqueueNextState},n)},n.prototype.onEnqueuedNextState=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ENQUEUED_NEXT_STATE,e)},n.prototype.setStatus=n.prototype.setState,n.prototype.connect=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_OUTBOUND_CONTACT,{endpoint:t.assertNotNull(o,"endpoint"),queueARN:n&&(n.queueARN||n.queueId)||this.getRoutingProfile().defaultOutboundQueue.queueARN},n&&{success:n.success,failure:n.failure})},n.prototype.getAllQueueARNs=function(){return this.getConfiguration().routingProfile.queues.map((function(e){return e.queueARN}))},n.prototype.getEndpoints=function(e,n,r){var o=this,i=t.core.getClient();t.assertNotNull(n,"callbacks"),t.assertNotNull(n.success,"callbacks.success");var s=r||{};s.endpoints=s.endpoints||[],s.maxResults=s.maxResults||t.DEFAULT_BATCH_SIZE,t.isArray(e)||(e=[e]),i.call(t.ClientMethods.GET_ENDPOINTS,{queueARNs:e,nextToken:s.nextToken||null,maxResults:s.maxResults},{success:function(r){if(r.nextToken)o.getEndpoints(e,n,{nextToken:r.nextToken,maxResults:s.maxResults,endpoints:s.endpoints.concat(r.endpoints)});else{s.endpoints=s.endpoints.concat(r.endpoints);var i=s.endpoints.map((function(e){return new t.Endpoint(e)}));n.success({endpoints:i,addresses:i})}},failure:n.failure})},n.prototype.getAddresses=n.prototype.getEndpoints,n.prototype._getResourceId=function(){var e=this.getAllQueueARNs();for(let t of e){const e=t.match(/\/agent\/([^/]+)/);if(e)return e[1]}return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ",e)},n.prototype.toSnapshot=function(){return new t.AgentSnapshot(this._getData())};var r=function(e){t.Agent.call(this),this.agentData=e};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._getData=function(){return this.agentData},r.prototype._createContactAPI=function(e){return new t.ContactSnapshot(e)};var o=function(e){this.contactId=e};o.prototype._getData=function(){return t.core.getAgentDataProvider().getContactData(this.getContactId())},o.prototype._createConnectionAPI=function(e){return this.getType()===t.ContactType.CHAT?new t.ChatConnection(this.contactId,e.connectionId):this.getType()===t.ContactType.TASK?new t.TaskConnection(this.contactId,e.connectionId):new t.VoiceConnection(this.contactId,e.connectionId)},o.prototype.getEventName=function(e){return t.core.getContactEventName(e,this.getContactId())},o.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.REFRESH),e)},o.prototype.onIncoming=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.INCOMING),e)},o.prototype.onConnecting=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTING),e)},o.prototype.onPending=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.PENDING),e)},o.prototype.onAccepted=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACCEPTED),e)},o.prototype.onMissed=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.MISSED),e)},o.prototype.onEnded=function(e){var n=t.core.getEventBus();n.subscribe(this.getEventName(t.ContactEvents.ENDED),e),n.subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onDestroy=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onACW=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACW),e)},o.prototype.onConnected=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTED),e)},o.prototype.onError=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ERROR),e)},o.prototype.getContactId=function(){return this.contactId},o.prototype.getOriginalContactId=function(){return this._getData().initialContactId},o.prototype.getInitialContactId=o.prototype.getOriginalContactId,o.prototype.getType=function(){return this._getData().type},o.prototype.getContactDuration=function(){return this._getData().contactDuration},o.prototype.getState=function(){return this._getData().state},o.prototype.getStatus=o.prototype.getState,o.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},o.prototype.getStatusDuration=o.prototype.getStateDuration,o.prototype.getQueue=function(){return this._getData().queue},o.prototype.getQueueTimestamp=function(){return this._getData().queueTimestamp},o.prototype.getConnections=function(){var e=this;return this._getData().connections.map((function(n){return e.getType()===t.ContactType.CHAT?new t.ChatConnection(e.contactId,n.connectionId):e.getType()===t.ContactType.TASK?new t.TaskConnection(e.contactId,n.connectionId):new t.VoiceConnection(e.contactId,n.connectionId)}))},o.prototype.getInitialConnection=function(){return t.find(this.getConnections(),(function(e){return e.isInitialConnection()}))||null},o.prototype.getActiveInitialConnection=function(){var e=this.getInitialConnection();return null!=e&&e.isActive()?e:null},o.prototype.getThirdPartyConnections=function(){return this.getConnections().filter((function(e){return!e.isInitialConnection()&&e.getType()!==t.ConnectionType.AGENT}))},o.prototype.getSingleActiveThirdPartyConnection=function(){return this.getThirdPartyConnections().filter((function(e){return e.isActive()}))[0]||null},o.prototype.getAgentConnection=function(){return t.find(this.getConnections(),(function(e){var n=e.getType();return n===t.ConnectionType.AGENT||n===t.ConnectionType.MONITORING}))},o.prototype.getName=function(){return this._getData().name},o.prototype.getContactMetadata=function(){return this._getData().contactMetadata},o.prototype.getDescription=function(){return this._getData().description},o.prototype.getReferences=function(){return this._getData().references},o.prototype.getAttributes=function(){return this._getData().attributes},o.prototype.getContactFeatures=function(){return this._getData().contactFeatures},o.prototype.getChannelContext=function(){return this._getData().channelContext},o.prototype.isSoftphoneCall=function(){return null!=t.find(this.getConnections(),(function(e){return null!=e.getSoftphoneMediaInfo()}))},o.prototype._isInbound=function(){return this._getData().initiationMethod!==t.ContactInitiationMethod.OUTBOUND},o.prototype.isInbound=function(){var e=this.getInitialConnection();return e.getMediaType()===t.MediaType.TASK?this._isInbound():!!e&&e.getType()===t.ConnectionType.INBOUND},o.prototype.isConnected=function(){return this.getStatus().type===t.ContactStateType.CONNECTED},o.prototype.accept=function(e){var n=t.core.getClient(),r=this,o=this.getContactId();n.call(t.ClientMethods.ACCEPT_CONTACT,{contactId:o},{success:function(n){var i=t.core.getUpstream();i.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(o)}),i.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,r.getContactId()),data:new t.Contact(o)});var s=new t.Contact(o);t.isFirefoxBrowser()&&s.isSoftphoneCall()&&t.core.triggerReadyToStartSessionEvent(),e&&e.success&&e.success(n)},failure:e?e.failure:null})},o.prototype.destroy=function(){t.getLog().warn("contact.destroy() has been deprecated.")},o.prototype.reject=function(e){t.core.getClient().call(t.ClientMethods.REJECT_CONTACT,{contactId:this.getContactId()},e)},o.prototype.complete=function(e){t.core.getClient().call(t.ClientMethods.COMPLETE_CONTACT,{contactId:this.getContactId()},e)},o.prototype.clear=function(e){t.core.getClient().call(t.ClientMethods.CLEAR_CONTACT,{contactId:this.getContactId()},e)},o.prototype.notifyIssue=function(e,n,r){t.core.getClient().call(t.ClientMethods.NOTIFY_CONTACT_ISSUE,{contactId:this.getContactId(),issueCode:e,description:n},r)},o.prototype.addConnection=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_ADDITIONAL_CONNECTION,{contactId:this.getContactId(),endpoint:o},n)},o.prototype.toggleActiveConnections=function(e){var n=t.core.getClient(),r=null,o=t.find(this.getConnections(),(function(e){return e.getStatus().type===t.ConnectionStateType.HOLD}));if(null!=o)r=o.getConnectionId();else{var i=this.getConnections().filter((function(e){return e.isActive()}));i.length>0&&(r=i[0].getConnectionId())}n.call(t.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:r},e)},o.prototype.sendSoftphoneMetrics=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,softphoneStreamStatistics:n},r),t.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:e.ccpVersion,stats:n})},o.prototype.sendSoftphoneReport=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n},r),t.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n})},o.prototype.conferenceConnections=function(e){t.core.getClient().call(t.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},o.prototype.toSnapshot=function(){return new t.ContactSnapshot(this._getData())},o.prototype.isMultiPartyConferenceEnabled=function(){var e=this.getContactFeatures();return!(!e||!e.multiPartyConferenceEnabled)};var i=function(e){t.Contact.call(this,e.contactId),this.contactData=e};(i.prototype=Object.create(o.prototype)).constructor=i,i.prototype._getData=function(){return this.contactData},i.prototype._createConnectionAPI=function(e){return new t.ConnectionSnapshot(e)};var s=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};s.prototype._getData=function(){return t.core.getAgentDataProvider().getConnectionData(this.getContactId(),this.getConnectionId())},s.prototype.getContactId=function(){return this.contactId},s.prototype.getConnectionId=function(){return this.connectionId},s.prototype.getEndpoint=function(){return new t.Endpoint(this._getData().endpoint)},s.prototype.getAddress=s.prototype.getEndpoint,s.prototype.getState=function(){return this._getData().state},s.prototype.getStatus=s.prototype.getState,s.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},s.prototype.getStatusDuration=s.prototype.getStateDuration,s.prototype.getType=function(){return this._getData().type},s.prototype.isInitialConnection=function(){return this._getData().initial},s.prototype.isActive=function(){return t.contains(t.CONNECTION_ACTIVE_STATES,this.getStatus().type)},s.prototype.isConnected=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTED},s.prototype.isConnecting=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTING},s.prototype.isOnHold=function(){return this.getStatus().type===t.ConnectionStateType.HOLD},s.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},s.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},s.prototype.destroy=function(e){t.core.getClient().call(t.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.sendDigits=function(e,n){t.core.getClient().call(t.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},n)},s.prototype.hold=function(e){t.core.getClient().call(t.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.resume=function(e){t.core.getClient().call(t.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.toSnapshot=function(){return new t.ConnectionSnapshot(this._getData())},s.prototype._initMediaController=function(){this.getMediaInfo()&&t.core.mediaFactory.get(this).catch((function(){}))},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING};var a=function(e){this.contactId=t.core.getAgentDataProvider().getContactData(e)?e:null};a.prototype.startContactRecording=function(e){var n,r,o=this;n=t.core.getClient(),r=t.core.getAgentDataProvider().getContactData(o.contactId);var i=e&&Object.values(t.ContactRecordingVoiceTrackConfig).includes(e)?e:t.ContactRecordingVoiceTrackConfig.ALL;return new Promise((function(e,s){n.call(t.AgentAppClientMethods.START_CONTACT_RECORDING,{initialContactId:r.initialContactId||o.contactId,contactId:o.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),voiceRecordingConfiguration:{voiceRecordingTrack:i}},{success:function(n){t.getLog().info("startContactRecording succeeded").withObject(n).sendInternalLogToServer(),e(n)},failure:function(e,n){t.getLog().error("startContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),s(Error("startContactRecording failed",{cause:e}))}})}))},a.prototype.stopContactRecording=function(){var e,n,r=this;return e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(r.contactId),new Promise((function(o,i){e.call(t.AgentAppClientMethods.STOP_CONTACT_RECORDING,{initialContactId:n.initialContactId||r.contactId,contactId:r.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId()},{success:function(e){t.getLog().info("stopContactRecording succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e,n){t.getLog().error("stopContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),i(Error("stopContactRecording failed",{cause:e}))}})}))},a.prototype.suspendContactRecording=function(){var e,n,r=this;return e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(r.contactId),new Promise((function(o,i){e.call(t.AgentAppClientMethods.SUSPEND_CONTACT_RECORDING,{initialContactId:n.initialContactId||r.contactId,contactId:r.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId()},{success:function(e){t.getLog().info("suspendContactRecording succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e,n){t.getLog().error("suspendContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),i(Error("suspendContactRecording failed",{cause:e}))}})}))},a.prototype.resumeContactRecording=function(){var e,n,r=this;return e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(r.contactId),new Promise((function(o,i){e.call(t.AgentAppClientMethods.RESUME_CONTACT_RECORDING,{initialContactId:n.initialContactId||r.contactId,contactId:r.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId()},{success:function(e){t.getLog().info("resumeContactRecording succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e,n){t.getLog().error("resumeContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),i(Error("resumeContactRecording failed"),{cause:e})}})}))};var c=function(e){this.contactId=e};c.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){n.call(t.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),awsAccountId:t.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){if(e.contactData.customerId){var n={speakerId:e.contactData.customerId};t.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),r(n)}else{var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call");o(i)}},failure:function(e){t.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(n)}})}))},c.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){var n=JSON.parse(e);switch(n.status){case 400:case 404:var i=n;i.type=i.type?i.type:t.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,t.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),r(i);break;default:t.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();var s=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);o(s)}}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype._optOutSpeakerInLcms=function(e){var n=this,r=t.core.getClient();return new Promise((function(o,i){r.call(t.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:n.contactId,InstanceId:t.core.getAgentDataProvider().getInstanceId(),AWSAccountId:t.core.getAgentDataProvider().getAWSAccountId(),CustomerId:t.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0}},{success:function(e){t.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){t.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);i(n)}})}))},c.prototype.optOutSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(s){var a=i.speakerId;n.call(t.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:t.assertNotNull(a,"speakerId"),DomainId:s},{success:function(n){e._optOutSpeakerInLcms(a).catch((function(){})),t.getLog().info("optOutSpeaker succeeded").withObject(n).sendInternalLogToServer(),r(n)},failure:function(e){t.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){t.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.startSession=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getDomainId().then((function(i){n.call(t.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),customerAccountId:t.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:i},{success:function(e){if(e.sessionId)r(e);else{t.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api");o(n)}},failure:function(e){t.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);o(n)}})})).catch((function(e){o(e)}))}))},c.prototype.evaluateSpeaker=function(e){var n=this;n.checkConferenceCall();var r=t.core.getClient(),o=t.core.getAgentDataProvider().getContactData(this.contactId),i=0;return new Promise((function(s,a){function c(){n.getDomainId().then((function(e){r.call(t.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:o.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++i=1&&(o=r.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i,"")),!o){t.getLog().info("getDomainId: no domainId found").sendInternalLogToServer();var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND);return void n(i)}t.getLog().info("getDomainId succeeded").withObject(r).sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.VoiceIdEvents.UPDATE_DOMAIN_ID,data:{domainId:o}}),e(o)}catch(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer(),i=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e),n(i)}},failure:function(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer();var r=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e);n(r)}}):n(new Error("Agent doesn't have the permission for Voice ID"))}))},c.prototype.checkConferenceCall=function(){if(t.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return t.contains(t.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new t.NotImplementedError("VoiceId is not supported for conference calls")},c.prototype.isAuthEnabled=function(e){return e!==t.ContactFlowAuthenticationDecision.NOT_ENABLED},c.prototype.isAuthResultNotEnoughSpeech=function(e){return e===t.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH},c.prototype.isAuthResultInconclusive=function(e){return e===t.ContactFlowAuthenticationDecision.INCONCLUSIVE},c.prototype.isFraudEnabled=function(e){return e!==t.ContactFlowFraudDetectionDecision.NOT_ENABLED},c.prototype.isFraudResultNotEnoughSpeech=function(e){return e===t.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH},c.prototype.isFraudResultInconclusive=function(e){return e===t.ContactFlowFraudDetectionDecision.INCONCLUSIVE};var u=function(e,t){this._speakerAuthenticator=new c(e),this._contactRecorder=new a(e),s.call(this,e,t)};(u.prototype=Object.create(s.prototype)).constructor=u,u.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},u.prototype.getMediaInfo=function(){return this._getData().softphoneMediaInfo},u.prototype.getMediaType=function(){return t.MediaType.SOFTPHONE},u.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},u.prototype.getVoiceIdSpeakerId=function(){return this._speakerAuthenticator.getSpeakerId()},u.prototype.getVoiceIdSpeakerStatus=function(){return this._speakerAuthenticator.getSpeakerStatus()},u.prototype.optOutVoiceIdSpeaker=function(){return this._speakerAuthenticator.optOutSpeaker()},u.prototype.deleteVoiceIdSpeaker=function(){return this._speakerAuthenticator.deleteSpeaker()},u.prototype.evaluateSpeakerWithVoiceId=function(e){return this._speakerAuthenticator.evaluateSpeaker(e)},u.prototype.enrollSpeakerInVoiceId=function(e){return this._speakerAuthenticator.enrollSpeaker(e)},u.prototype.updateVoiceIdSpeakerId=function(e){return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e)},u.prototype.getQuickConnectName=function(){return this._getData().quickConnectName},u.prototype.isMute=function(){return this._getData().mute},u.prototype.muteParticipant=function(e){t.core.getClient().call(t.ClientMethods.MUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},u.prototype.unmuteParticipant=function(e){t.core.getClient().call(t.ClientMethods.UNMUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},u.prototype.startContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.startContactRecording()},u.prototype.stopContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.stopContactRecording()},u.prototype.suspendContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.suspendContactRecording()},u.prototype.resumeContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.resumeContactRecording()},u.prototype.checkConferenceCall=function(){if(t.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return t.contains(t.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new t.NotImplementedError("VoiceId and Contact Recording are not supported for conference calls")};var l=function(e,t){s.call(this,e,t)};(l.prototype=Object.create(s.prototype)).constructor=l,l.prototype.getMediaInfo=function(){var e=this._getData().chatMediaInfo;if(e){var n=t.core.getAgentDataProvider().getContactData(this.contactId),r={contactId:this.contactId,initialContactId:n.initialContactId||this.contactId,participantId:this.connectionId,getConnectionToken:t.hitch(this,this.getConnectionToken)};if(e.connectionData)try{r.participantToken=JSON.parse(e.connectionData).ConnectionAuthenticationToken}catch(n){t.getLog().error(t.LogComponent.CHAT,"Connection data is invalid").withObject(e).withException(n).sendInternalLogToServer(),r.participantToken=null}return r.participantToken=r.participantToken||null,r.originalInfo=this._getData().chatMediaInfo,r}return null},l.prototype.getConnectionToken=function(){var e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(this.contactId),r={transportType:t.TRANSPORT_TYPES.CHAT_TOKEN,participantId:this.connectionId,contactId:n.initialContactId||this.contactId};return new Promise((function(n,o){e.call(t.ClientMethods.CREATE_TRANSPORT,r,{success:function(e){t.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(),n(e)},failure:function(e,n){t.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({err:e,data:n}),o(Error("getConnectionToken failed"))}})}))},l.prototype.getMediaType=function(){return t.MediaType.CHAT},l.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},l.prototype._initMediaController=function(){this._isAgentConnectionType()&&t.core.mediaFactory.get(this).catch((function(){}))};var p=function(e,t){s.call(this,e,t)};(p.prototype=Object.create(s.prototype)).constructor=p,p.prototype.getMediaType=function(){return t.MediaType.TASK},p.prototype.getMediaInfo=function(){var e=t.core.getAgentDataProvider().getContactData(this.contactId);return{contactId:this.contactId,initialContactId:e.initialContactId||this.contactId}},p.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)};var d=function(e){t.Connection.call(this,e.contactId,e.connectionId),this.connectionData=e};(d.prototype=Object.create(s.prototype)).constructor=d,d.prototype._getData=function(){return this.connectionData},d.prototype._initMediaController=function(){};var h=function(e){var t=e||{};this.endpointARN=t.endpointId||t.endpointARN||null,this.endpointId=this.endpointARN,this.type=t.type||null,this.name=t.name||null,this.phoneNumber=t.phoneNumber||null,this.agentLogin=t.agentLogin||null,this.queue=t.queue||null};h.prototype.stripPhoneNumber=function(){return this.phoneNumber?this.phoneNumber.replace(/sip:([^@]*)@.*/,"$1"):""},h.byPhoneNumber=function(e,n){return new h({type:t.EndpointType.PHONE_NUMBER,phoneNumber:e,name:n||null})};var f=function(e,t,n){this.errorType=e,this.errorMessage=t,this.endPointUrl=n};f.prototype.getErrorType=function(){return this.errorType},f.prototype.getErrorMessage=function(){return this.errorMessage},f.prototype.getEndPointUrl=function(){return this.endPointUrl},t.agent=function(e){var n=t.core.getEventBus().subscribe(t.AgentEvents.INIT,e);return t.agent.initialized&&e(new t.Agent),n},t.agent.initialized=!1,t.contact=function(e){return t.core.getEventBus().subscribe(t.ContactEvents.INIT,e)},t.onWebsocketInitFailure=function(e){var n=t.core.getEventBus().subscribe(t.WebSocketEvents.INIT_FAILURE,e);return t.webSocketInitFailed&&e(),n},t.ifMaster=function(e,n,r,o){if(t.assertNotNull(e,"A topic must be provided."),t.assertNotNull(n,"A true callback must be provided."),!t.core.masterClient)return t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e).sendInternalLogToServer(),void(r&&r());t.core.getMasterClient().call(t.MasterMethods.CHECK_MASTER,{topic:e,shouldNotBecomeMasterIfNone:o},{success:function(e){e.isMaster?n():r&&r()}})},t.becomeMaster=function(e,n,r){t.assertNotNull(e,"A topic must be provided."),t.core.masterClient?t.core.getMasterClient().call(t.MasterMethods.BECOME_MASTER,{topic:e},{success:function(){n&&n()}}):(t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e),r&&r())},t.Agent=n,t.AgentSnapshot=r,t.Contact=o,t.ContactSnapshot=i,t.Connection=u,t.BaseConnection=s,t.VoiceConnection=u,t.ChatConnection=l,t.TaskConnection=p,t.ConnectionSnapshot=d,t.Endpoint=h,t.Address=h,t.SoftphoneError=f,t.VoiceId=c,t.ContactRecording=a}()},827:(e,t,n)=>{var r;!function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return o(t[s][1][e]||e)}),u,u.exports,e,t,n,r)}return n[s].exports}for(var i=void 0,s=0;s-1});var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]","[object DataView]"];t.exports={isEmptyData:function(e){return"string"==typeof e?0===e.length:0===e.byteLength},convertToBuffer:function(e){return"string"==typeof e&&(e=new r(e,"utf8")),ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}}},{"buffer/":81}],12:[function(e,t,n){var r=e("./browserHashUtils");function o(e,t){this.hash=new e,this.outer=new e;var n=function(e,t){var n=r.convertToBuffer(t);if(n.byteLength>e.BLOCK_SIZE){var o=new e;o.update(n),n=o.digest()}var i=new Uint8Array(e.BLOCK_SIZE);return i.set(n),i}(e,t),o=new Uint8Array(e.BLOCK_SIZE);o.set(n);for(var i=0;i>>32-o)+n&4294967295}function c(e,t,n,r,o,i,s){return a(t&n|~t&r,e,t,o,i,s)}function u(e,t,n,r,o,i,s){return a(t&r|n&~r,e,t,o,i,s)}function l(e,t,n,r,o,i,s){return a(t^n^r,e,t,o,i,s)}function p(e,t,n,r,o,i,s){return a(n^(t|~r),e,t,o,i,s)}t.exports=s,s.BLOCK_SIZE=i,s.prototype.update=function(e){if(r.isEmptyData(e))return this;if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=r.convertToBuffer(e),n=0,o=t.byteLength;for(this.bytesHashed+=o;o>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),o--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},s.prototype.digest=function(e){if(!this.finished){var t=this,n=t.buffer,r=t.bufferLength,s=8*t.bytesHashed;if(n.setUint8(this.bufferLength++,128),r%i>=56){for(var a=this.bufferLength;a>>0,!0),n.setUint32(60,Math.floor(s/4294967296),!0),this.hashBuffer(),this.finished=!0}var c=new DataView(new ArrayBuffer(16));for(a=0;a<4;a++)c.setUint32(4*a,this.state[a],!0);var u=new o(c.buffer,c.byteOffset,c.byteLength);return e?u.toString(e):u},s.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],i=t[3];n=c(n,r,o,i,e.getUint32(0,!0),7,3614090360),i=c(i,n,r,o,e.getUint32(4,!0),12,3905402710),o=c(o,i,n,r,e.getUint32(8,!0),17,606105819),r=c(r,o,i,n,e.getUint32(12,!0),22,3250441966),n=c(n,r,o,i,e.getUint32(16,!0),7,4118548399),i=c(i,n,r,o,e.getUint32(20,!0),12,1200080426),o=c(o,i,n,r,e.getUint32(24,!0),17,2821735955),r=c(r,o,i,n,e.getUint32(28,!0),22,4249261313),n=c(n,r,o,i,e.getUint32(32,!0),7,1770035416),i=c(i,n,r,o,e.getUint32(36,!0),12,2336552879),o=c(o,i,n,r,e.getUint32(40,!0),17,4294925233),r=c(r,o,i,n,e.getUint32(44,!0),22,2304563134),n=c(n,r,o,i,e.getUint32(48,!0),7,1804603682),i=c(i,n,r,o,e.getUint32(52,!0),12,4254626195),o=c(o,i,n,r,e.getUint32(56,!0),17,2792965006),n=u(n,r=c(r,o,i,n,e.getUint32(60,!0),22,1236535329),o,i,e.getUint32(4,!0),5,4129170786),i=u(i,n,r,o,e.getUint32(24,!0),9,3225465664),o=u(o,i,n,r,e.getUint32(44,!0),14,643717713),r=u(r,o,i,n,e.getUint32(0,!0),20,3921069994),n=u(n,r,o,i,e.getUint32(20,!0),5,3593408605),i=u(i,n,r,o,e.getUint32(40,!0),9,38016083),o=u(o,i,n,r,e.getUint32(60,!0),14,3634488961),r=u(r,o,i,n,e.getUint32(16,!0),20,3889429448),n=u(n,r,o,i,e.getUint32(36,!0),5,568446438),i=u(i,n,r,o,e.getUint32(56,!0),9,3275163606),o=u(o,i,n,r,e.getUint32(12,!0),14,4107603335),r=u(r,o,i,n,e.getUint32(32,!0),20,1163531501),n=u(n,r,o,i,e.getUint32(52,!0),5,2850285829),i=u(i,n,r,o,e.getUint32(8,!0),9,4243563512),o=u(o,i,n,r,e.getUint32(28,!0),14,1735328473),n=l(n,r=u(r,o,i,n,e.getUint32(48,!0),20,2368359562),o,i,e.getUint32(20,!0),4,4294588738),i=l(i,n,r,o,e.getUint32(32,!0),11,2272392833),o=l(o,i,n,r,e.getUint32(44,!0),16,1839030562),r=l(r,o,i,n,e.getUint32(56,!0),23,4259657740),n=l(n,r,o,i,e.getUint32(4,!0),4,2763975236),i=l(i,n,r,o,e.getUint32(16,!0),11,1272893353),o=l(o,i,n,r,e.getUint32(28,!0),16,4139469664),r=l(r,o,i,n,e.getUint32(40,!0),23,3200236656),n=l(n,r,o,i,e.getUint32(52,!0),4,681279174),i=l(i,n,r,o,e.getUint32(0,!0),11,3936430074),o=l(o,i,n,r,e.getUint32(12,!0),16,3572445317),r=l(r,o,i,n,e.getUint32(24,!0),23,76029189),n=l(n,r,o,i,e.getUint32(36,!0),4,3654602809),i=l(i,n,r,o,e.getUint32(48,!0),11,3873151461),o=l(o,i,n,r,e.getUint32(60,!0),16,530742520),n=p(n,r=l(r,o,i,n,e.getUint32(8,!0),23,3299628645),o,i,e.getUint32(0,!0),6,4096336452),i=p(i,n,r,o,e.getUint32(28,!0),10,1126891415),o=p(o,i,n,r,e.getUint32(56,!0),15,2878612391),r=p(r,o,i,n,e.getUint32(20,!0),21,4237533241),n=p(n,r,o,i,e.getUint32(48,!0),6,1700485571),i=p(i,n,r,o,e.getUint32(12,!0),10,2399980690),o=p(o,i,n,r,e.getUint32(40,!0),15,4293915773),r=p(r,o,i,n,e.getUint32(4,!0),21,2240044497),n=p(n,r,o,i,e.getUint32(32,!0),6,1873313359),i=p(i,n,r,o,e.getUint32(60,!0),10,4264355552),o=p(o,i,n,r,e.getUint32(24,!0),15,2734768916),r=p(r,o,i,n,e.getUint32(52,!0),21,1309151649),n=p(n,r,o,i,e.getUint32(16,!0),6,4149444226),i=p(i,n,r,o,e.getUint32(44,!0),10,3174756917),o=p(o,i,n,r,e.getUint32(8,!0),15,718787259),r=p(r,o,i,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=r+t[1]&4294967295,t[2]=o+t[2]&4294967295,t[3]=i+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":81}],14:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils");function i(){this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=new Uint32Array(80),this.offset=0,this.shift=24,this.totalLength=0}new Uint32Array([1518500249,1859775393,-1894007588,-899497514]),Math.pow(2,53),t.exports=i,i.BLOCK_SIZE=64,i.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=(e=o.convertToBuffer(e)).length;this.totalLength+=8*t;for(var n=0;n14||14===this.offset&&this.shift<24)&&this.processBlock(),this.offset=14,this.shift=24,this.write(0),this.write(0),this.write(this.totalLength>0xffffffffff?this.totalLength/1099511627776:0),this.write(this.totalLength>4294967295?this.totalLength/4294967296:0);for(var t=24;t>=0;t-=8)this.write(this.totalLength>>t);var n=new r(20),o=new DataView(n.buffer);return o.setUint32(0,this.h0,!1),o.setUint32(4,this.h1,!1),o.setUint32(8,this.h2,!1),o.setUint32(12,this.h3,!1),o.setUint32(16,this.h4,!1),e?n.toString(e):n},i.prototype.processBlock=function(){for(var e=16;e<80;e++){var t=this.block[e-3]^this.block[e-8]^this.block[e-14]^this.block[e-16];this.block[e]=t<<1|t>>>31}var n,r,o=this.h0,i=this.h1,s=this.h2,a=this.h3,c=this.h4;for(e=0;e<80;e++){e<20?(n=a^i&(s^a),r=1518500249):e<40?(n=i^s^a,r=1859775393):e<60?(n=i&s|a&(i|s),r=2400959708):(n=i^s^a,r=3395469782);var u=(o<<5|o>>>27)+n+c+r+(0|this.block[e]);c=a,a=s,s=i<<30|i>>>2,i=o,o=u}for(this.h0=this.h0+o|0,this.h1=this.h1+i|0,this.h2=this.h2+s|0,this.h3=this.h3+a|0,this.h4=this.h4+c|0,this.offset=0,e=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":81}],15:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils"),i=64,s=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=Math.pow(2,53)-1;function c(){this.state=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}t.exports=c,c.BLOCK_SIZE=i,c.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=0,n=(e=o.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>a)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},c.prototype.digest=function(e){if(!this.finished){var t=8*this.bytesHashed,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),o=this.bufferLength;if(n.setUint8(this.bufferLength++,128),o%i>=56){for(var s=this.bufferLength;s>>24&255,a[4*s+1]=this.state[s]>>>16&255,a[4*s+2]=this.state[s]>>>8&255,a[4*s+3]=this.state[s]>>>0&255;return e?a.toString(e):a},c.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],a=t[3],c=t[4],u=t[5],l=t[6],p=t[7],d=0;d>>17|h<<15)^(h>>>19|h<<13)^h>>>10,g=((h=this.temp[d-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(f+this.temp[d-7]|0)+(g+this.temp[d-16]|0)}var m=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(p+(s[d]+this.temp[d]|0)|0)|0,v=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&o^r&o)|0;p=l,l=u,u=c,c=a+m|0,a=o,o=r,r=n,n=m+v|0}t[0]+=n,t[1]+=r,t[2]+=o,t[3]+=a,t[4]+=c,t[5]+=u,t[6]+=l,t[7]+=p}},{"./browserHashUtils":11,"buffer/":81}],16:[function(e,t,n){(function(n){(function(){var n=e("./util");n.crypto.lib=e("./browserCryptoLib"),n.Buffer=e("buffer/").Buffer,n.url=e("url/"),n.querystring=e("querystring/"),n.realClock=e("./realclock/browserClock"),n.environment="js",n.createEventStream=e("./event-stream/buffered-create-event-stream").createEventStream,n.isBrowser=function(){return!0},n.isNode=function(){return!1};var r=e("./core");if(t.exports=r,e("./credentials"),e("./credentials/credential_provider_chain"),e("./credentials/temporary_credentials"),e("./credentials/chainable_temporary_credentials"),e("./credentials/web_identity_credentials"),e("./credentials/cognito_identity_credentials"),e("./credentials/saml_credentials"),r.XML.Parser=e("./xml/browser_parser"),e("./http/xhr"),void 0===o)var o={browser:!0}}).call(this)}).call(this,e("_process"))},{"./browserCryptoLib":10,"./core":18,"./credentials":19,"./credentials/chainable_temporary_credentials":20,"./credentials/cognito_identity_credentials":21,"./credentials/credential_provider_chain":22,"./credentials/saml_credentials":23,"./credentials/temporary_credentials":24,"./credentials/web_identity_credentials":25,"./event-stream/buffered-create-event-stream":27,"./http/xhr":35,"./realclock/browserClock":52,"./util":71,"./xml/browser_parser":72,_process:86,"buffer/":81,"querystring/":92,"url/":94}],17:[function(e,t,n){var r,o=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),o.Config=o.util.inherit({constructor:function(e){void 0===e&&(e={}),e=this.extractCredentials(e),o.util.each.call(this,this.keys,(function(t,n){this.set(t,e[t],n)}))},getCredentials:function(e){var t,n=this;function r(t){e(t,t?null:n.credentials)}function i(e,t){return new o.util.error(t||new Error,{code:"CredentialsError",message:e,name:"CredentialsError"})}n.credentials?"function"==typeof n.credentials.get?n.credentials.get((function(e){e&&(e=i("Could not load credentials from "+n.credentials.constructor.name,e)),r(e)})):(t=null,n.credentials.accessKeyId&&n.credentials.secretAccessKey||(t=i("Missing credentials")),r(t)):n.credentialProvider?n.credentialProvider.resolve((function(e,t){e&&(e=i("Could not load credentials from any providers",e)),n.credentials=t,r(e)})):r(i("No credentials to load"))},update:function(e,t){t=t||!1,e=this.extractCredentials(e),o.util.each.call(this,e,(function(e,n){(t||Object.prototype.hasOwnProperty.call(this.keys,e)||o.Service.hasService(e))&&this.set(e,n)}))},loadFromPath:function(e){this.clear();var t=JSON.parse(o.util.readFileSync(e)),n=new o.FileSystemCredentials(e),r=new o.CredentialProviderChain;return r.providers.unshift(n),r.resolve((function(e,n){if(e)throw e;t.credentials=n})),this.constructor(t),this},clear:function(){o.util.each.call(this,this.keys,(function(e){delete this[e]})),this.set("credentials",void 0),this.set("credentialProvider",void 0)},set:function(e,t,n){void 0===t?(void 0===n&&(n=this.keys[e]),this[e]="function"==typeof n?n.call(this):n):"httpOptions"===e&&this[e]?this[e]=o.util.merge(this[e],t):this[e]=t},keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:void 0,httpOptions:{timeout:12e4},maxRetries:void 0,maxRedirects:10,paramValidation:!0,sslEnabled:!0,s3ForcePathStyle:!1,s3BucketEndpoint:!1,s3DisableBodySigning:!0,computeChecksums:!0,convertResponseTypes:!0,correctClockSkew:!1,customUserAgent:null,dynamoDbCrc32:!0,systemClockOffset:0,signatureVersion:null,signatureCache:!0,retryDelayOptions:{},useAccelerateEndpoint:!1,clientSideMonitoring:!1,endpointDiscoveryEnabled:!1,endpointCacheSize:1e3,hostPrefixEnabled:!0,stsRegionalEndpoints:null},extractCredentials:function(e){return e.accessKeyId&&e.secretAccessKey&&((e=o.util.copy(e)).credentials=new o.Credentials(e)),e},setPromisesDependency:function(e){r=e,null===e&&"function"==typeof Promise&&(r=Promise);var t=[o.Request,o.Credentials,o.CredentialProviderChain];o.S3&&(t.push(o.S3),o.S3.ManagedUpload&&t.push(o.S3.ManagedUpload)),o.util.addPromises(t,r)},getPromisesDependency:function(){return r}}),o.config=new o.Config},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(e,t,n){var r={util:e("./util")};({}).toString(),t.exports=r,r.util.update(r,{VERSION:"2.553.0",Signers:{},Protocol:{Json:e("./protocol/json"),Query:e("./protocol/query"),Rest:e("./protocol/rest"),RestJson:e("./protocol/rest_json"),RestXml:e("./protocol/rest_xml")},XML:{Builder:e("./xml/builder"),Parser:null},JSON:{Builder:e("./json/builder"),Parser:e("./json/parser")},Model:{Api:e("./model/api"),Operation:e("./model/operation"),Shape:e("./model/shape"),Paginator:e("./model/paginator"),ResourceWaiter:e("./model/resource_waiter")},apiLoader:e("./api_loader"),EndpointCache:e("../vendor/endpoint-cache").EndpointCache}),e("./sequential_executor"),e("./service"),e("./config"),e("./http"),e("./event_listeners"),e("./request"),e("./response"),e("./resource_waiter"),e("./signers/request_signer"),e("./param_validator"),r.events=new r.SequentialExecutor,r.util.memoizedProperty(r,"endpointCache",(function(){return new r.EndpointCache(r.config.endpointCacheSize)}),!0)},{"../vendor/endpoint-cache":103,"./api_loader":9,"./config":17,"./event_listeners":33,"./http":34,"./json/builder":36,"./json/parser":37,"./model/api":38,"./model/operation":40,"./model/paginator":41,"./model/resource_waiter":42,"./model/shape":43,"./param_validator":44,"./protocol/json":46,"./protocol/query":47,"./protocol/rest":48,"./protocol/rest_json":49,"./protocol/rest_xml":50,"./request":55,"./resource_waiter":56,"./response":57,"./sequential_executor":58,"./service":59,"./signers/request_signer":63,"./util":71,"./xml/builder":73}],19:[function(e,t,n){var r=e("./core");r.Credentials=r.util.inherit({constructor:function(){if(r.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"==typeof arguments[0]){var e=arguments[0].credentials||arguments[0];this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken}else this.accessKeyId=arguments[0],this.secretAccessKey=arguments[1],this.sessionToken=arguments[2]},expiryWindow:15,needsRefresh:function(){var e=r.util.date.getDate().getTime(),t=new Date(e+1e3*this.expiryWindow);return!!(this.expireTime&&t>this.expireTime)||this.expired||!this.accessKeyId||!this.secretAccessKey},get:function(e){var t=this;this.needsRefresh()?this.refresh((function(n){n||(t.expired=!1),e&&e(n)})):e&&e()},refresh:function(e){this.expired=!1,e()},coalesceRefresh:function(e,t){var n=this;1===n.refreshCallbacks.push(e)&&n.load((function(e){r.util.arrayEach(n.refreshCallbacks,(function(n){t?n(e):r.util.defer((function(){n(e)}))})),n.refreshCallbacks.length=0}))},load:function(e){e()}}),r.Credentials.addPromisesToClass=function(e){this.prototype.getPromise=r.util.promisifyMethod("get",e),this.prototype.refreshPromise=r.util.promisifyMethod("refresh",e)},r.Credentials.deletePromisesFromClass=function(){delete this.prototype.getPromise,delete this.prototype.refreshPromise},r.util.addPromises(r.Credentials)},{"./core":18}],20:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.ChainableTemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=r.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new r.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}var n=r.util.merge({params:t,credentials:e.masterCredentials||r.config.credentials},e.stsConfig||{});this.service=new o(n)},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this,n=t.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode((function(r,o){var i={};r?e(r):(o&&(i.TokenCode=o),t.service[n](i,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)})))}))},getTokenCode:function(e){var t=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,(function(n,o){if(n){var i=n;return n instanceof Error&&(i=n.message),void e(r.util.error(new Error("Error fetching MFA token: "+i),{code:t.errorCode}))}e(null,o)})):e(null)}})},{"../../clients/sts":8,"../core":18}],21:[function(e,t,n){var r=e("../core"),o=e("../../clients/cognitoidentity"),i=e("../../clients/sts");r.CognitoIdentityCredentials=r.util.inherit(r.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=r.util.copy(t||{}),this.loadCachedId();var n=this;Object.defineProperty(this,"identityId",{get:function(){return n.loadCachedId(),n._identityId||n.params.IdentityId},set:function(e){n._identityId=e}})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.data=null,t._identityId=null,t.getId((function(n){n?(t.clearIdOnNotAuthorized(n),e(n)):t.params.RoleArn?t.getCredentialsFromSTS(e):t.getCredentialsForIdentity(e)}))},clearCachedId:function(){this._identityId=null,delete this.params.IdentityId;var e=this.params.IdentityPoolId,t=this.params.LoginId||"";delete this.storage[this.localStorageKey.id+e+t],delete this.storage[this.localStorageKey.providers+e+t]},clearIdOnNotAuthorized:function(e){"NotAuthorizedException"==e.code&&this.clearCachedId()},getId:function(e){var t=this;if("string"==typeof t.params.IdentityId)return e(null,t.params.IdentityId);t.cognito.getId((function(n,r){!n&&r.IdentityId?(t.params.IdentityId=r.IdentityId,e(null,r.IdentityId)):e(n)}))},loadCredentials:function(e,t){e&&t&&(t.expired=!1,t.accessKeyId=e.Credentials.AccessKeyId,t.secretAccessKey=e.Credentials.SecretKey,t.sessionToken=e.Credentials.SessionToken,t.expireTime=e.Credentials.Expiration)},getCredentialsForIdentity:function(e){var t=this;t.cognito.getCredentialsForIdentity((function(n,r){n?t.clearIdOnNotAuthorized(n):(t.cacheId(r),t.data=r,t.loadCredentials(t.data,t)),e(n)}))},getCredentialsFromSTS:function(e){var t=this;t.cognito.getOpenIdToken((function(n,r){n?(t.clearIdOnNotAuthorized(n),e(n)):(t.cacheId(r),t.params.WebIdentityToken=r.Token,t.webIdentityCredentials.refresh((function(n){n||(t.data=t.webIdentityCredentials.data,t.sts.credentialsFrom(t.data,t)),e(n)})))}))},loadCachedId:function(){var e=this;if(r.util.isBrowser()&&!e.params.IdentityId){var t=e.getStorage("id");if(t&&e.params.Logins){var n=Object.keys(e.params.Logins);0!==(e.getStorage("providers")||"").split(",").filter((function(e){return-1!==n.indexOf(e)})).length&&(e.params.IdentityId=t)}else t&&(e.params.IdentityId=t)}},createClients:function(){var e=this._clientConfig;if(this.webIdentityCredentials=this.webIdentityCredentials||new r.WebIdentityCredentials(this.params,e),!this.cognito){var t=r.util.merge({},e);t.params=this.params,this.cognito=new o(t)}this.sts=this.sts||new i(e)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,r.util.isBrowser()&&(this.setStorage("id",e.IdentityId),this.params.Logins&&this.setStorage("providers",Object.keys(this.params.Logins).join(",")))},getStorage:function(e){return this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]},setStorage:function(e,t){try{this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]=t}catch(e){}},storage:function(){try{var e=r.util.isBrowser()&&null!==window.localStorage&&"object"==typeof window.localStorage?window.localStorage:{};return e["aws.test-storage"]="foobar",delete e["aws.test-storage"],e}catch(e){return{}}}()})},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(e,t,n){var r=e("../core");r.CredentialProviderChain=r.util.inherit(r.Credentials,{constructor:function(e){this.providers=e||r.CredentialProviderChain.defaultProviders.slice(0),this.resolveCallbacks=[]},resolve:function(e){var t=this;if(0===t.providers.length)return e(new Error("No providers")),t;if(1===t.resolveCallbacks.push(e)){var n=0,o=t.providers.slice(0);!function e(i,s){if(!i&&s||n===o.length)return r.util.arrayEach(t.resolveCallbacks,(function(e){e(i,s)})),void(t.resolveCallbacks.length=0);var a=o[n++];(s="function"==typeof a?a.call():a).get?s.get((function(t){e(t,t?null:s)})):e(null,s)}()}return t}}),r.CredentialProviderChain.defaultProviders=[],r.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=r.util.promisifyMethod("resolve",e)},r.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},r.util.addPromises(r.CredentialProviderChain)},{"../core":18}],23:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.SAMLCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithSAML((function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":18}],24:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.TemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.loadMasterCredentials(t),this.expired=!0,this.params=e||{},this.params.RoleArn&&(this.params.RoleSessionName=this.params.RoleSessionName||"temporary-credentials")},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.masterCredentials.get((function(){t.service.config.credentials=t.masterCredentials,(t.params.RoleArn?t.service.assumeRole:t.service.getSessionToken).call(t.service,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))}))},loadMasterCredentials:function(e){for(this.masterCredentials=e||r.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new r.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":18}],25:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.WebIdentityCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=r.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithWebIdentity((function(n,r){t.data=null,n||(t.data=r,t.service.credentialsFrom(r,t)),e(n)}))},createClients:function(){if(!this.service){var e=r.util.merge({},this._clientConfig);e.params=this.params,this.service=new o(e)}}})},{"../../clients/sts":8,"../core":18}],26:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./util"),i=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function s(e){var t=e.service,n=t.api||{},r=(n.operations,{});return t.config.region&&(r.region=t.config.region),n.serviceId&&(r.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(r.accessKeyId=t.config.credentials.accessKeyId),r}function a(e,t,n){n&&null!=t&&"structure"===n.type&&n.required&&n.required.length>0&&o.arrayEach(n.required,(function(r){var o=n.members[r];if(!0===o.endpointDiscoveryId){var i=o.isLocationName?o.name:r;e[i]=String(t[r])}else a(e,t[r],o)}))}function c(e,t){var n={};return a(n,e.params,t),n}function u(e){var t=e.service,n=t.api,i=n.operations?n.operations[e.operation]:void 0,a=c(e,i?i.input:void 0),u=s(e);Object.keys(a).length>0&&(u=o.update(u,a),i&&(u.operation=i.name));var l=r.endpointCache.get(u);if(!l||1!==l.length||""!==l[0].Address)if(l&&l.length>0)e.httpRequest.updateEndpoint(l[0].Address);else{var p=t.makeRequest(n.endpointOperation,{Operation:i.name,Identifiers:a});d(p),p.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),p.removeListener("retry",r.EventListeners.Core.RETRY_CHECK),r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}]),p.send((function(e,t){t&&t.Endpoints?r.endpointCache.put(u,t.Endpoints):e&&r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}])}))}}var l={};function p(e,t){var n=e.service,i=n.api,a=i.operations?i.operations[e.operation]:void 0,u=a?a.input:void 0,p=c(e,u),h=s(e);Object.keys(p).length>0&&(h=o.update(h,p),a&&(h.operation=a.name));var f=r.EndpointCache.getKeyString(h),g=r.endpointCache.get(f);if(g&&1===g.length&&""===g[0].Address)return l[f]||(l[f]=[]),void l[f].push({request:e,callback:t});if(g&&g.length>0)e.httpRequest.updateEndpoint(g[0].Address),t();else{var m=n.makeRequest(i.endpointOperation,{Operation:a.name,Identifiers:p});m.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),d(m),r.endpointCache.put(f,[{Address:"",CachePeriodInMinutes:60}]),m.send((function(n,i){if(n){var s={code:"EndpointDiscoveryException",message:"Request cannot be fulfilled without specifying an endpoint",retryable:!1};if(e.response.error=o.error(n,s),r.endpointCache.remove(h),l[f]){var a=l[f];o.arrayEach(a,(function(e){e.request.response.error=o.error(n,s),e.callback()})),delete l[f]}}else i&&(r.endpointCache.put(f,i.Endpoints),e.httpRequest.updateEndpoint(i.Endpoints[0].Address),l[f])&&(a=l[f],o.arrayEach(a,(function(e){e.request.httpRequest.updateEndpoint(i.Endpoints[0].Address),e.callback()})),delete l[f]);t()}))}}function d(e){var t=e.service.api.apiVersion;t&&!e.httpRequest.headers["x-amz-api-version"]&&(e.httpRequest.headers["x-amz-api-version"]=t)}function h(e){var t=e.error,n=e.httpResponse;if(t&&("InvalidEndpointException"===t.code||421===n.statusCode)){var i=e.request,a=i.service.api.operations||{},u=c(i,a[i.operation]?a[i.operation].input:void 0),l=s(i);Object.keys(u).length>0&&(l=o.update(l,u),a[i.operation]&&(l.operation=a[i.operation].name)),r.endpointCache.remove(l)}}function f(e){return["false","0"].indexOf(e)>=0}t.exports={discoverEndpoint:function(e,t){var s=e.service||{};if(function(e){if(e._originalConfig&&e._originalConfig.endpoint&&!0===e._originalConfig.endpointDiscoveryEnabled)throw o.error(new Error,{code:"ConfigurationException",message:"Custom endpoint is supplied; endpointDiscoveryEnabled must not be true."});var t=r.config[e.serviceIdentifier]||{};return Boolean(r.config.endpoint||t.endpoint||e._originalConfig&&e._originalConfig.endpoint)}(s)||e.isPresigned())return t();if(!function(e){if(!0===(e.service||{}).config.endpointDiscoveryEnabled)return!0;if(o.isBrowser())return!1;for(var t=0;t-1&&(e[t]++,0===e[t]);t--);}i.fromNumber=function(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(e+" is too large (or, if negative, too small) to represent as an Int64");for(var t=new Uint8Array(8),n=7,r=Math.abs(Math.round(e));n>-1&&r>0;n--,r/=256)t[n]=r;return e<0&&s(t),new i(t)},i.prototype.valueOf=function(){var e=this.bytes.slice(0),t=128&e[0];return t&&s(e),parseInt(e.toString("hex"),16)*(t?-1:1)},i.prototype.toString=function(){return String(this.valueOf())},t.exports={Int64:i}},{"../core":18}],30:[function(e,t,n){var r=e("./parse-message").parseMessage;t.exports={parseEvent:function(e,t,n){var o=r(t),i=o.headers[":message-type"];if(i){if("error"===i.value)throw function(e){var t=e.headers[":error-code"],n=e.headers[":error-message"],r=new Error(n.value||n);return r.code=r.name=t.value||t,r}(o);if("event"!==i.value)return}var s=o.headers[":event-type"],a=n.members[s.value];if(a){var c={},u=a.eventPayloadMemberName;if(u){var l=a.members[u];"binary"===l.type?c[u]=o.body:c[u]=e.parse(o.body.toString(),l)}for(var p=a.eventHeaderMemberNames,d=0;d=0)return e.httpRequest.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",t();r.util.computeSha256(i,(function(n,r){n?t(n):(e.httpRequest.headers["X-Amz-Content-Sha256"]=r,t())}))}else t()}})),e("SET_CONTENT_LENGTH","afterBuild",(function(e){var t=function(e){if(!e.service.api.operations)return"";var t=e.service.api.operations[e.operation];return t?t.authtype:""}(e),n=r.util.getRequestPayloadShape(e);if(void 0===e.httpRequest.headers["Content-Length"])try{var o=r.util.string.byteLength(e.httpRequest.body);e.httpRequest.headers["Content-Length"]=o}catch(r){if(n&&n.isStreaming){if(n.requiresLength)throw r;if(t.indexOf("unsigned-body")>=0)return void(e.httpRequest.headers["Transfer-Encoding"]="chunked");throw r}throw r}})),e("SET_HTTP_HOST","afterBuild",(function(e){e.httpRequest.headers.Host=e.httpRequest.endpoint.host})),e("RESTART","restart",(function(){var e=this.response.error;e&&e.retryable&&(this.httpRequest=new r.HttpRequest(this.service.endpoint,this.service.region),this.response.retryCount=600?this.emit("sign",[this],(function(e){e?t(e):i()})):i()})),e("HTTP_HEADERS","httpHeaders",(function(e,t,n,o){n.httpResponse.statusCode=e,n.httpResponse.statusMessage=o,n.httpResponse.headers=t,n.httpResponse.body=r.util.buffer.toBuffer(""),n.httpResponse.buffers=[],n.httpResponse.numBytes=0;var i=t.date||t.Date,s=n.request.service;if(i){var a=Date.parse(i);s.config.correctClockSkew&&s.isClockSkewed(a)&&s.applyClockOffset(a)}})),e("HTTP_DATA","httpData",(function(e,t){if(e){if(r.util.isNode()){t.httpResponse.numBytes+=e.length;var n=t.httpResponse.headers["content-length"],o={loaded:t.httpResponse.numBytes,total:n};t.request.emit("httpDownloadProgress",[o,t])}t.httpResponse.buffers.push(r.util.buffer.toBuffer(e))}})),e("HTTP_DONE","httpDone",(function(e){if(e.httpResponse.buffers&&e.httpResponse.buffers.length>0){var t=r.util.buffer.concat(e.httpResponse.buffers);e.httpResponse.body=t}delete e.httpResponse.numBytes,delete e.httpResponse.buffers})),e("FINALIZE_ERROR","retry",(function(e){e.httpResponse.statusCode&&(e.error.statusCode=e.httpResponse.statusCode,void 0===e.error.retryable&&(e.error.retryable=this.service.retryableError(e.error,this)))})),e("INVALIDATE_CREDENTIALS","retry",(function(e){if(e.error)switch(e.error.code){case"RequestExpired":case"ExpiredTokenException":case"ExpiredToken":e.error.retryable=!0,e.request.service.config.credentials.expired=!0}})),e("EXPIRED_SIGNATURE","retry",(function(e){var t=e.error;t&&"string"==typeof t.code&&"string"==typeof t.message&&t.code.match(/Signature/)&&t.message.match(/expired/)&&(e.error.retryable=!0)})),e("CLOCK_SKEWED","retry",(function(e){e.error&&this.service.clockSkewError(e.error)&&this.service.config.correctClockSkew&&(e.error.retryable=!0)})),e("REDIRECT","retry",(function(e){e.error&&e.error.statusCode>=300&&e.error.statusCode<400&&e.httpResponse.headers.location&&(this.httpRequest.endpoint=new r.Endpoint(e.httpResponse.headers.location),this.httpRequest.headers.Host=this.httpRequest.endpoint.host,e.error.redirect=!0,e.error.retryable=!0)})),e("RETRY_CHECK","retry",(function(e){e.error&&(e.error.redirect&&e.redirectCount=this.HEADERS_RECEIVED&&!p&&(c.statusCode=l.status,c.headers=s.parseHeaders(l.getAllResponseHeaders()),c.emit("headers",c.statusCode,c.headers,l.statusText),p=!0),this.readyState===this.DONE&&s.finishRequest(l,c)}),!1),l.upload.addEventListener("progress",(function(e){c.emit("sendProgress",e)})),l.addEventListener("progress",(function(e){c.emit("receiveProgress",e)}),!1),l.addEventListener("timeout",(function(){i(r.util.error(new Error("Timeout"),{code:"TimeoutError"}))}),!1),l.addEventListener("error",(function(){i(r.util.error(new Error("Network Failure"),{code:"NetworkingError"}))}),!1),l.addEventListener("abort",(function(){i(r.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))}),!1),n(c),l.open(e.method,u,!1!==t.xhrAsync),r.util.each(e.headers,(function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&l.setRequestHeader(e,t)})),t.timeout&&!1!==t.xhrAsync&&(l.timeout=t.timeout),t.xhrWithCredentials&&(l.withCredentials=!0);try{l.responseType="arraybuffer"}catch(e){}try{e.body?l.send(e.body):l.send()}catch(t){if(!e.body||"object"!=typeof e.body.buffer)throw t;l.send(e.body.buffer)}return c},parseHeaders:function(e){var t={};return r.util.arrayEach(e.split(/\r?\n/),(function(e){var n=e.split(":",1)[0],r=e.substring(n.length+2);n.length>0&&(t[n.toLowerCase()]=r)})),t},finishRequest:function(e,t){var n;if("arraybuffer"===e.responseType&&e.response){var o=e.response;n=new r.util.Buffer(o.byteLength);for(var i=new Uint8Array(o),s=0;s-1?t||"":t,this.isJsonValue?JSON.parse(t):t&&"function"==typeof t.toString?t.toString():t},this.toWireFormat=function(e){return this.isJsonValue?JSON.stringify(e):e}}function h(){a.apply(this,arguments),this.toType=function(e){var t=o.base64.decode(e);if(this.isSensitive&&o.isNode()&&"function"==typeof o.Buffer.alloc){var n=o.Buffer.alloc(t.length,t);t.fill(0),t=n}return t},this.toWireFormat=o.base64.encode}function f(){h.apply(this,arguments)}function g(){a.apply(this,arguments),this.toType=function(e){return"boolean"==typeof e?e:null==e?null:"true"===e}}a.normalizedTypes={character:"string",double:"float",long:"integer",short:"integer",biginteger:"integer",bigdecimal:"float",blob:"binary"},a.types={structure:u,list:l,map:p,boolean:g,timestamp:function(e){var t=this;if(a.apply(this,arguments),e.timestampFormat)i(this,"timestampFormat",e.timestampFormat);else if(t.isTimestampFormatSet&&this.timestampFormat)i(this,"timestampFormat",this.timestampFormat);else if("header"===this.location)i(this,"timestampFormat","rfc822");else if("querystring"===this.location)i(this,"timestampFormat","iso8601");else if(this.api)switch(this.api.protocol){case"json":case"rest-json":i(this,"timestampFormat","unixTimestamp");break;case"rest-xml":case"query":case"ec2":i(this,"timestampFormat","iso8601")}this.toType=function(e){return null==e?null:"function"==typeof e.toUTCString?e:"string"==typeof e||"number"==typeof e?o.date.parseTimestamp(e):null},this.toWireFormat=function(e){return o.date.format(e,t.timestampFormat)}},float:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseFloat(e)},this.toWireFormat=this.toType},integer:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseInt(e,10)},this.toWireFormat=this.toType},string:d,base64:f,binary:h},a.resolve=function(e,t){if(e.shape){var n=t.api.shapes[e.shape];if(!n)throw new Error("Cannot find shape reference: "+e.shape);return n}return null},a.create=function(e,t,n){if(e.isShape)return e;var r=a.resolve(e,t);if(r){var o=Object.keys(e);t.documentation||(o=o.filter((function(e){return!e.match(/documentation/)})));var i=function(){r.constructor.call(this,e,t,n)};return i.prototype=r,new i}e.type||(e.members?e.type="structure":e.member?e.type="list":e.key?e.type="map":e.type="string");var s=e.type;if(a.normalizedTypes[e.type]&&(e.type=a.normalizedTypes[e.type]),a.types[e.type])return new a.types[e.type](e,t,n);throw new Error("Unrecognized shape type: "+s)},a.shapes={StructureShape:u,ListShape:l,MapShape:p,StringShape:d,BooleanShape:g,Base64Shape:f},t.exports=a},{"../util":71,"./collection":39}],44:[function(e,t,n){var r=e("./core");r.ParamValidator=r.util.inherit({constructor:function(e){!0!==e&&void 0!==e||(e={min:!0}),this.validation=e},validate:function(e,t,n){if(this.errors=[],this.validateMember(e,t||{},n||"params"),this.errors.length>1){var o=this.errors.join("\n* ");throw o="There were "+this.errors.length+" validation errors:\n* "+o,r.util.error(new Error(o),{code:"MultipleValidationErrors",errors:this.errors})}if(1===this.errors.length)throw this.errors[0];return!0},fail:function(e,t){this.errors.push(r.util.error(new Error(t),{code:e}))},validateStructure:function(e,t,n){var r;this.validateType(t,n,["object"],"structure");for(var o=0;e.required&&o= 1, but found "'+t+'" for '+n)},validatePattern:function(e,t,n){this.validation.pattern&&void 0!==e.pattern&&(new RegExp(e.pattern).test(t)||this.fail("PatternMatchError",'Provided value "'+t+'" does not match regex pattern /'+e.pattern+"/ for "+n))},validateRange:function(e,t,n,r){this.validation.min&&void 0!==e.min&&t= "+e.min+", but found "+t+" for "+n),this.validation.max&&void 0!==e.max&&t>e.max&&this.fail("MaxRangeError","Expected "+r+" <= "+e.max+", but found "+t+" for "+n)},validateEnum:function(e,t,n){this.validation.enum&&void 0!==e.enum&&-1===e.enum.indexOf(t)&&this.fail("EnumError","Found string value of "+t+", but expected "+e.enum.join("|")+" for "+n)},validateType:function(e,t,n,o){if(null==e)return!1;for(var i=!1,s=0;s63)throw r.error(new Error,{code:"ValidationError",message:"Hostname label length should be between 1 to 63 characters, inclusive."});if(!i.test(e))throw o.util.error(new Error,{code:"ValidationError",message:e+" is not hostname compatible."})}))}return e}}},{"../core":18,"../util":71}],46:[function(e,t,n){var r=e("../util"),o=e("../json/builder"),i=e("../json/parser"),s=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.httpRequest,n=e.service.api,r=n.targetPrefix+"."+n.operations[e.operation].name,i=n.jsonVersion||"1.0",a=n.operations[e.operation].input,c=new o;1===i&&(i="1.0"),t.body=c.build(e.params||{},a),t.headers["Content-Type"]="application/x-amz-json-"+i,t.headers["X-Amz-Target"]=r,s(e)},extractError:function(e){var t={},n=e.httpResponse;if(t.code=n.headers["x-amzn-errortype"]||"UnknownError","string"==typeof t.code&&(t.code=t.code.split(":")[0]),n.body.length>0)try{var o=JSON.parse(n.body.toString());(o.__type||o.code)&&(t.code=(o.__type||o.code).split("#").pop()),"RequestEntityTooLarge"===t.code?t.message="Request body must be less than 1 MB":t.message=o.message||o.Message||null}catch(o){t.statusCode=n.statusCode,t.message=n.statusMessage}else t.statusCode=n.statusCode,t.message=n.statusCode.toString();e.error=r.error(new Error,t)},extractData:function(e){var t=e.httpResponse.body.toString()||"{}";if(!1===e.request.service.config.convertResponseTypes)e.data=JSON.parse(t);else{var n=e.request.service.api.operations[e.request.operation].output||{},r=new i;e.data=r.parse(t,n)}}}},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(e,t,n){var r=e("../core"),o=e("../util"),i=e("../query/query_param_serializer"),s=e("../model/shape"),a=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.service.api.operations[e.operation],n=e.httpRequest;n.headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8",n.params={Version:e.service.api.apiVersion,Action:t.name},(new i).serialize(e.params,t.input,(function(e,t){n.params[e]=t})),n.body=o.queryParamsToString(n.params),a(e)},extractError:function(e){var t,n=e.httpResponse.body.toString();if(n.match("=0?"&":"?";var c=[];r.arrayEach(Object.keys(s).sort(),(function(e){Array.isArray(s[e])||(s[e]=[s[e]]);for(var t=0;t0){var p=(t=new r.XML.Parser).parse(s.toString(),c);o.update(e.data,p)}}}},{"../core":18,"../util":71,"./rest":48}],51:[function(e,t,n){var r=e("../util");function o(){}function i(e){return e.isQueryName||"ec2"!==e.api.protocol?e.name:e.name[0].toUpperCase()+e.name.substr(1)}function s(e,t,n,o){r.each(n.members,(function(n,r){var s=t[n];if(null!=s){var c=i(r);a(c=e?e+"."+c:c,s,r,o)}}))}function a(e,t,n,o){null!=t&&("structure"===n.type?s(e,t,n,o):"list"===n.type?function(e,t,n,o){var s=n.member||{};0!==t.length?r.arrayEach(t,(function(t,r){var c="."+(r+1);if("ec2"===n.api.protocol)c+="";else if(n.flattened){if(s.name){var u=e.split(".");u.pop(),u.push(i(s)),e=u.join(".")}}else c="."+(s.name?s.name:"member")+c;a(e+c,t,s,o)})):o.call(this,e,null)}(e,t,n,o):"map"===n.type?function(e,t,n,o){var i=1;r.each(t,(function(t,r){var s=(n.flattened?".":".entry.")+i+++".",c=s+(n.key.name||"key"),u=s+(n.value.name||"value");a(e+c,t,n.key,o),a(e+u,r,n.value,o)}))}(e,t,n,o):o(e,n.toWireFormat(t).toString()))}o.prototype.serialize=function(e,t,n){s("",e,t,n)},t.exports=o},{"../util":71}],52:[function(e,t,n){t.exports={now:function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}}},{}],53:[function(e,t,n){var r=e("./util"),o=e("./region_config_data.json");function i(e,t){r.each(t,(function(t,n){"globalEndpoint"!==t&&(void 0!==e.config[t]&&null!==e.config[t]||(e.config[t]=n))}))}t.exports=function(e){for(var t=function(e){var t=e.config.region,n=function(e){if(!e)return null;var t=e.split("-");return t.length<3?null:t.slice(0,t.length-2).join("-")+"-*"}(t),r=e.api.endpointPrefix;return[[t,r],[n,r],[t,"*"],[n,"*"],["*",r],["*","*"]].map((function(e){return e[0]&&e[1]?e.join("/"):null}))}(e),n=0;n=0){c=!0;var u=0}var l=function(){c&&u!==a?o.emit("error",n.util.error(new Error("Stream content length mismatch. Received "+u+" of "+a+" bytes."),{code:"StreamContentLengthMismatch"})):2===n.HttpClient.streamsApiVersion?o.end():o.emit("end")},p=s.httpResponse.createUnbufferedStream();if(2===n.HttpClient.streamsApiVersion)if(c){var d=new e.PassThrough;d._write=function(t){return t&&t.length&&(u+=t.length),e.PassThrough.prototype._write.apply(this,arguments)},d.on("end",l),o.on("error",(function(e){c=!1,p.unpipe(d),d.emit("end"),d.end()})),p.pipe(d).pipe(o,{end:!1})}else p.pipe(o);else c&&p.on("data",(function(e){e&&e.length&&(u+=e.length)})),p.on("data",(function(e){o.emit("data",e)})),p.on("end",l);p.on("error",(function(e){c=!1,o.emit("error",e)}))}})),o},emitEvent:function(e,t,r){"function"==typeof t&&(r=t,t=null),r||(r=function(){}),t||(t=this.eventParameters(e,this.response)),n.SequentialExecutor.prototype.emit.call(this,e,t,(function(e){e&&(this.response.error=e),r.call(this,e)}))},eventParameters:function(e){switch(e){case"restart":case"validate":case"sign":case"build":case"afterValidate":case"afterBuild":return[this];case"error":return[this.response.error,this.response];default:return[this.response]}},presign:function(e,t){return t||"function"!=typeof e||(t=e,e=null),(new n.Signers.Presign).sign(this.toGet(),e,t)},isPresigned:function(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,"presigned-expires")},toUnauthenticated:function(){return this._unAuthenticated=!0,this.removeListener("validate",n.EventListeners.Core.VALIDATE_CREDENTIALS),this.removeListener("sign",n.EventListeners.Core.SIGN),this},toGet:function(){return"query"!==this.service.api.protocol&&"ec2"!==this.service.api.protocol||(this.removeListener("build",this.buildAsGet),this.addListener("build",this.buildAsGet)),this},buildAsGet:function(e){e.httpRequest.method="GET",e.httpRequest.path=e.service.endpoint.path+"?"+e.httpRequest.body,e.httpRequest.body="",delete e.httpRequest.headers["Content-Length"],delete e.httpRequest.headers["Content-Type"]},haltHandlersOnError:function(){this._haltHandlersOnError=!0}}),n.Request.addPromisesToClass=function(e){this.prototype.promise=function(){var t=this;return this.httpRequest.appendToUserAgent("promise"),new e((function(e,n){t.on("complete",(function(t){t.error?n(t.error):e(Object.defineProperty(t.data||{},"$response",{value:t}))})),t.runTo()}))}},n.Request.deletePromisesFromClass=function(){delete this.prototype.promise},n.util.addPromises(n.Request),n.util.mixin(n.Request,n.SequentialExecutor)}).call(this)}).call(this,e("_process"))},{"./core":18,"./state_machine":70,_process:86,jmespath:85}],56:[function(e,t,n){var r=e("./core"),o=r.util.inherit,i=e("jmespath");function s(e){var t=e.request._waiter,n=t.config.acceptors,r=!1,o="retry";n.forEach((function(n){if(!r){var i=t.matchers[n.matcher];i&&i(e,n.expected,n.argument)&&(r=!0,o=n.state)}})),!r&&e.error&&(o="failure"),"success"===o?t.setSuccess(e):t.setError(e,"retry"===o)}r.ResourceWaiter=o({constructor:function(e,t){this.service=e,this.state=t,this.loadWaiterConfig(this.state)},service:null,state:null,config:null,matchers:{path:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}return i.strictDeepEqual(r,t)},pathAll:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}Array.isArray(r)||(r=[r]);var o=r.length;if(!o)return!1;for(var s=0;s-1&&n.splice(o,1)}return this},removeAllListeners:function(e){return e?delete this._events[e]:this._events={},this},emit:function(e,t,n){n||(n=function(){});var r=this.listeners(e),o=r.length;return this.callListeners(r,t,n),o>0},callListeners:function(e,t,n,o){var i=this,s=o||null;function a(o){if(o&&(s=r.util.error(s||new Error,o),i._haltHandlersOnError))return n.call(i,s);i.callListeners(e,t,n,s)}for(;e.length>0;){var c=e.shift();if(c._isAsync)return void c.apply(i,t.concat([a]));try{c.apply(i,t)}catch(e){s=r.util.error(s||new Error,e)}if(s&&i._haltHandlersOnError)return void n.call(i,s)}n.call(i,s)},addListeners:function(e){var t=this;return e._events&&(e=e._events),r.util.each(e,(function(e,n){"function"==typeof n&&(n=[n]),r.util.arrayEach(n,(function(n){t.on(e,n)}))})),t},addNamedListener:function(e,t,n,r){return this[e]=n,this.addListener(t,n,r),this},addNamedAsyncListener:function(e,t,n,r){return n._isAsync=!0,this.addNamedListener(e,t,n,r)},addNamedListeners:function(e){var t=this;return e((function(){t.addNamedListener.apply(t,arguments)}),(function(){t.addNamedAsyncListener.apply(t,arguments)})),this}}),r.SequentialExecutor.prototype.addListener=r.SequentialExecutor.prototype.on,t.exports=r.SequentialExecutor},{"./core":18}],59:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./model/api"),i=e("./region_config"),s=r.util.inherit,a=0;r.Service=s({constructor:function(e){if(!this.loadServiceClass)throw r.util.error(new Error,"Service must be constructed with `new' operator");var t=this.loadServiceClass(e||{});if(t){var n=r.util.copy(e),o=new t(e);return Object.defineProperty(o,"_originalConfig",{get:function(){return n},enumerable:!1,configurable:!0}),o._clientId=++a,o}this.initialize(e)},initialize:function(e){var t=r.config[this.serviceIdentifier];if(this.config=new r.Config(r.config),t&&this.config.update(t,!0),e&&this.config.update(e,!0),this.validateService(),this.config.endpoint||i(this),this.config.endpoint=this.endpointFromTemplate(this.config.endpoint),this.setEndpoint(this.config.endpoint),r.SequentialExecutor.call(this),r.Service.addDefaultMonitoringListeners(this),(this.config.clientSideMonitoring||r.Service._clientSideMonitoring)&&this.publisher){var o=this.publisher;this.addNamedListener("PUBLISH_API_CALL","apiCall",(function(e){n.nextTick((function(){o.eventHandler(e)}))})),this.addNamedListener("PUBLISH_API_ATTEMPT","apiCallAttempt",(function(e){n.nextTick((function(){o.eventHandler(e)}))}))}},validateService:function(){},loadServiceClass:function(e){var t=e;if(r.util.isEmpty(this.api)){if(t.apiConfig)return r.Service.defineServiceApi(this.constructor,t.apiConfig);if(this.constructor.services){(t=new r.Config(r.config)).update(e,!0);var n=t.apiVersions[this.constructor.serviceIdentifier];return n=n||t.apiVersion,this.getLatestServiceClass(n)}return null}return null},getLatestServiceClass:function(e){return e=this.getLatestServiceVersion(e),null===this.constructor.services[e]&&r.Service.defineServiceApi(this.constructor,e),this.constructor.services[e]},getLatestServiceVersion:function(e){if(!this.constructor.services||0===this.constructor.services.length)throw new Error("No services defined on "+this.constructor.serviceIdentifier);if(e?r.util.isType(e,Date)&&(e=r.util.date.iso8601(e).split("T")[0]):e="latest",Object.hasOwnProperty(this.constructor.services,e))return e;for(var t=Object.keys(this.constructor.services).sort(),n=null,o=t.length-1;o>=0;o--)if("*"!==t[o][t[o].length-1]&&(n=t[o]),t[o].substr(0,10)<=e)return n;throw new Error("Could not find "+this.constructor.serviceIdentifier+" API to satisfy version constraint `"+e+"'")},api:{},defaultRetryCount:3,customizeRequests:function(e){if(e){if("function"!=typeof e)throw new Error("Invalid callback type '"+typeof e+"' provided in customizeRequests");this.customRequestHandler=e}else this.customRequestHandler=null},makeRequest:function(e,t,n){if("function"==typeof t&&(n=t,t=null),t=t||{},this.config.params){var o=this.api.operations[e];o&&(t=r.util.copy(t),r.util.each(this.config.params,(function(e,n){o.input.members[e]&&(void 0!==t[e]&&null!==t[e]||(t[e]=n))})))}var i=new r.Request(this,e,t);return this.addAllRequestListeners(i),this.attachMonitoringEmitter(i),n&&i.send(n),i},makeUnauthenticatedRequest:function(e,t,n){"function"==typeof t&&(n=t,t={});var r=this.makeRequest(e,t).toUnauthenticated();return n?r.send(n):r},waitFor:function(e,t,n){return new r.ResourceWaiter(this,e).wait(t,n)},addAllRequestListeners:function(e){for(var t=[r.events,r.EventListeners.Core,this.serviceInterface(),r.EventListeners.CorePost],n=0;n299?(o.code&&(n.FinalAwsException=o.code),o.message&&(n.FinalAwsExceptionMessage=o.message)):((o.code||o.name)&&(n.FinalSdkException=o.code||o.name),o.message&&(n.FinalSdkExceptionMessage=o.message))}return n},apiAttemptEvent:function(e){var t=e.service.api.operations[e.operation],n={Type:"ApiCallAttempt",Api:t?t.name:e.operation,Version:1,Service:e.service.api.serviceId||e.service.api.endpointPrefix,Fqdn:e.httpRequest.endpoint.hostname,UserAgent:e.httpRequest.getUserAgent()},r=e.response;return r.httpResponse.statusCode&&(n.HttpStatusCode=r.httpResponse.statusCode),!e._unAuthenticated&&e.service.config.credentials&&e.service.config.credentials.accessKeyId&&(n.AccessKey=e.service.config.credentials.accessKeyId),r.httpResponse.headers?(e.httpRequest.headers["x-amz-security-token"]&&(n.SessionToken=e.httpRequest.headers["x-amz-security-token"]),r.httpResponse.headers["x-amzn-requestid"]&&(n.XAmznRequestId=r.httpResponse.headers["x-amzn-requestid"]),r.httpResponse.headers["x-amz-request-id"]&&(n.XAmzRequestId=r.httpResponse.headers["x-amz-request-id"]),r.httpResponse.headers["x-amz-id-2"]&&(n.XAmzId2=r.httpResponse.headers["x-amz-id-2"]),n):n},attemptFailEvent:function(e){var t=this.apiAttemptEvent(e),n=e.response,r=n.error;return n.httpResponse.statusCode>299?(r.code&&(t.AwsException=r.code),r.message&&(t.AwsExceptionMessage=r.message)):((r.code||r.name)&&(t.SdkException=r.code||r.name),r.message&&(t.SdkExceptionMessage=r.message)),t},attachMonitoringEmitter:function(e){var t,n,o,i,s,a,c=0,u=this;e.on("validate",(function(){i=r.util.realClock.now(),a=Date.now()}),!0),e.on("sign",(function(){n=r.util.realClock.now(),t=Date.now(),s=e.httpRequest.region,c++}),!0),e.on("validateResponse",(function(){o=Math.round(r.util.realClock.now()-n)})),e.addNamedListener("API_CALL_ATTEMPT","success",(function(){var n=u.apiAttemptEvent(e);n.Timestamp=t,n.AttemptLatency=o>=0?o:0,n.Region=s,u.emit("apiCallAttempt",[n])})),e.addNamedListener("API_CALL_ATTEMPT_RETRY","retry",(function(){var i=u.attemptFailEvent(e);i.Timestamp=t,o=o||Math.round(r.util.realClock.now()-n),i.AttemptLatency=o>=0?o:0,i.Region=s,u.emit("apiCallAttempt",[i])})),e.addNamedListener("API_CALL","complete",(function(){var t=u.apiCallEvent(e);if(t.AttemptCount=c,!(t.AttemptCount<=0)){t.Timestamp=a;var n=Math.round(r.util.realClock.now()-i);t.Latency=n>=0?n:0;var o=e.response;"number"==typeof o.retryCount&&"number"==typeof o.maxRetries&&o.retryCount>=o.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t])}}))},setupRequestListeners:function(e){},getSignerClass:function(e){var t,n=null,o="";return e&&(o=(n=(e.service.api.operations||{})[e.operation]||null)?n.authtype:""),t=this.config.signatureVersion?this.config.signatureVersion:"v4"===o||"v4-unsigned-body"===o?"v4":this.api.signatureVersion,r.Signers.RequestSigner.getVersion(t)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return r.EventListeners.Query;case"json":return r.EventListeners.Json;case"rest-json":return r.EventListeners.RestJson;case"rest-xml":return r.EventListeners.RestXml}if(this.api.protocol)throw new Error("Invalid service `protocol' "+this.api.protocol+" in API config")},successfulResponse:function(e){return e.httpResponse.statusCode<300},numRetries:function(){return void 0!==this.config.maxRetries?this.config.maxRetries:this.defaultRetryCount},retryDelays:function(e){return r.util.calculateRetryDelay(e,this.config.retryDelayOptions)},retryableError:function(e){return!!this.timeoutError(e)||!!this.networkingError(e)||!!this.expiredCredentialsError(e)||!!this.throttledError(e)||e.statusCode>=500},networkingError:function(e){return"NetworkingError"===e.code},timeoutError:function(e){return"TimeoutError"===e.code},expiredCredentialsError:function(e){return"ExpiredTokenException"===e.code},clockSkewError:function(e){switch(e.code){case"RequestTimeTooSkewed":case"RequestExpired":case"InvalidSignatureException":case"SignatureDoesNotMatch":case"AuthFailure":case"RequestInTheFuture":return!0;default:return!1}},getSkewCorrectedDate:function(){return new Date(Date.now()+this.config.systemClockOffset)},applyClockOffset:function(e){e&&(this.config.systemClockOffset=e-Date.now())},isClockSkewed:function(e){if(e)return Math.abs(this.getSkewCorrectedDate().getTime()-e)>=3e4},throttledError:function(e){if(429===e.statusCode)return!0;switch(e.code){case"ProvisionedThroughputExceededException":case"Throttling":case"ThrottlingException":case"RequestLimitExceeded":case"RequestThrottled":case"RequestThrottledException":case"TooManyRequestsException":case"TransactionInProgressException":return!0;default:return!1}},endpointFromTemplate:function(e){if("string"!=typeof e)return e;var t=e;return t=(t=(t=t.replace(/\{service\}/g,this.api.endpointPrefix)).replace(/\{region\}/g,this.config.region)).replace(/\{scheme\}/g,this.config.sslEnabled?"https":"http")},setEndpoint:function(e){this.endpoint=new r.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(!n){if(t){var o=new Error;throw r.util.error(o,"No pagination configuration for "+e)}return null}return n}}),r.util.update(r.Service,{defineMethods:function(e){r.util.each(e.prototype.api.operations,(function(t){e.prototype[t]||("none"===e.prototype.api.operations[t].authtype?e.prototype[t]=function(e,n){return this.makeUnauthenticatedRequest(t,e,n)}:e.prototype[t]=function(e,n){return this.makeRequest(t,e,n)})}))},defineService:function(e,t,n){r.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var o=s(r.Service,n||{});if("string"==typeof e){r.Service.addVersions(o,t);var i=o.serviceIdentifier||e;o.serviceIdentifier=i}else o.prototype.api=e,r.Service.defineMethods(o);if(r.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&r.util.clientSideMonitoring){var a=r.util.clientSideMonitoring.Publisher,c=(0,r.util.clientSideMonitoring.configProvider)();this.prototype.publisher=new a(c),c.enabled&&(r.Service._clientSideMonitoring=!0)}return r.SequentialExecutor.call(o.prototype),r.Service.addDefaultMonitoringListeners(o.prototype),o},addVersions:function(e,t){Array.isArray(t)||(t=[t]),e.services=e.services||{};for(var n=0;n=0))throw n.util.error(new Error,t);this.config.stsRegionalEndpoints=e.toLowerCase()},validateRegionalEndpointsFlag:function(){var e=this.config;if(e.stsRegionalEndpoints&&this.validateRegionalEndpointsFlagValue(e.stsRegionalEndpoints,{code:"InvalidConfiguration",message:'invalid "stsRegionalEndpoints" configuration. Expect "legacy" or "regional". Got "'+e.stsRegionalEndpoints+'".'}),n.util.isNode()){if(Object.prototype.hasOwnProperty.call(t.env,o)){var r=t.env.AWS_STS_REGIONAL_ENDPOINTS;this.validateRegionalEndpointsFlagValue(r,{code:"InvalidEnvironmentalVariable",message:'invalid AWS_STS_REGIONAL_ENDPOINTS environmental variable. Expect "legacy" or "regional". Got "'+t.env.AWS_STS_REGIONAL_ENDPOINTS+'".'})}var s={};try{s=n.util.getProfilesFromSharedConfig(n.util.iniLoader)[t.env.AWS_PROFILE||n.util.defaultProfile]}catch(e){}if(s&&Object.prototype.hasOwnProperty.call(s,i)){var a=s.sts_regional_endpoints;this.validateRegionalEndpointsFlagValue(a,{code:"InvalidConfiguration",message:'invalid sts_regional_endpoints profile config. Expect "legacy" or "regional". Got "'+s.sts_regional_endpoints+'".'})}}},optInRegionalEndpoint:function(){this.validateRegionalEndpointsFlag();var e=this.config;if("regional"===e.stsRegionalEndpoints){if(r(this),!this.isGlobalEndpoint)return;if(this.isGlobalEndpoint=!1,!e.region)throw n.util.error(new Error,{code:"ConfigError",message:"Missing region in config"});var t=e.endpoint.indexOf(".amazonaws.com");e.endpoint=e.endpoint.substring(0,t)+"."+e.region+e.endpoint.substring(t)}},validateService:function(){this.optInRegionalEndpoint()}})}).call(this)}).call(this,e("_process"))},{"../core":18,"../region_config":53,_process:86}],62:[function(e,t,n){var r=e("../core"),o=r.util.inherit,i="presigned-expires";function s(e){var t=e.httpRequest.headers[i],n=e.service.getSignerClass(e);if(delete e.httpRequest.headers["User-Agent"],delete e.httpRequest.headers["X-Amz-User-Agent"],n===r.Signers.V4){if(t>604800)throw r.util.error(new Error,{code:"InvalidExpiryTime",message:"Presigning does not support expiry time greater than a week with SigV4 signing.",retryable:!1});e.httpRequest.headers[i]=t}else{if(n!==r.Signers.S3)throw r.util.error(new Error,{message:"Presigning only supports S3 or SigV4 signing.",code:"UnsupportedSigner",retryable:!1});var o=e.service?e.service.getSkewCorrectedDate():r.util.date.getDate();e.httpRequest.headers[i]=parseInt(r.util.date.unixTimestamp(o)+t,10).toString()}}function a(e){var t=e.httpRequest.endpoint,n=r.util.urlParse(e.httpRequest.path),o={};n.search&&(o=r.util.queryStringParse(n.search.substr(1)));var s=e.httpRequest.headers.Authorization.split(" ");if("AWS"===s[0])s=s[1].split(":"),o.AWSAccessKeyId=s[0],o.Signature=s[1],r.util.each(e.httpRequest.headers,(function(e,t){e===i&&(e="Expires"),0===e.indexOf("x-amz-meta-")&&(delete o[e],e=e.toLowerCase()),o[e]=t})),delete e.httpRequest.headers[i],delete o.Authorization,delete o.Host;else if("AWS4-HMAC-SHA256"===s[0]){s.shift();var a=s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];o["X-Amz-Signature"]=a,delete o.Expires}t.pathname=n.pathname,t.search=r.util.queryParamsToString(o)}r.Signers.Presign=o({sign:function(e,t,n){if(e.httpRequest.headers[i]=t||3600,e.on("build",s),e.on("sign",a),e.removeListener("afterBuild",r.EventListeners.Core.SET_CONTENT_LENGTH),e.removeListener("afterBuild",r.EventListeners.Core.COMPUTE_SHA256),e.emit("beforePresign",[e]),!n){if(e.build(),e.response.error)throw e.response.error;return r.util.urlFormat(e.httpRequest.endpoint)}e.build((function(){this.response.error?n(this.response.error):n(null,r.util.urlFormat(e.httpRequest.endpoint))}))}}),t.exports=r.Signers.Presign},{"../core":18}],63:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.RequestSigner=o({constructor:function(e){this.request=e},setServiceClientId:function(e){this.serviceClientId=e},getServiceClientId:function(){return this.serviceClientId}}),r.Signers.RequestSigner.getVersion=function(e){switch(e){case"v2":return r.Signers.V2;case"v3":return r.Signers.V3;case"s3v4":case"v4":return r.Signers.V4;case"s3":return r.Signers.S3;case"v3https":return r.Signers.V3Https}throw new Error("Unknown signing version "+e)},e("./v2"),e("./v3"),e("./v3https"),e("./v4"),e("./s3"),e("./presign")},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.S3=o(r.Signers.RequestSigner,{subResources:{acl:1,accelerate:1,analytics:1,cors:1,lifecycle:1,delete:1,inventory:1,location:1,logging:1,metrics:1,notification:1,partNumber:1,policy:1,requestPayment:1,replication:1,restore:1,tagging:1,torrent:1,uploadId:1,uploads:1,versionId:1,versioning:1,versions:1,website:1},responseHeaders:{"response-content-type":1,"response-content-language":1,"response-expires":1,"response-cache-control":1,"response-content-disposition":1,"response-content-encoding":1},addAuthorization:function(e,t){this.request.headers["presigned-expires"]||(this.request.headers["X-Amz-Date"]=r.util.date.rfc822(t)),e.sessionToken&&(this.request.headers["x-amz-security-token"]=e.sessionToken);var n=this.sign(e.secretAccessKey,this.stringToSign()),o="AWS "+e.accessKeyId+":"+n;this.request.headers.Authorization=o},stringToSign:function(){var e=this.request,t=[];t.push(e.method),t.push(e.headers["Content-MD5"]||""),t.push(e.headers["Content-Type"]||""),t.push(e.headers["presigned-expires"]||"");var n=this.canonicalizedAmzHeaders();return n&&t.push(n),t.push(this.canonicalizedResource()),t.join("\n")},canonicalizedAmzHeaders:function(){var e=[];r.util.each(this.request.headers,(function(t){t.match(/^x-amz-/i)&&e.push(t)})),e.sort((function(e,t){return e.toLowerCase()=0?"&":"?";this.request.path+=i+r.util.queryParamsToString(o)},authorization:function(e,t){var n=[],r=this.credentialString(t);return n.push(this.algorithm+" Credential="+e.accessKeyId+"/"+r),n.push("SignedHeaders="+this.signedHeaders()),n.push("Signature="+this.signature(e,t)),n.join(", ")},signature:function(e,t){var n=o.getSigningKey(e,t.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return r.util.crypto.hmac(n,this.stringToSign(t),"hex")},stringToSign:function(e){var t=[];return t.push("AWS4-HMAC-SHA256"),t.push(e),t.push(this.credentialString(e)),t.push(this.hexEncodedHash(this.canonicalString())),t.join("\n")},canonicalString:function(){var e=[],t=this.request.pathname();return"s3"!==this.serviceName&&"s3v4"!==this.signatureVersion&&(t=r.util.uriEscapePath(t)),e.push(this.request.method),e.push(t),e.push(this.request.search()),e.push(this.canonicalHeaders()+"\n"),e.push(this.signedHeaders()),e.push(this.hexEncodedBodyHash()),e.join("\n")},canonicalHeaders:function(){var e=[];r.util.each.call(this,this.request.headers,(function(t,n){e.push([t,n])})),e.sort((function(e,t){return e[0].toLowerCase()50&&delete o[i.shift()]),h},emptyCache:function(){o={},i=[]}}},{"../core":18}],70:[function(e,t,n){function r(e,t){this.currentState=t||null,this.states=e||{}}r.prototype.runTo=function(e,t,n,r){"function"==typeof e&&(r=n,n=t,t=e,e=null);var o=this,i=o.states[o.currentState];i.fn.call(n||o,r,(function(r){if(r){if(!i.fail)return t?t.call(n,r):null;o.currentState=i.fail}else{if(!i.accept)return t?t.call(n):null;o.currentState=i.accept}if(o.currentState===e)return t?t.call(n,r):null;o.runTo(e,t,n,r)}))},r.prototype.addState=function(e,t,n,r){return"function"==typeof t?(r=t,t=null,n=null):"function"==typeof n&&(r=n,n=null),this.currentState||(this.currentState=e),this.states[e]={accept:t,fail:n,fn:r},this},t.exports=r},{}],71:[function(e,t,n){(function(n,r){(function(){var o,i={environment:"nodejs",engine:function(){if(i.isBrowser()&&"undefined"!=typeof navigator)return navigator.userAgent;var e=n.platform+"/"+n.version;return n.env.AWS_EXECUTION_ENV&&(e+=" exec-env/"+n.env.AWS_EXECUTION_ENV),e},userAgent:function(){var t=i.environment,n="aws-sdk-"+t+"/"+e("./core").VERSION;return"nodejs"===t&&(n+=" "+i.engine()),n},uriEscape:function(e){var t=encodeURIComponent(e);return t=(t=t.replace(/[^A-Za-z0-9_.~\-%]+/g,escape)).replace(/[*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))},uriEscapePath:function(e){var t=[];return i.arrayEach(e.split("/"),(function(e){t.push(i.uriEscape(e))})),t.join("/")},urlParse:function(e){return i.url.parse(e)},urlFormat:function(e){return i.url.format(e)},queryStringParse:function(e){return i.querystring.parse(e)},queryParamsToString:function(e){var t=[],n=i.uriEscape,r=Object.keys(e).sort();return i.arrayEach(r,(function(r){var o=e[r],s=n(r),a=s+"=";if(Array.isArray(o)){var c=[];i.arrayEach(o,(function(e){c.push(n(e))})),a=s+"="+c.sort().join("&"+s+"=")}else null!=o&&(a=s+"="+n(o));t.push(a)})),t.join("&")},readFileSync:function(t){return i.isBrowser()?null:e("fs").readFileSync(t,"utf-8")},base64:{encode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 encode number "+e));return null==e?e:i.buffer.toBuffer(e).toString("base64")},decode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 decode number "+e));return null==e?e:i.buffer.toBuffer(e,"base64")}},buffer:{toBuffer:function(e,t){return"function"==typeof i.Buffer.from&&i.Buffer.from!==Uint8Array.from?i.Buffer.from(e,t):new i.Buffer(e,t)},alloc:function(e,t,n){if("number"!=typeof e)throw new Error("size passed to alloc must be a number.");if("function"==typeof i.Buffer.alloc)return i.Buffer.alloc(e,t,n);var r=new i.Buffer(e);return void 0!==t&&"function"==typeof r.fill&&r.fill(t,void 0,void 0,n),r},toStream:function(e){i.Buffer.isBuffer(e)||(e=i.buffer.toBuffer(e));var t=new i.stream.Readable,n=0;return t._read=function(r){if(n>=e.length)return t.push(null);var o=n+r;o>e.length&&(o=e.length),t.push(e.slice(n,o)),n=o},t},concat:function(e){var t,n,r=0,o=0;for(n=0;n>>8^t[255&(n^e.readUInt8(r))];return(-1^n)>>>0},hmac:function(e,t,n,r){return n||(n="binary"),"buffer"===n&&(n=void 0),r||(r="sha256"),"string"==typeof t&&(t=i.buffer.toBuffer(t)),i.crypto.lib.createHmac(r,e).update(t).digest(n)},md5:function(e,t,n){return i.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return i.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,r){var o=i.crypto.createHash(e);n||(n="binary"),"buffer"===n&&(n=void 0),"string"==typeof t&&(t=i.buffer.toBuffer(t));var s=i.arraySliceFn(t),a=i.Buffer.isBuffer(t);if(i.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(a=!0),r&&"object"==typeof t&&"function"==typeof t.on&&!a)t.on("data",(function(e){o.update(e)})),t.on("error",(function(e){r(e)})),t.on("end",(function(){r(null,o.digest(n))}));else{if(!r||!s||a||"undefined"==typeof FileReader){i.isBrowser()&&"object"==typeof t&&!a&&(t=new i.Buffer(new Uint8Array(t)));var c=o.update(t).digest(n);return r&&r(null,c),c}var u=0,l=new FileReader;l.onerror=function(){r(new Error("Failed to read data."))},l.onload=function(){var e=new i.Buffer(new Uint8Array(l.result));o.update(e),u+=e.length,l._continueReading()},l._continueReading=function(){if(u>=t.size)r(null,o.digest(n));else{var e=u+524288;e>t.size&&(e=t.size),l.readAsArrayBuffer(s.call(t,u,e))}},l._continueReading()}},toHex:function(e){for(var t=[],n=0;n=3e5,!1),o.config.isClockSkewed},applyClockOffset:function(e){e&&(o.config.systemClockOffset=e-(new Date).getTime())},extractRequestId:function(e){var t=e.httpResponse.headers["x-amz-request-id"]||e.httpResponse.headers["x-amzn-requestid"];!t&&e.data&&e.data.ResponseMetadata&&(t=e.data.ResponseMetadata.RequestId),t&&(e.requestId=t),e.error&&(e.error.requestId=t)},addPromises:function(e,t){var n=!1;void 0===t&&o&&o.config&&(t=o.config.getPromisesDependency()),void 0===t&&"undefined"!=typeof Promise&&(t=Promise),"function"!=typeof t&&(n=!0),Array.isArray(e)||(e=[e]);for(var r=0;r=500||429===r});o&&s.retryable&&(s.retryAfter=o),c(s)}}))}),c)};o.util.defer(u)},uuid:{v4:function(){return e("uuid").v4()}},convertPayloadToString:function(e){var t=e.request,n=t.operation,r=t.service.api.operations[n].output||{};r.payload&&e.data[r.payload]&&(e.data[r.payload]=e.data[r.payload].toString())},defer:function(e){"object"==typeof n&&"function"==typeof n.nextTick?n.nextTick(e):"function"==typeof r?r(e):setTimeout(e,0)},getRequestPayloadShape:function(e){var t=e.service.api.operations;if(t){var n=(t||{})[e.operation];if(n&&n.input&&n.input.payload)return n.input.members[n.input.payload]}},getProfilesFromSharedConfig:function(e,t){var r={},o={};n.env[i.configOptInEnv]&&(o=e.loadFrom({isConfig:!0,filename:n.env[i.sharedConfigFileEnv]}));for(var s=e.loadFrom({filename:t||n.env[i.configOptInEnv]&&n.env[i.sharedCredentialsFileEnv]}),a=0,c=Object.keys(o);a0||r?i.toString():""},t.exports=s},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(e,t,n){t.exports={escapeAttribute:function(e){return e.replace(/&/g,"&").replace(/'/g,"'").replace(//g,">").replace(/"/g,""")}}},{}],75:[function(e,t,n){t.exports={escapeElement:function(e){return e.replace(/&/g,"&").replace(//g,">")}}},{}],76:[function(e,t,n){var r=e("./escape-attribute").escapeAttribute;function o(e,t){void 0===t&&(t=[]),this.name=e,this.children=t,this.attributes={}}o.prototype.addAttribute=function(e,t){return this.attributes[e]=t,this},o.prototype.addChildNode=function(e){return this.children.push(e),this},o.prototype.removeAttribute=function(e){return delete this.attributes[e],this},o.prototype.toString=function(){for(var e=Boolean(this.children.length),t="<"+this.name,n=this.attributes,o=0,i=Object.keys(n);o"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},t.exports={XmlNode:o}},{"./escape-attribute":74}],77:[function(e,t,n){var r=e("./escape-element").escapeElement;function o(e){this.value=e}o.prototype.toString=function(){return r(""+this.value)},t.exports={XmlText:o}},{"./escape-element":75}],78:[function(e,t,n){"use strict";n.byteLength=function(e){var t=u(e),n=t[0],r=t[1];return 3*(n+r)/4-r},n.toByteArray=function(e){var t,n,r=u(e),s=r[0],a=r[1],c=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),l=0,p=a>0?s-4:s;for(n=0;n>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===a&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[l++]=255&t),1===a&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},n.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],s=16383,a=0,c=n-o;ac?c:a+s));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var o,i,s=[],a=t;a>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],79:[function(e,t,n){},{}],80:[function(e,t,o){(function(e){(function(){!function(i){"object"==typeof o&&o&&o.nodeType,"object"==typeof t&&t&&t.nodeType;var s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self;var a,c=2147483647,u=36,l=/^xn--/,p=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,h={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function m(e){throw RangeError(h[e])}function v(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function y(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+v((e=e.replace(d,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=g((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=g(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function C(e,t,n){var r=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;r+=u)e=f(e/35);return f(r+36*e/(e+38))}function T(e){var t,n,r,o,i,s,a,l,p,d,h,g=[],v=e.length,y=0,E=128,b=72;for((n=e.lastIndexOf("-"))<0&&(n=0),r=0;r=128&&m("not-basic"),g.push(e.charCodeAt(r));for(o=n>0?n+1:0;o=v&&m("invalid-input"),((l=(h=e.charCodeAt(o++))-48<10?h-22:h-65<26?h-65:h-97<26?h-97:u)>=u||l>f((c-y)/s))&&m("overflow"),y+=l*s,!(l<(p=a<=b?1:a>=b+26?26:a-b));a+=u)s>f(c/(d=u-p))&&m("overflow"),s*=d;b=C(y-i,t=g.length+1,0==i),f(y/t)>c-E&&m("overflow"),E+=f(y/t),y%=t,g.splice(y++,0,E)}return S(g)}function I(e){var t,n,r,o,i,s,a,l,p,d,h,v,y,S,T,I=[];for(v=(e=E(e)).length,t=128,n=0,i=72,s=0;s=t&&hf((c-n)/(y=r+1))&&m("overflow"),n+=(a-t)*y,t=a,s=0;sc&&m("overflow"),h==t){for(l=n,p=u;!(l<(d=p<=i?1:p>=i+26?26:p-i));p+=u)T=l-d,S=u-d,I.push(g(b(d+T%S,0))),l=f(T/S);I.push(g(b(l,0))),i=C(n,y,r==o),n=0,++r}++n,++t}return I.join("")}a={version:"1.3.2",ucs2:{decode:E,encode:S},decode:T,encode:I,toASCII:function(e){return y(e,(function(e){return p.test(e)?"xn--"+I(e):e}))},toUnicode:function(e){return y(e,(function(e){return l.test(e)?T(e.slice(4).toLowerCase()):e}))}},void 0===(r=function(){return a}.call(o,n,o,t))||(t.exports=r)}()}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(e,t,r){(function(t,n){(function(){"use strict";var n=e("base64-js"),o=e("ieee754"),i=e("isarray");function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function f(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function v(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=n;ia&&(n=a-c),i=n;i>=0;i--){for(var p=!0,d=0;do&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:u>223?3:u>191?2:1;if(o+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,p=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),o+=p}return function(e){var t=e.length;if(t<=w)return String.fromCharCode.apply(String,e);for(var n="",r=0;r0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,r,o){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),a=Math.min(i,s),u=this.slice(r,o),l=e.slice(t,n),p=0;po)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return C(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var w=4096;function R(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;oo)&&(n=o);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function P(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function x(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function M(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||M(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,i){return i||M(e,0,n,8),o.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},c.prototype.readUInt8=function(e,t){return t||L(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||L(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||L(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||L(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||L(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||L(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||L(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||L(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||L(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||D(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function j(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"base64-js":78,buffer:81,ieee754:83,isarray:84}],82:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function o(e){return"function"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,a,c,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(s(n=this._events[e]))return!1;if(o(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(i(n))for(a=Array.prototype.slice.call(arguments,1),r=(u=n.slice()).length,c=0;c0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){if(!o(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var n,r,s,a;if(!o(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(n=this._events[e]).length,r=-1,n===t||o(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){r=a;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(o(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?o(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(o(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],83:[function(e,t,n){n.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<>1,l=-7,p=n?o-1:0,d=n?-1:1,h=e[t+p];for(p+=d,i=h&(1<<-l)-1,h>>=-l,l+=a;l>0;i=256*i+e[t+p],p+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+p],p+=d,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),i-=u}return(h?-1:1)*s*Math.pow(2,i-r)},n.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+p>=1?d/c:d*Math.pow(2,1-p))*c>=2&&(s++,c/=2),s+p>=l?(a=0,s=l):s+p>=1?(a=(t*c-1)*Math.pow(2,o),s+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;e[n+h]=255&a,h+=f,a/=256,o-=8);for(s=s<0;e[n+h]=255&s,h+=f,s/=256,u-=8);e[n+h-f]|=128*g}},{}],84:[function(e,t,n){var r={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},{}],85:[function(e,t,n){!function(e){"use strict";function t(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e,o){if(e===o)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(o))return!1;if(!0===t(e)){if(e.length!==o.length)return!1;for(var i=0;i":!0,"=":!0,"!":!0},q={" ":!0,"\t":!0,"\n":!0};function B(e){return e>="0"&&e<="9"||"-"===e}function j(){}j.prototype={tokenize:function(e){var t,n,r,o,i=[];for(this._current=0;this._current="a"&&o<="z"||o>="A"&&o<="Z"||"_"===o)t=this._current,n=this._consumeUnquotedIdentifier(e),i.push({type:u,value:n,start:t});else if(void 0!==U[e[this._current]])i.push({type:U[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(B(e[this._current]))r=this._consumeNumber(e),i.push(r);else if("["===e[this._current])r=this._consumeLBracket(e),i.push(r);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),i.push({type:l,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),i.push({type:M,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);i.push({type:M,value:s,start:t})}else if(void 0!==F[e[this._current]])i.push(this._consumeOperator(e));else if(void 0!==q[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,i.push({type:b,value:"&&",start:t})):i.push({type:y,value:"&",start:t});else{if("|"!==e[this._current]){var a=new Error("Unknown character:"+e[this._current]);throw a.name="LexerError",a}t=this._current,this._current++,"|"===e[this._current]?(this._current++,i.push({type:S,value:"||",start:t})):i.push({type:E,value:"|",start:t})}return i},_consumeUnquotedIdentifier:function(e){var t,n=this._current;for(this._current++;this._current="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t);)this._current++;return e.slice(n,this._current)},_consumeQuotedIdentifier:function(e){var t=this._current;this._current++;for(var n=e.length;'"'!==e[this._current]&&this._current"===n?"="===e[this._current]?(this._current++,{type:_,value:">=",start:t}):{type:T,value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:C,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,n=this._current,r=e.length;"`"!==e[this._current]&&this._current=0)return!0;if(["true","false","null"].indexOf(e)>=0)return!0;if(!("-0123456789".indexOf(e[0])>=0))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var V={};function H(){}function W(e){this.runtime=e}function G(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[s]}]},avg:{_func:this._functionAvg,_signature:[{types:[8]}]},ceil:{_func:this._functionCeil,_signature:[{types:[s]}]},contains:{_func:this._functionContains,_signature:[{types:[a,3]},{types:[1]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[a]},{types:[a]}]},floor:{_func:this._functionFloor,_signature:[{types:[s]}]},length:{_func:this._functionLength,_signature:[{types:[a,3,4]}]},map:{_func:this._functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this._functionMax,_signature:[{types:[8,9]}]},merge:{_func:this._functionMerge,_signature:[{types:[4],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[3]},{types:[6]}]},sum:{_func:this._functionSum,_signature:[{types:[8]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[a]},{types:[a]}]},min:{_func:this._functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[3]},{types:[6]}]},type:{_func:this._functionType,_signature:[{types:[1]}]},keys:{_func:this._functionKeys,_signature:[{types:[4]}]},values:{_func:this._functionValues,_signature:[{types:[4]}]},sort:{_func:this._functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[3]},{types:[6]}]},join:{_func:this._functionJoin,_signature:[{types:[a]},{types:[9]}]},reverse:{_func:this._functionReverse,_signature:[{types:[a,3]}]},to_array:{_func:this._functionToArray,_signature:[{types:[1]}]},to_string:{_func:this._functionToString,_signature:[{types:[1]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[1]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[1],variadic:!0}]}}}V.EOF=0,V.UnquotedIdentifier=0,V.QuotedIdentifier=0,V.Rbracket=0,V.Rparen=0,V.Comma=0,V.Rbrace=0,V.Number=0,V.Current=0,V.Expref=0,V.Pipe=1,V.Or=2,V.And=3,V.EQ=5,V.GT=5,V.LT=5,V.GTE=5,V.LTE=5,V.NE=5,V.Flatten=9,V.Star=20,V.Filter=21,V.Dot=40,V.Not=45,V.Lbrace=50,V.Lbracket=55,V.Lparen=60,H.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)!==c){var n=this._lookaheadToken(0),r=new Error("Unexpected token type: "+n.type+", value: "+n.value);throw r.name="ParserError",r}return t},_loadTokens:function(e){var t=(new j).tokenize(e);t.push({type:c,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),r=this._lookahead(0);e=0?this.expression(e):t===P?(this._match(P),this._parseMultiselectList()):t===D?(this._match(D),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(V[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===P)t=this.expression(e);else if(this._lookahead(0)===k)t=this.expression(e);else{if(this._lookahead(0)!==O){var n=this._lookaheadToken(0),r=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw r.name="ParserError",r}this._match(O),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==p;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===h&&(this._match(h),this._lookahead(0)===p))throw new Error("Unexpected token Rbracket")}return this._match(p),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,n,r=[],o=[u,l];;){if(e=this._lookaheadToken(0),o.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(f),n={type:"KeyValuePair",name:t,value:this.expression(0)},r.push(n),this._lookahead(0)===h)this._match(h);else if(this._lookahead(0)===g){this._match(g);break}}return{type:"MultiSelectHash",children:r}}},W.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,i){var s,a,c,u,l,p,d,h,f;switch(e.type){case"Field":return null===i?null:n(i)?void 0===(p=i[e.name])?null:p:null;case"Subexpression":for(c=this.visit(e.children[0],i),f=1;f0)for(f=b;fN;f+=k)c.push(i[f]);return c;case"Projection":var O=this.visit(e.children[0],i);if(!t(O))return null;for(h=[],f=0;fl;break;case _:c=u>=l;break;case I:c=u=e&&(t=n<0?e-1:e),t}},G.prototype={callFunction:function(e,t){var n=this.functionTable[e];if(void 0===n)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,n._signature),n._func.call(this,t)},_validateArgs:function(e,t,n){var r,o,i,s;if(n[n.length-1].variadic){if(t.length=0;r--)n+=t[r];return n}var o=e[0].slice(0);return o.reverse(),o},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,n=e[0],r=0;r=0},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return n(e[0])?Object.keys(e[0]).length:e[0].length},_functionMap:function(e){for(var t=[],n=this._interpreter,r=e[0],o=e[1],i=0;i0){if(this._getTypeName(e[0][0])===s)return Math.max.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;r0){if(this._getTypeName(e[0][0])===s)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;ra?1:sc&&(c=n,t=o[u]);return t},_functionMinBy:function(e){for(var t,n,r=e[1],o=e[0],i=this.createKeyFunction(r,[s,a]),c=1/0,u=0;u1)for(var n=1;n0&&u>c&&(u=c);for(var l=0;l=0?(p=g.substr(0,m),d=g.substr(m+1)):(p=g,d=""),h=decodeURIComponent(p),f=decodeURIComponent(d),r(s,h)?o(s[h])?s[h].push(f):s[h]=[s[h],f]:s[h]=f}return s};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],88:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?i(s(e),(function(s){var a=encodeURIComponent(r(s))+n;return o(e[s])?i(e[s],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[s]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r0&&c>a&&(c=a);for(var u=0;u=0?(l=f.substr(0,g),p=f.substr(g+1)):(l=f,p=""),d=decodeURIComponent(l),h=decodeURIComponent(p),r(i,d)?Array.isArray(i[d])?i[d].push(h):i[d]=[i[d],h]:i[d]=h}return i}},{}],91:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,o){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map((function(o){var i=encodeURIComponent(r(o))+n;return Array.isArray(e[o])?e[o].map((function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):o?encodeURIComponent(r(o))+n+encodeURIComponent(r(e)):""}},{}],92:[function(e,t,n){arguments[4][89][0].apply(n,arguments)},{"./decode":90,"./encode":91,dup:89}],93:[function(e,t,n){(function(t,r){(function(){var o=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,a={},c=0;function u(e,t){this._id=e,this._clearFn=t}n.setTimeout=function(){return new u(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new u(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(e){e.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},n.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},n._unrefActive=n.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n.setImmediate="function"==typeof t?t:function(e){var t=c++,r=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,o((function(){a[t]&&(r?e.apply(null,r):e.call(null),n.clearImmediate(t))})),t},n.clearImmediate="function"==typeof r?r:function(e){delete a[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":86,timers:93}],94:[function(e,t,n){var r=e("punycode");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=v,n.resolve=function(e,t){return v(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},n.format=function(e){return y(e)&&(e=v(e)),e instanceof o?e.format():o.prototype.format.call(e)},n.Url=o;var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,a=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(a),u=["%","/","?",";","#"].concat(c),l=["/","?","#"],p=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,h={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},m=e("querystring");function v(e,t,n){if(e&&E(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function y(e){return"string"==typeof e}function E(e){return"object"==typeof e&&null!==e}function S(e){return null===e}o.prototype.parse=function(e,t,n){if(!y(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e;o=o.trim();var s=i.exec(o);if(s){var a=(s=s[0]).toLowerCase();this.protocol=a,o=o.substr(s.length)}if(n||s||o.match(/^\/\/[^@\/]+@[^@\/]+/)){var v="//"===o.substr(0,2);!v||s&&f[s]||(o=o.substr(2),this.slashes=!0)}if(!f[s]&&(v||s&&!g[s])){for(var E,S,b=-1,C=0;C127?R+="x":R+=w[N];if(!R.match(p)){var O=_.slice(0,C),L=_.slice(C+1),D=w.match(d);D&&(O.push(D[1]),L.unshift(D[2])),L.length&&(o="/"+L.join(".")+o),this.hostname=O.join(".");break}}}if(this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),!I){var P=this.hostname.split("."),x=[];for(C=0;C0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),n.search=e.search,n.query=e.query,S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!p.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var h=p.slice(-1)[0],m=(n.host||e.host)&&("."===h||".."===h)||""===h,v=0,E=p.length;E>=0;E--)"."==(h=p[E])?p.splice(E,1):".."===h?(p.splice(E,1),v++):v&&(p.splice(E,1),v--);if(!u&&!l)for(;v--;v)p.unshift("..");!u||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),m&&"/"!==p.join("/").substr(-1)&&p.push("");var b,C=""===p[0]||p[0]&&"/"===p[0].charAt(0);return d&&(n.hostname=n.host=C?"":p.length?p.shift():"",(b=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),(u=u||n.host&&p.length)&&!C&&p.unshift(""),p.length?n.pathname=p.join("/"):(n.pathname=null,n.path=null),S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{punycode:80,querystring:89}],95:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],96:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],97:[function(e,t,r){(function(t,n){(function(){var o=/%[sdj%]/g;r.format=function(e){if(!v(e)){for(var t=[],n=0;n=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}})),c=r[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),f(t)?n.showHidden=t:t&&r._extend(n,t),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),l(n,e,n.depth)}function c(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function u(e,t){return e}function l(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var o=t.inspect(n,e);return v(o)||(o=l(e,o,n)),o}var i=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(v(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return m(t)?e.stylize(""+t,"number"):f(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,t);if(i)return i;var s=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),C(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return p(t);if(0===s.length){if(T(t)){var c=t.name?": "+t.name:"";return e.stylize("[Function"+c+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(b(t))return e.stylize(Date.prototype.toString.call(t),"date");if(C(t))return p(t)}var u,S="",I=!1,_=["{","}"];return h(t)&&(I=!0,_=["[","]"]),T(t)&&(S=" [Function"+(t.name?": "+t.name:"")+"]"),E(t)&&(S=" "+RegExp.prototype.toString.call(t)),b(t)&&(S=" "+Date.prototype.toUTCString.call(t)),C(t)&&(S=" "+p(t)),0!==s.length||I&&0!=t.length?n<0?E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=I?function(e,t,n,r,o){for(var i=[],s=0,a=t.length;s60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(u,S,_)):_[0]+S+_[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,r,o,i){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),R(r,o)||(s="["+o+"]"),a||(e.seen.indexOf(c.value)<0?(a=g(n)?l(e,c.value,null):l(e,c.value,n-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),y(s)){if(i&&o.match(/^\d+$/))return a;(s=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function h(e){return Array.isArray(e)}function f(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function v(e){return"string"==typeof e}function y(e){return void 0===e}function E(e){return S(e)&&"[object RegExp]"===I(e)}function S(e){return"object"==typeof e&&null!==e}function b(e){return S(e)&&"[object Date]"===I(e)}function C(e){return S(e)&&("[object Error]"===I(e)||e instanceof Error)}function T(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function _(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(y(i)&&(i=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!s[e])if(new RegExp("\\b"+e+"\\b","i").test(i)){var n=t.pid;s[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else s[e]=function(){};return s[e]},r.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=h,r.isBoolean=f,r.isNull=g,r.isNullOrUndefined=function(e){return null==e},r.isNumber=m,r.isString=v,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=y,r.isRegExp=E,r.isObject=S,r.isDate=b,r.isError=C,r.isFunction=T,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function w(){var e=new Date,t=[_(e.getHours()),_(e.getMinutes()),_(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){console.log("%s - %s",w(),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!S(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this)}).call(this,e("_process"),void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":96,_process:86,inherits:95}],98:[function(e,t,n){var r=e("./v1"),o=e("./v4"),i=o;i.v1=r,i.v4=o,t.exports=i},{"./v1":101,"./v4":102}],99:[function(e,t,n){for(var r=[],o=0;o<256;++o)r[o]=(o+256).toString(16).substr(1);t.exports=function(e,t){var n=t||0,o=r;return[o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]]].join("")}},{}],100:[function(e,t,n){var r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(r){var o=new Uint8Array(16);t.exports=function(){return r(o),o}}else{var i=new Array(16);t.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i}}},{}],101:[function(e,t,n){var r,o,i=e("./lib/rng"),s=e("./lib/bytesToUuid"),a=0,c=0;t.exports=function(e,t,n){var u=t&&n||0,l=t||[],p=(e=e||{}).node||r,d=void 0!==e.clockseq?e.clockseq:o;if(null==p||null==d){var h=i();null==p&&(p=r=[1|h[0],h[1],h[2],h[3],h[4],h[5]]),null==d&&(d=o=16383&(h[6]<<8|h[7]))}var f=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:c+1,m=f-a+(g-c)/1e4;if(m<0&&void 0===e.clockseq&&(d=d+1&16383),(m<0||f>a)&&void 0===e.nsecs&&(g=0),g>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=f,c=g,o=d;var v=(1e4*(268435455&(f+=122192928e5))+g)%4294967296;l[u++]=v>>>24&255,l[u++]=v>>>16&255,l[u++]=v>>>8&255,l[u++]=255&v;var y=f/4294967296*1e4&268435455;l[u++]=y>>>8&255,l[u++]=255&y,l[u++]=y>>>24&15|16,l[u++]=y>>>16&255,l[u++]=d>>>8|128,l[u++]=255&d;for(var E=0;E<6;++E)l[u+E]=p[E];return t||s(l)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(e,t,n){var r=e("./lib/rng"),o=e("./lib/bytesToUuid");t.exports=function(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[i+a]=s[a];return t||o(s)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var r=e("./utils/LRU"),o=function(){function e(e){void 0===e&&(e=1e3),this.maxSize=e,this.cache=new r.LRUCache(e)}return Object.defineProperty(e.prototype,"size",{get:function(){return this.cache.length},enumerable:!0,configurable:!0}),e.prototype.put=function(t,n){var r="string"!=typeof t?e.getKeyString(t):t,o=this.populateValue(n);this.cache.put(r,o)},e.prototype.get=function(t){var n="string"!=typeof t?e.getKeyString(t):t,r=Date.now(),o=this.cache.get(n);if(o)for(var i=0;i{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.ClientMethods=t.makeEnum(["getAgentSnapshot","putAgentState","getAgentStates","getDialableCountryCodes","getRoutingProfileQueues","getAgentPermissions","getAgentConfiguration","updateAgentConfiguration","acceptContact","createOutboundContact","createTaskContact","clearContact","completeContact","destroyContact","rejectContact","notifyContactIssue","updateContactAttributes","createAdditionalConnection","destroyConnection","holdConnection","resumeConnection","toggleActiveConnections","conferenceConnections","sendClientLogs","sendDigits","sendSoftphoneCallReport","sendSoftphoneCallMetrics","getEndpoints","getNewAuthToken","createTransport","muteParticipant","unmuteParticipant"]),t.AgentAppClientMethods={GET_CONTACT:"AgentAppService.Lcms.getContact",DELETE_SPEAKER:"AgentAppService.VoiceId.deleteSpeaker",ENROLL_BY_SESSION:"AgentAppService.VoiceId.enrollBySession",EVALUATE_SESSION:"AgentAppService.VoiceId.evaluateSession",DESCRIBE_SPEAKER:"AgentAppService.VoiceId.describeSpeaker",OPT_OUT_SPEAKER:"AgentAppService.VoiceId.optOutSpeaker",UPDATE_VOICE_ID_DATA:"AgentAppService.Lcms.updateVoiceIdData",DESCRIBE_SESSION:"AgentAppService.VoiceId.describeSession",UPDATE_SESSION:"AgentAppService.VoiceId.updateSession",START_VOICE_ID_SESSION:"AgentAppService.Nasa.startVoiceIdSession",LIST_INTEGRATION_ASSOCIATIONS:"AgentAppService.Acs.listIntegrationAssociations",START_CONTACT_RECORDING:"AgentAppService.Acs.StartContactRecording",STOP_CONTACT_RECORDING:"AgentAppService.Acs.StopContactRecording",SUSPEND_CONTACT_RECORDING:"AgentAppService.Acs.SuspendContactRecording",RESUME_CONTACT_RECORDING:"AgentAppService.Acs.ResumeContactRecording"},t.MasterMethods=t.makeEnum(["becomeMaster","checkMaster"]),t.TaskTemplatesClientMethods=t.makeEnum(["listTaskTemplates","getTaskTemplate","createTemplatedTask","updateContact"]);var n=function(){};n.EMPTY_CALLBACKS={success:function(){},failure:function(){}},n.prototype.call=function(e,r,o){t.assertNotNull(e,"method");var i=r||{},s=o||n.EMPTY_CALLBACKS;this._callImpl(e,i,s)},n.prototype._callImpl=function(e,n,r){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){if(r&&r.failure){var o=t.sprintf("No such method exists on NULL client: %s",e);r.failure(new t.ValueError(o),{message:o})}};var o=function(e,r,o){n.call(this),this.conduit=e,this.requestEvent=r,this.responseEvent=o,this._requestIdCallbacksMap={},this.conduit.onUpstream(o,t.hitch(this,this._handleResponse))};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._callImpl=function(e,n,r){var o=t.EventFactory.createRequest(this.requestEvent,e,n);this._requestIdCallbacksMap[o.requestId]=r,this.conduit.sendUpstream(o.event,o)},o.prototype._getCallbacksForRequest=function(e){var t=this._requestIdCallbacksMap[e]||null;return null!=t&&delete this._requestIdCallbacksMap[e],t},o.prototype._handleResponse=function(e){var t=this._getCallbacksForRequest(e.requestId);null!=t&&(e.err&&t.failure?t.failure(e.err,e.data):t.success&&t.success(e.data))};var i=function(e){o.call(this,e,t.EventType.API_REQUEST,t.EventType.API_RESPONSE)};(i.prototype=Object.create(o.prototype)).constructor=i;var s=function(e){o.call(this,e,t.EventType.MASTER_REQUEST,t.EventType.MASTER_RESPONSE)};(s.prototype=Object.create(o.prototype)).constructor=s;var a=function(e,r,o){t.assertNotNull(e,"authCookieName"),t.assertNotNull(r,"authToken"),t.assertNotNull(o,"endpoint"),n.call(this),this.endpointUrl=t.getUrlWithProtocol(o),this.authToken=r,this.authCookieName=e};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype._callImpl=function(e,n,r){var o=this,i={};i[o.authCookieName]=o.authToken;var s={method:"post",body:JSON.stringify(n||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(i)}};t.fetch(o.endpointUrl,s).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))};var c=function(e,r,o){t.assertNotNull(e,"authToken"),t.assertNotNull(r,"region"),n.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=r,this.authToken=e;var i=t.getBaseUrl(),s=o||(i.includes(".awsapps.com")?i+"/connect/api":i+"/api"),a=new AWS.Endpoint(s);this.client=new AWS.Connect({endpoint:a})};(c.prototype=Object.create(n.prototype)).constructor=c,c.prototype._callImpl=function(e,n,r){var o=this,i=t.getLog();if(t.contains(this.client,e))n=this._translateParams(e,n),i.trace("AWSClient: --\x3e Calling operation '%s'",e).sendInternalLogToServer(),this.client[e](n).on("build",(function(e){e.httpRequest.headers["X-Amz-Bearer"]=o.authToken})).send((function(n,o){try{if(n){if(n.code===t.CTIExceptions.UNAUTHORIZED_EXCEPTION)r.authFailure();else if(!r.accessDenied||n.code!==t.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==n.statusCode){var s={};if(s.type=n.code,s.message=n.message,s.stack=[],n.stack)try{Array.isArray(n.stack)?s.stack=n.stack:"object"==typeof n.stack?s.stack=[JSON.stringify(n.stack)]:"string"==typeof n.stack&&(s.stack=n.stack.split("\n"))}catch{}r.failure(s,o)}else r.accessDenied();i.trace("AWSClient: <-- Operation '%s' failed: %s",e,JSON.stringify(n)).sendInternalLogToServer()}else i.trace("AWSClient: <-- Operation '%s' succeeded.",e).withObject(o).sendInternalLogToServer(),r.success(o)}catch(n){t.getLog().error("Failed to handle AWS API request for method %s",e).withException(n).sendInternalLogToServer()}}));else{var s=t.sprintf("No such method exists on AWS client: %s",e);r.failure(new t.ValueError(s),{message:s})}},c.prototype._requiresAuthenticationParam=function(e){return e!==t.ClientMethods.COMPLETE_CONTACT&&e!==t.ClientMethods.CLEAR_CONTACT&&e!==t.ClientMethods.REJECT_CONTACT&&e!==t.ClientMethods.CREATE_TASK_CONTACT},c.prototype._translateParams=function(e,n){switch(e){case t.ClientMethods.UPDATE_AGENT_CONFIGURATION:n.configuration=this._translateAgentConfiguration(n.configuration);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:n.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(n.softphoneStreamStatistics);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:n.report=this._translateSoftphoneCallReport(n.report)}return this._requiresAuthenticationParam(e)&&(n.authentication={authToken:this.authToken}),n},c.prototype._translateAgentConfiguration=function(e){return{name:e.name,softphoneEnabled:e.softphoneEnabled,softphoneAutoAccept:e.softphoneAutoAccept,extension:e.extension,routingProfile:this._translateRoutingProfile(e.routingProfile),agentPreferences:e.agentPreferences}},c.prototype._translateRoutingProfile=function(e){return{name:e.name,routingProfileARN:e.routingProfileARN,defaultOutboundQueue:this._translateQueue(e.defaultOutboundQueue)}},c.prototype._translateQueue=function(e){return{queueARN:e.queueARN,name:e.name}},c.prototype._translateSoftphoneStreamStatistics=function(e){return e.forEach((function(e){"packetsCount"in e&&(e.packetCount=e.packetsCount,delete e.packetsCount)})),e},c.prototype._translateSoftphoneCallReport=function(e){return"handshakingTimeMillis"in e&&(e.handshakeTimeMillis=e.handshakingTimeMillis,delete e.handshakingTimeMillis),"preTalkingTimeMillis"in e&&(e.preTalkTimeMillis=e.preTalkingTimeMillis,delete e.preTalkingTimeMillis),"handshakingFailure"in e&&(e.handshakeFailure=e.handshakingFailure,delete e.handshakingFailure),"talkingTimeMillis"in e&&(e.talkTimeMillis=e.talkingTimeMillis,delete e.talkingTimeMillis),e.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(e.softphoneStreamStatistics),e};var u=function(e){if(t.assertNotNull(e,"endpoint"),n.call(this),e.includes("/task-templates"))this.endpointUrl=t.getUrlWithProtocol(e);else{var r=new AWS.Endpoint(e),o=e.includes(".awsapps.com")?"/connect":"";this.endpointUrl=t.getUrlWithProtocol(`${r.host}${o}/task-templates/api/ccp`)}};(u.prototype=Object.create(n.prototype)).constructor=u,u.prototype._callImpl=function(e,n,r){t.assertNotNull(e,"method"),t.assertNotNull(n,"params");var o={credentials:"include",method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","x-csrf-token":"csrf"}},i=n.instanceId,s=this.endpointUrl,a=t.TaskTemplatesClientMethods;switch(e){case a.LIST_TASK_TEMPLATES:if(s+=`/proxy/instance/${i}/task/template`,n.queryParams){const e=new URLSearchParams(n.queryParams).toString();e&&(s+=`?${e}`)}break;case a.GET_TASK_TEMPLATE:t.assertNotNull(n.templateParams,"params.templateParams");const r=t.assertNotNull(n.templateParams.id,"params.templateParams.id"),c=n.templateParams.version;s+=`/proxy/instance/${i}/task/template/${r}`,c&&(s+=`?snapshotVersion=${c}`);break;case a.CREATE_TEMPLATED_TASK:s+=`/${e}`,o.body=JSON.stringify(n),o.method="PUT";break;case a.UPDATE_CONTACT:s+=`/${e}`,o.body=JSON.stringify(n),o.method="POST"}t.fetch(s,o).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))},t.ClientBase=n,t.NullClient=r,t.UpstreamConduitClient=i,t.UpstreamConduitMasterClient=s,t.AWSClient=c,t.AgentAppClient=a,t.TaskTemplatesClient=u}()},895:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.core={},t.core.initialized=!1,t.version="2.2.0",t.DEFAULT_BATCH_SIZE=500;var n="Amazon Connect CCP",r="https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}",o="06919f4fd8ed324e",i="/auth/authorize",s="/connect/auth/authorize",a="IframeRefreshAttempts",c="IframeInitializationSuccess";function u(e){var t=e.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/gi);return t.length?t[0]:""}t.numberOfConnectedCCPs=0,t.numberOfConnectedCCPsInThisTab=0,t.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION=3,t.core.MAX_CTI_AUTH_RETRY_COUNT=10,t.core.ctiAuthRetryCount=0,t.core.authorizeTimeoutId=null,t.core.ctiTimeoutId=null,t.SessionStorageKeys=t.makeEnum(["tab_id","authorize_retry_count"]),t.core.checkNotInitialized=function(){t.core.initialized&&t.getLog().warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer()},t.core.init=function(e){t.core.eventBus=new t.EventBus,t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.initClient(e),t.core.initAgentAppClient(e),t.core.initTaskTemplatesClient(e),t.core.initialized=!0},t.core.initClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.region,"params.region"),o=e.endpoint||null;t.core.client=new t.AWSClient(n,r,o)},t.core.initAgentAppClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.authCookieName,"params.authCookieName"),o=t.assertNotNull(e.agentAppEndpoint,"params.agentAppEndpoint");t.core.agentAppClient=new t.AgentAppClient(r,n,o)},t.core.initTaskTemplatesClient=function(e){t.assertNotNull(e,"params");var n=e.taskTemplatesEndpoint||e.endpoint;t.assertNotNull(n,"taskTemplatesEndpoint"),t.core.taskTemplatesClient=new t.TaskTemplatesClient(n)},t.core.terminate=function(){t.core.client=new t.NullClient,t.core.agentAppClient=new t.NullClient,t.core.taskTemplatesClient=new t.NullClient,t.core.masterClient=new t.NullClient;var e=t.core.getEventBus();e&&e.unsubscribeAll(),t.core.bus=new t.EventBus,t.core.agentDataProvider=null,t.core.softphoneManager=null,t.core.upstream=null,t.core.keepaliveManager=null,t.agent.initialized=!1,t.core.initialized=!1},t.core.softphoneUserMediaStream=null,t.core.getSoftphoneUserMediaStream=function(){return t.core.softphoneUserMediaStream},t.core.setSoftphoneUserMediaStream=function(e){t.core.softphoneUserMediaStream=e},t.core.initRingtoneEngines=function(e){t.assertNotNull(e,"params");var n=function(e){t.assertNotNull(e,"ringtoneSettings"),t.assertNotNull(e.voice,"ringtoneSettings.voice"),t.assertTrue(e.voice.ringtoneUrl||e.voice.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"),t.assertNotNull(e.queue_callback,"ringtoneSettings.queue_callback"),t.assertTrue(e.queue_callback.ringtoneUrl||e.queue_callback.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"),t.core.ringtoneEngines={},t.agent((function(n){n.onRefresh((function(){t.ifMaster(t.MasterTopics.RINGTONE,(function(){e.voice.disabled||t.core.ringtoneEngines.voice||(t.core.ringtoneEngines.voice=new t.VoiceRingtoneEngine(e.voice),t.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer()),e.chat.disabled||t.core.ringtoneEngines.chat||(t.core.ringtoneEngines.chat=new t.ChatRingtoneEngine(e.chat),t.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer()),e.task.disabled||t.core.ringtoneEngines.task||(t.core.ringtoneEngines.task=new t.TaskRingtoneEngine(e.task),t.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer()),e.queue_callback.disabled||t.core.ringtoneEngines.queue_callback||(t.core.ringtoneEngines.queue_callback=new t.QueueCallbackRingtoneEngine(e.queue_callback),t.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer())}))}))})),l()},r=function(e,n){e.ringtone=e.ringtone||{},e.ringtone.voice=e.ringtone.voice||{},e.ringtone.queue_callback=e.ringtone.queue_callback||{},e.ringtone.chat=e.ringtone.chat||{disabled:!0},e.ringtone.task=e.ringtone.task||{disabled:!0},n.softphone&&(n.softphone.disableRingtone&&(e.ringtone.voice.disabled=!0,e.ringtone.queue_callback.disabled=!0),n.softphone.ringtoneUrl&&(e.ringtone.voice.ringtoneUrl=n.softphone.ringtoneUrl,e.ringtone.queue_callback.ringtoneUrl=n.softphone.ringtoneUrl)),n.chat&&(n.chat.disableRingtone&&(e.ringtone.chat.disabled=!0),n.chat.ringtoneUrl&&(e.ringtone.chat.ringtoneUrl=n.chat.ringtoneUrl)),n.ringtone&&(e.ringtone.voice=t.merge(e.ringtone.voice,n.ringtone.voice||{}),e.ringtone.queue_callback=t.merge(e.ringtone.queue_callback,n.ringtone.voice||{}),e.ringtone.chat=t.merge(e.ringtone.chat,n.ringtone.chat||{}))};r(e,e),t.isFramed()?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(t){this.unsubscribe(),r(e,t),n(e.ringtone)})):n(e.ringtone)};var l=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_RINGER_DEVICE,p)},p=function(e){if(0!==t.keys(t.core.ringtoneEngines).length&&e&&e.deviceId){var n=e.deviceId;for(var r in t.core.ringtoneEngines)t.core.ringtoneEngines[r].setOutputDevice(n);t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.RINGER_DEVICE_CHANGED,data:{deviceId:n}})}};t.core.initSoftphoneManager=function(e){t.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer();var n=e||{},r=function(e){var r=t.merge(n.softphone||{},e);t.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(),t.agent((function(e){e.getChannelConcurrency(t.ChannelType.VOICE)&&e.onRefresh((function(){var n=this;t.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(),t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(),!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),n.unsubscribe())}))}))}))};function o(e){var r=t.merge(n.softphone||{},e);t.core.softphoneParams=r,t.isFirefoxBrowser()&&(t.core.getUpstream().onUpstream(t.EventType.MASTER_RESPONSE,(function(e){if(e.data&&e.data.topic===t.MasterTopics.SOFTPHONE&&e.data.takeOver&&e.data.masterId!==t.core.portStreamId){t.core.softphoneManager&&(t.core.softphoneManager.onInitContactSub.unsubscribe(),delete t.core.softphoneManager);var n=t.core.getSoftphoneUserMediaStream();n&&(n.getTracks().forEach((function(e){e.stop()})),t.core.setSoftphoneUserMediaStream(null))}})),t.core.getEventBus().subscribe(t.ConnectionEvents.READY_TO_START_SESSION,(function(){t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.core.softphoneManager&&t.core.softphoneManager.startSession()}),(function(){t.becomeMaster(t.MasterTopics.SOFTPHONE,(function(){t.agent((function(e){!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),t.core.softphoneManager.startSession())}))}))}))})),t.contact((function(e){t.agent((function(n){e.onRefresh((function(e){if(t.hasOtherConnectedCCPs()&&"visible"===document.visibilityState&&(e.getStatus().type===t.ContactStatusType.CONNECTING||e.getStatus().type===t.ContactStatusType.INCOMING)){var r=e.isSoftphoneCall()&&!e.isInbound(),o=e.isSoftphoneCall()&&n.getConfiguration().softphoneAutoAccept,i=e.getType()===t.ContactType.QUEUE_CALLBACK;(r||o||i)&&t.core.triggerReadyToStartSessionEvent()}}))}))})))}t.isFramed()&&!n.allowFramedSoftphone?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(e){t.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(),e.softphone&&e.softphone.allowFramedSoftphone&&(this.unsubscribe(),r(e.softphone)),o(e.softphone)})):(r(n),o(n)),t.agent((function(e){e.isSoftphoneEnabled()&&e.getChannelConcurrency(t.ChannelType.VOICE)&&t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE})}))},t.core.triggerReadyToStartSessionEvent=function(){var e=t.core.softphoneParams&&t.core.softphoneParams.allowFramedSoftphone;t.isCCP()?e?t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):t.isFramed()?t.core.getUpstream().sendDownstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):e?t.core.getUpstream().sendUpstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION)},t.core.initPageOptions=function(e){if(t.assertNotNull(e,"params"),t.isFramed()){var n=t.core.getEventBus();n.subscribe(t.EventType.CONFIGURE,(function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.CONFIGURE,data:e})})),n.subscribe(t.EventType.MEDIA_DEVICE_REQUEST,(function(){function e(e){t.core.getUpstream().sendDownstream(t.EventType.MEDIA_DEVICE_RESPONSE,e)}navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})).catch((function(t){e({error:t.message})})):e({error:"No navigator or navigator.mediaDevices object found"})}))}},t.core.getFrameMediaDevices=function(e){var n=null,r=e||1e3,o=new Promise((function(e,t){setTimeout((function(){t(new Error("Timeout exceeded"))}),r)})),i=new Promise((function(e,r){if(t.isFramed()||t.isCCP())navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})):r(new Error("No navigator or navigator.mediaDevices object found"));else{var o=t.core.getEventBus();n=o.subscribe(t.EventType.MEDIA_DEVICE_RESPONSE,(function(t){t.error?r(new Error(t.error)):e(t)})),t.core.getUpstream().sendUpstream(t.EventType.MEDIA_DEVICE_REQUEST)}}));return Promise.race([i,o]).finally((function(){n&&n.unsubscribe()}))},t.core.authorize=function(e){var n=e;return n||(n=t.core.isLegacyDomain()?s:i),t.fetch(n,{credentials:"include"},2e3,5)},t.core.verifyDomainAccess=function(e,n){if(t.getLog().warn("This API will be deprecated in the next major version release"),!t.isFramed())return Promise.resolve();var r={headers:{"X-Amz-Bearer":e}},o=null;return o=n||(t.core.isLegacyDomain()?"/connect/whitelisted-origins":"/whitelisted-origins"),t.fetch(o,r,2e3,5).then((function(e){var t=u(window.document.referrer);return e.whitelistedOrigins.some((function(e){return t===u(e)}))?Promise.resolve():Promise.reject()}))},t.core.isLegacyDomain=function(e){return(e=e||window.location.href).includes(".awsapps.com")},t.core.initSharedWorker=function(n){if(t.core.checkNotInitialized(),!t.core.initialized){t.assertNotNull(n,"params");var r=t.assertNotNull(n.sharedWorkerUrl,"params.sharedWorkerUrl"),o=t.assertNotNull(n.authToken,"params.authToken"),a=t.assertNotNull(n.refreshToken,"params.refreshToken"),c=t.assertNotNull(n.authTokenExpiration,"params.authTokenExpiration"),u=t.assertNotNull(n.region,"params.region"),l=n.endpoint||null,p=n.authorizeEndpoint;p||(p=t.core.isLegacyDomain()?s:i);var d=n.agentAppEndpoint||null,g=n.taskTemplatesEndpoint||null,m=n.authCookieName||null;try{t.core.eventBus=new t.EventBus({logEvents:!0}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(n);var v=new SharedWorker(r,"ConnectSharedWorker"),y=new t.Conduit("ConnectSharedWorkerConduit",new t.PortStream(v.port),new t.WindowIOStream(window,parent));t.core.upstream=y,t.core.webSocketProvider=new h,e.onunload=function(){y.sendUpstream(t.EventType.CLOSE),v.port.close()},t.getLog().scheduleUpstreamLogPush(y),t.getLog().scheduleDownstreamClientSideLogsPush(),y.onAllUpstream(t.core.getEventBus().bridge()),y.onAllUpstream(y.passDownstream()),t.isFramed()&&(y.onAllDownstream(t.core.getEventBus().bridge()),y.onAllDownstream(y.passUpstream())),y.sendUpstream(t.EventType.CONFIGURE,{authToken:o,authTokenExpiration:c,endpoint:l,refreshToken:a,region:u,authorizeEndpoint:p,agentAppEndpoint:d,taskTemplatesEndpoint:g,authCookieName:m,longPollingOptions:n.longPollingOptions||void 0}),y.onUpstream(t.EventType.ACKNOWLEDGE,(function(e){t.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(),t.core.initialized=!0,t.core._setTabId(),t.core.portStreamId=e.id,this.unsubscribe()})),y.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),y.onUpstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))})),y.onDownstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.isFramed()&&Array.isArray(e)&&e.forEach((function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))}))})),y.onDownstream(t.EventType.LOG,(function(e){t.isFramed()&&e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.onAuthFail(t.hitch(t.core,t.core._handleAuthFail,n.loginEndpoint||null,p)),t.core.onAuthorizeSuccess(t.hitch(t.core,t.core._handleAuthorizeSuccess)),t.getLog().info("User Agent: "+navigator.userAgent).sendInternalLogToServer(),t.getLog().info("isCCPv2: "+!0).sendInternalLogToServer(),t.getLog().info("isFramed: "+t.isFramed()).sendInternalLogToServer(),t.core.upstream.onDownstream(t.EventType.OUTER_CONTEXT_INFO,(function(e){var n=e.streamsVersion;t.getLog().info("StreamsJS Version: "+n).sendInternalLogToServer()})),y.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.getLog().info("Number of connected CCPs updated: "+e.length).sendInternalLogToServer(),t.numberOfConnectedCCPs=e.length,e[t.core.tabId]&&!isNaN(e[t.core.tabId].length)&&t.numberOfConnectedCCPsInThisTab!==e[t.core.tabId].length&&(t.numberOfConnectedCCPsInThisTab=e[t.core.tabId].length,t.numberOfConnectedCCPsInThisTab>1&&t.getLog().warn("There are "+t.numberOfConnectedCCPsInThisTab+" connected CCPs in this tab. Please adjust your implementation to avoid complications. If you are embedding CCP, please do so exclusively with initCCP. InitCCP will not let you embed more than one CCP.").sendInternalLogToServer(),t.publishMetric({name:"ConnectedCCPSingleTabCount",data:{count:t.numberOfConnectedCCPsInThisTab}})),e.tabId&&e.streamsTabsAcrossBrowser&&t.ifMaster(t.MasterTopics.METRICS,(()=>t.agent((()=>t.publishMetric({name:"CCPTabsAcrossBrowserCount",data:{tabId:e.tabId,count:e.streamsTabsAcrossBrowser}})))))})),t.core.client=new t.UpstreamConduitClient(y),t.core.masterClient=new t.UpstreamConduitMasterClient(y),t.core.getEventBus().subscribe(t.EventType.TERMINATE,y.passUpstream()),t.core.getEventBus().subscribe(t.EventType.TERMINATED,(function(){window.location.reload(!0)})),v.port.start(),y.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.agent((function(){(new t.VoiceId).getDomainId().then((function(e){t.getLog().info("voiceId domainId successfully fetched at agent initialization: "+e).sendInternalLogToServer()})).catch((function(e){t.getLog().info("voiceId domainId not fetched at agent initialization").withObject({err:e}).sendInternalLogToServer()}))})),t.core.getNotificationManager().requestPermission()}catch(e){t.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer()}}},t.core._setTabId=function(){try{t.core.tabId=window.sessionStorage.getItem(t.SessionStorageKeys.TAB_ID),t.core.tabId||(t.core.tabId=t.randomId(),window.sessionStorage.setItem(t.SessionStorageKeys.TAB_ID,t.core.tabId)),t.core.upstream.sendUpstream(t.EventType.TAB_ID,{tabId:t.core.tabId})}catch(e){t.getLog().error("[Tab Id] There was an issue setting the tab Id").withException(e).sendInternalLogToServer()}},t.core.initCCP=function(n,i){if(t.core.checkNotInitialized(),!t.core.initialized){t.getLog().info("Iframe initialization started").sendInternalLogToServer();var s=Date.now();try{if(t.core._getCCPIframe())return void t.getLog().error("Attempted to call initCCP when an iframe generated by initCCP already exists").sendInternalLogToServer()}catch(e){t.getLog().error("Error while checking if initCCP has already been called").withException(e).sendInternalLogToServer()}var u={};"string"==typeof i?u.ccpUrl=i:u=i,t.assertNotNull(n,"containerDiv"),t.assertNotNull(u.ccpUrl,"params.ccpUrl");var l=t.core._createCCPIframe(n,u);t.core.eventBus=new t.EventBus({logEvents:!1}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(u);var p=new t.IFrameConduit(u.ccpUrl,window,l);t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(l,p),t.core.upstream=p,t.core.webSocketProvider=new h,p.onAllUpstream(t.core.getEventBus().bridge()),t.core.keepaliveManager=new d(p,t.core.getEventBus(),u.ccpSynTimeout||1e3,u.ccpAckTimeout||3e3),t.core.iframeRefreshTimeout=null,t.core.ccpLoadTimeoutInstance=e.setTimeout((function(){t.core.ccpLoadTimeoutInstance=null,t.core.getEventBus().trigger(t.EventType.ACK_TIMEOUT)}),u.ccpLoadTimeout||5e3),t.getLog().scheduleUpstreamOuterContextCCPLogsPush(p),t.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(p),p.onUpstream(t.EventType.ACKNOWLEDGE,(function(n){if(t.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(),t.core.client=new t.UpstreamConduitClient(p),t.core.masterClient=new t.UpstreamConduitMasterClient(p),t.core.portStreamId=n.id,(u.softphone||u.chat||u.pageOptions||u.shouldAddNamespaceToLogs)&&p.sendUpstream(t.EventType.CONFIGURE,{softphone:u.softphone,chat:u.chat,pageOptions:u.pageOptions,shouldAddNamespaceToLogs:u.shouldAddNamespaceToLogs}),t.core.ccpLoadTimeoutInstance&&(e.clearTimeout(t.core.ccpLoadTimeoutInstance),t.core.ccpLoadTimeoutInstance=null),p.sendUpstream(t.EventType.OUTER_CONTEXT_INFO,{streamsVersion:t.version}),t.core.keepaliveManager.start(),this.unsubscribe(),t.core.initialized=!0,t.core.getEventBus().trigger(t.EventType.INIT),s){var r=Date.now()-s,o=t.core.iframeRefreshAttempt||0;t.getLog().info("Iframe initialization succeeded").sendInternalLogToServer(),t.getLog().info(`Iframe initialization time ${r}`).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${o}`).sendInternalLogToServer(),setTimeout((()=>{t.publishMetric({name:a,data:{count:o}}),t.publishMetric({name:c,data:{count:1}}),t.publishMetric({name:"IframeInitializationTime",data:{count:r}}),s=null}),1e3)}})),p.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.getEventBus().subscribe(t.EventType.ACK_TIMEOUT,(function(){if(!1!==u.loginPopup)try{var i=function(n){var i="https://lily.us-east-1.amazonaws.com/taw/auth/code";return t.assertNotNull(i),n.loginUrl?n.loginUrl:n.alias?(log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."),r.replace("{alias}",n.alias).replace("{client_id}",o).replace("{redirect}",e.encodeURIComponent(i))):n.ccpUrl}(u);t.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(),u.loginUrl&&t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),t.core.loginWindow=t.core.getPopupManager().open(i,t.MasterTopics.LOGIN_POPUP,u.loginOptions)}catch(e){t.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer()}if(null==t.core.iframeRefreshTimeout)try{p.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=null,t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),(u.loginPopupAutoClose||u.loginOptions&&u.loginOptions.autoClose)&&t.core.loginWindow&&(t.core.loginWindow.close(),t.core.loginWindow=null)})),t.core._refreshIframeOnTimeout(u,n)}catch(e){t.getLog().error("Error occurred while refreshing iframe").withException(e).sendInternalLogToServer()}})),u.onViewContact&&t.core.onViewContact(u.onViewContact),p.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.numberOfConnectedCCPs=e.length})),p.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,(function(){if(s){var e=t.core.iframeRefreshAttempt-1;t.getLog().info("Iframe initialization failed").sendInternalLogToServer(),t.getLog().info("Time after iframe initialization started "+(Date.now()-s)).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${e}`).sendInternalLogToServer(),t.publishMetric({name:a,data:{count:e}}),t.publishMetric({name:c,data:{count:0}}),s=null}})),t.core.softphoneParams=u.softphone}},t.core.onIframeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,e)},t.core._refreshIframeOnTimeout=function(n,r){t.assertNotNull(n,"initCCPParams"),t.assertNotNull(r,"containerDiv");var o=(n.disasterRecoveryOn?1e4:5e3)+AWS.util.calculateRetryDelay(t.core.iframeRefreshAttempt||0,{base:2e3});e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=e.setTimeout((function(){if(t.core.iframeRefreshAttempt=(t.core.iframeRefreshAttempt||0)+1,t.core.iframeRefreshAttempt<=6){try{var o=t.core._getCCPIframe();o&&o.parentNode.removeChild(o);var i=t.core._createCCPIframe(r,n);t.core.upstream.upstream.output=i.contentWindow,t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(i,t.core.upstream)}catch(e){t.getLog().error("Error while checking for, and recreating, the CCP IFrame").withException(e).sendInternalLogToServer()}t.core._refreshIframeOnTimeout(n,r)}else t.core.getEventBus().trigger(t.EventType.IFRAME_RETRIES_EXHAUSTED),e.clearTimeout(t.core.iframeRefreshTimeout)}),o)},t.core._getCCPIframe=function(){for(var e of window.document.getElementsByTagName("iframe"))if(e.name===n)return e;return null},t.core._createCCPIframe=function(e,r){t.assertNotNull(r,"initCCPParams"),t.assertNotNull(e,"containerDiv");var o=document.createElement("iframe");return o.src=r.ccpUrl,o.allow="microphone; autoplay",o.style=r.style||"width: 100%; height: 100%",o.title=r.iframeTitle||n,o.name=n,e.appendChild(o),o},t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime=function(e,n){t.assertNotNull(e,"iframe"),t.assertNotNull(n,"conduit"),setTimeout((function(){var r={display:window.getComputedStyle(e,null).display,offsetWidth:e.offsetWidth,offsetHeight:e.offsetHeight,clientRectsLength:e.getClientRects().length};n.sendUpstream(t.EventType.IFRAME_STYLE,r)}),1e4)};var d=function(e,t,n,r){this.conduit=e,this.eventBus=t,this.synTimeout=n,this.ackTimeout=r,this.ackTimer=null,this.synTimer=null,this.ackSub=null};d.prototype.start=function(){var n=this;this.conduit.sendUpstream(t.EventType.SYNCHRONIZE),this.ackSub=this.conduit.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(n.ackTimer),n._deferStart()})),this.ackTimer=e.setTimeout((function(){n.ackSub.unsubscribe(),n.eventBus.trigger(t.EventType.ACK_TIMEOUT),n._deferStart()}),this.ackTimeout)},d.prototype._deferStart=function(){this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout)},d.prototype.deferStart=function(){null==this.synTimer&&(this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout))};var h=function(){var e={initFailure:new Set,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},n=function(e,t){e.forEach((function(e){e(t)}))};t.core.getUpstream().onUpstream(t.WebSocketEvents.INIT_FAILURE,(function(){n(e.initFailure)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_OPEN,(function(t){n(e.connectionOpen,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_CLOSE,(function(t){n(e.connectionClose,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_GAIN,(function(){n(e.connectionGain)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_LOST,(function(t){n(e.connectionLost,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,(function(t){n(e.subscriptionUpdate,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,(function(t){n(e.subscriptionFailure,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.ALL_MESSAGE,(function(t){n(e.allMessage,t),e.topic.has(t.topic)&&n(e.topic.get(t.topic),t)})),this.sendMessage=function(e){t.core.getUpstream().sendUpstream(t.WebSocketEvents.SEND,e)},this.onInitFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.initFailure.add(n),function(){return e.initFailure.delete(n)}},this.onConnectionOpen=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionOpen.add(n),function(){return e.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionClose.add(n),function(){return e.connectionClose.delete(n)}},this.onConnectionGain=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionGain.add(n),function(){return e.connectionGain.delete(n)}},this.onConnectionLost=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionLost.add(n),function(){return e.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionUpdate.add(n),function(){return e.subscriptionUpdate.delete(n)}},this.onSubscriptionFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionFailure.add(n),function(){return e.subscriptionFailure.delete(n)}},this.subscribeTopics=function(e){t.assertNotNull(e,"topics"),t.assertTrue(t.isArray(e),"topics must be a array"),t.core.getUpstream().sendUpstream(t.WebSocketEvents.SUBSCRIBE,e)},this.onMessage=function(n,r){return t.assertNotNull(n,"topicName"),t.assertTrue(t.isFunction(r),"method must be a function"),e.topic.has(n)?e.topic.get(n).add(r):e.topic.set(n,new Set([r])),function(){return e.topic.get(n).delete(r)}},this.onAllMessage=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.allMessage.add(n),function(){return e.allMessage.delete(n)}}},f=function(e){this.bus=e,this.bus.subscribe(t.AgentEvents.UPDATE,t.hitch(this,this.updateAgentData))};f.prototype.updateAgentData=function(e){var n=this.agentData;this.agentData=e,null==n&&(t.agent.initialized=!0,this.bus.trigger(t.AgentEvents.INIT,new t.Agent)),this.bus.trigger(t.AgentEvents.REFRESH,new t.Agent),this._fireAgentUpdateEvents(n)},f.prototype.getAgentData=function(){if(null==this.agentData)throw new t.StateError("No agent data is available yet!");return this.agentData},f.prototype.getContactData=function(e){var n=this.getAgentData(),r=t.find(n.snapshot.contacts,(function(t){return t.contactId===e}));if(null==r)throw new t.StateError("Contact %s no longer exists.",e);return r},f.prototype.getConnectionData=function(e,n){var r=this.getContactData(e),o=t.find(r.connections,(function(e){return e.connectionId===n}));if(null==o)throw new t.StateError("Connection %s for contact %s no longer exists.",n,e);return o},f.prototype.getInstanceId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]},f.prototype.getAWSAccountId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]},f.prototype._diffContacts=function(e){var n={added:{},removed:{},common:{},oldMap:t.index(null==e?[]:e.snapshot.contacts,(function(e){return e.contactId})),newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))};return t.keys(n.oldMap).forEach((function(e){t.contains(n.newMap,e)?n.common[e]=n.newMap[e]:n.removed[e]=n.oldMap[e]})),t.keys(n.newMap).forEach((function(e){t.contains(n.oldMap,e)||(n.added[e]=n.newMap[e])})),n},f.prototype._fireAgentUpdateEvents=function(e){var n=this,r=null,o=null==e?t.AgentAvailStates.INIT:e.snapshot.state.name,i=this.agentData.snapshot.state.name,s=null==e?t.AgentStateType.INIT:e.snapshot.state.type,a=this.agentData.snapshot.state.type;s!==a&&t.core.getAgentRoutingEventGraph().getAssociations(this,s,a).forEach((function(e){n.bus.trigger(e,new t.Agent)})),o!==i&&(this.bus.trigger(t.AgentEvents.STATE_CHANGE,{agent:new t.Agent,oldState:o,newState:i}),t.core.getAgentStateEventGraph().getAssociations(this,o,i).forEach((function(e){n.bus.trigger(e,new t.Agent)})));var c=e&&e.snapshot.nextState?e.snapshot.nextState.name:null,u=this.agentData.snapshot.nextState?this.agentData.snapshot.nextState.name:null;c!==u&&u&&n.bus.trigger(t.AgentEvents.ENQUEUED_NEXT_STATE,new t.Agent),r=null!==e?this._diffContacts(e):{added:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId})),removed:{},common:{},oldMap:{},newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))},t.values(r.added).forEach((function(e){n.bus.trigger(t.ContactEvents.INIT,new t.Contact(e.contactId)),n._fireContactUpdateEvents(e.contactId,t.ContactStateType.INIT,e.state.type)})),t.values(r.removed).forEach((function(e){n.bus.trigger(t.ContactEvents.DESTROYED,new t.ContactSnapshot(e)),n.bus.trigger(t.core.getContactEventName(t.ContactEvents.DESTROYED,e.contactId),new t.ContactSnapshot(e)),n._unsubAllContactEventsForContact(e.contactId)})),t.keys(r.common).forEach((function(e){n._fireContactUpdateEvents(e,r.oldMap[e].state.type,r.newMap[e].state.type)}))},f.prototype._fireContactUpdateEvents=function(e,n,r){var o=this;n!==r&&t.core.getContactEventGraph().getAssociations(this,n,r).forEach((function(n){o.bus.trigger(n,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(n,e),new t.Contact(e))})),o.bus.trigger(t.ContactEvents.REFRESH,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(t.ContactEvents.REFRESH,e),new t.Contact(e))},f.prototype._unsubAllContactEventsForContact=function(e){var n=this;t.values(t.ContactEvents).forEach((function(r){n.bus.getSubscriptions(t.core.getContactEventName(r,e)).map((function(e){e.unsubscribe()}))}))},t.core.onViewContact=function(e){t.core.getUpstream().onUpstream(t.ContactEvents.VIEW,e)},t.core.viewContact=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.VIEW,data:{contactId:e}})},t.core.onActivateChannelWithViewType=function(e){t.core.getUpstream().onUpstream(t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,e)},t.core.activateChannelWithViewType=function(e,n,r){const o={viewType:e,mediaType:n};r&&(o.source=r),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,data:o})},t.core.triggerTaskCreated=function(e){t.core.getUpstream().upstreamBus.trigger(t.TaskEvents.CREATED,e)},t.core.onAccessDenied=function(e){t.core.getUpstream().onUpstream(t.EventType.ACCESS_DENIED,e)},t.core.onAuthFail=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTH_FAIL,e)},t.core.onAuthorizeSuccess=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTHORIZE_SUCCESS,e)},t.core._handleAuthorizeSuccess=function(){window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,0)},t.core._handleAuthFail=function(e,n,r){r&&r.authorize?t.core._handleAuthorizeFail(e):t.core._handleCTIAuthFail(n)},t.core._handleAuthorizeFail=function(e){let n=t.core._getAuthRetryCount();if(!t.core.authorizeTimeoutId)if(n{t.core._redirectToLogin(e)}),r)}else t.getLog().warn("We have exhausted our authorization retries due to 401s from the authorize api. No more retries will be attempted in this session until the authorize api returns 200.").sendInternalLogToServer(),t.core.getEventBus().trigger(t.EventType.AUTHORIZE_RETRIES_EXHAUSTED)},t.core._redirectToLogin=function(e){"string"==typeof e?location.assign(e):location.reload()},t.core._handleCTIAuthFail=function(e){if(!t.core.ctiTimeoutId)if(t.core.ctiAuthRetryCount{t.core.authorize(e).then(t.core._triggerAuthorizeSuccess.bind(t.core)).catch(t.core._triggerAuthFail.bind(t.core,{authorize:!0})),t.core.ctiTimeoutId=null}),n)}else t.getLog().warn("We have exhausted our authorization retries due to 401s from the CTI service. No more retries will be attempted until the page is refreshed.").sendInternalLogToServer(),t.core.getEventBus().trigger(t.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED)},t.core._triggerAuthorizeSuccess=function(){t.core.getUpstream().upstreamBus.trigger(t.EventType.AUTHORIZE_SUCCESS)},t.core._triggerAuthFail=function(e){t.core.getUpstream().upstreamBus.trigger(t.EventType.AUTH_FAIL,e)},t.core._getAuthRetryCount=function(){let e=window.sessionStorage.getItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT);if(null!==e){if(isNaN(parseInt(e)))throw new t.StateError("The session storage value for auth retry count was NaN");return parseInt(e)}return window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,0),0},t.core._incrementAuthRetryCount=function(){window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,(t.core._getAuthRetryCount()+1).toString())},t.core.onAuthorizeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.AUTHORIZE_RETRIES_EXHAUSTED,e)},t.core.onCTIAuthorizeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED,e)},t.core.onSoftphoneSessionInit=function(e){t.core.getUpstream().onUpstream(t.ConnectionEvents.SESSION_INIT,e)},t.core.onConfigure=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.CONFIGURE,e)},t.core.onInitialized=function(e){t.core.getEventBus().subscribe(t.EventType.INIT,e)},t.core.getContactEventName=function(e,n){if(t.assertNotNull(e,"eventName"),t.assertNotNull(n,"contactId"),!t.contains(t.values(t.ContactEvents),e))throw new t.ValueError("%s is not a valid contact event.",e);return t.sprintf("%s::%s",e,n)},t.core.getEventBus=function(){return t.core.eventBus},t.core.getWebSocketManager=function(){return t.core.webSocketProvider},t.core.getAgentDataProvider=function(){return t.core.agentDataProvider},t.core.getLocalTimestamp=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp},t.core.getSkew=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.skew},t.core.getAgentRoutingEventGraph=function(){return t.core.agentRoutingEventGraph},t.core.agentRoutingEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.AgentStateType.ROUTABLE,t.AgentEvents.ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.NOT_ROUTABLE,t.AgentEvents.NOT_ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.OFFLINE,t.AgentEvents.OFFLINE),t.core.getAgentStateEventGraph=function(){return t.core.agentStateEventGraph},t.core.agentStateEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.values(t.AgentErrorStates),t.AgentEvents.ERROR).assoc(t.EventGraph.ANY,t.AgentAvailStates.AFTER_CALL_WORK,t.AgentEvents.ACW),t.core.getContactEventGraph=function(){return t.core.contactEventGraph},t.core.contactEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.ContactStateType.INCOMING,t.ContactEvents.INCOMING).assoc(t.EventGraph.ANY,t.ContactStateType.PENDING,t.ContactEvents.PENDING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTING,t.ContactEvents.CONNECTING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTED,t.ContactEvents.CONNECTED).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.ContactStateType.INCOMING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.EventGraph.ANY,t.ContactStateType.ENDED,t.ContactEvents.ACW).assoc(t.values(t.CONTACT_ACTIVE_STATES),t.values(t.relativeComplement(t.CONTACT_ACTIVE_STATES,t.ContactStateType)),t.ContactEvents.ENDED).assoc(t.EventGraph.ANY,t.ContactStateType.ERROR,t.ContactEvents.ERROR).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.MISSED,t.ContactEvents.MISSED),t.core.getClient=function(){if(!t.core.client)throw new t.StateError("The connect core has not been initialized!");return t.core.client},t.core.client=null,t.core.getAgentAppClient=function(){if(!t.core.agentAppClient)throw new t.StateError("The connect AgentApp Client has not been initialized!");return t.core.agentAppClient},t.core.agentAppClient=null,t.core.getTaskTemplatesClient=function(){if(!t.core.taskTemplatesClient)throw new t.StateError("The connect TaskTemplates Client has not been initialized!");return t.core.taskTemplatesClient},t.core.taskTemplatesClient=null,t.core.getMasterClient=function(){if(!t.core.masterClient)throw new t.StateError("The connect master client has not been initialized!");return t.core.masterClient},t.core.masterClient=null,t.core.getSoftphoneManager=function(){return t.core.softphoneManager},t.core.softphoneManager=null,t.core.getNotificationManager=function(){return t.core.notificationManager||(t.core.notificationManager=new t.NotificationManager),t.core.notificationManager},t.core.notificationManager=null,t.core.getPopupManager=function(){return t.core.popupManager},t.core.popupManager=new t.PopupManager,t.core.getUpstream=function(){if(!t.core.upstream)throw new t.StateError("There is no upstream conduit!");return t.core.upstream},t.core.upstream=null,t.core.AgentDataProvider=f}()},592:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t;var n="<>",r=t.makeEnum(["acknowledge","ack_timeout","init","api_request","api_response","auth_fail","access_denied","close","configure","log","master_request","master_response","synchronize","terminate","terminated","send_logs","reload_agent_configuration","broadcast","api_metric","client_metric","softphone_stats","softphone_report","client_side_logs","server_bound_internal_log","mute","iframe_style","iframe_retries_exhausted","update_connected_ccps","outer_context_info","media_device_request","media_device_response","tab_id","authorize_success","authorize_retries_exhausted","cti_authorize_retries_exhausted"]),o=t.makeNamespacedEnum("connect",["loginPopup","sendLogs","softphone","ringtone","metrics"]),i=t.makeNamespacedEnum("agent",["init","update","refresh","routable","not_routable","pending","contact_pending","offline","error","softphone_error","websocket_connection_lost","websocket_connection_gained","state_change","acw","mute_toggle","local_media_stream_created","enqueued_next_state"]),s=t.makeNamespacedEnum("webSocket",["init_failure","connection_open","connection_close","connection_error","connection_gain","connection_lost","subscription_update","subscription_failure","all_message","send","subscribe"]),a=t.makeNamespacedEnum("contact",["init","refresh","destroyed","incoming","pending","connecting","connected","missed","acw","view","ended","error","accepted"]),c=t.makeNamespacedEnum("taskList",["activate_channel_with_view_type"]),u=t.makeNamespacedEnum("task",["created"]),l=t.makeNamespacedEnum("connection",["session_init","ready_to_start_session"]),p=t.makeNamespacedEnum("configuration",["configure","set_speaker_device","set_microphone_device","set_ringer_device","speaker_device_changed","microphone_device_changed","ringer_device_changed"]),d=t.makeNamespacedEnum("voiceId",["update_domain_id"]),h=function(){};h.createRequest=function(e,n,r){return{event:e,requestId:t.randomId(),method:n,params:r}},h.createResponse=function(e,t,n,r){return{event:e,requestId:t.requestId,data:n,err:r||null}};var f=function(e,n,r){this.subMap=e,this.id=t.randomId(),this.eventName=n,this.f=r};f.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var g=function(){this.subIdMap={},this.subEventNameMap={}};g.prototype.subscribe=function(e,t){var n=new f(this,e,t);this.subIdMap[n.id]=n;var r=this.subEventNameMap[e]||[];return r.push(n),this.subEventNameMap[e]=r,n},g.prototype.unsubscribe=function(e,n){t.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==n})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),t.contains(this.subIdMap,n)&&delete this.subIdMap[n]},g.prototype.getAllSubscriptions=function(){return t.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},g.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var m=function(e){var t=e||{};this.subMap=new g,this.logEvents=t.logEvents||!1};m.prototype.subscribe=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.subMap.subscribe(e,n)},m.prototype.subscribeAll=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.subMap.subscribe(n,e)},m.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},m.prototype.trigger=function(e,r){t.assertNotNull(e,"eventName");var o=this,i=this.subMap.getSubscriptions(n),s=this.subMap.getSubscriptions(e);this.logEvents&&e!==t.EventType.LOG&&e!==t.EventType.MASTER_RESPONSE&&e!==t.EventType.API_METRIC&&e!==t.EventType.SERVER_BOUND_INTERNAL_LOG&&t.getLog().trace("Publishing event: %s",e).sendInternalLogToServer(),e.startsWith(t.ContactEvents.ACCEPTED)&&r&&r.contactId&&!(r instanceof t.Contact)&&(r=new t.Contact(r.contactId)),i.concat(s).forEach((function(n){try{n.f(r||null,e,o)}catch(n){t.getLog().error("'%s' event handler failed.",e).withException(n).sendInternalLogToServer()}}))},m.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},m.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))},t.EventBus=m,t.EventFactory=h,t.EventType=r,t.AgentEvents=i,t.ConfigurationEvents=p,t.ConnectionEvents=l,t.ConnnectionEvents=l,t.ContactEvents=a,t.ChannelViewEvents=c,t.TaskEvents=u,t.VoiceIdEvents=d,t.WebSocketEvents=s,t.MasterTopics=o}()},286:()=>{!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";var r=n(1),o="DEBUG",i="aws/subscribe",s="aws/heartbeat",a="disconnected";function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var u={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return u.assertTrue(null!==e&&void 0!==c(e),Object(r.sprintf)("%s must be provided",t||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,t){if(!Array.isArray(e))throw new Error(t+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==c(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},l=new RegExp("^(wss://)\\w*");u.validWSUrl=function(e){return l.test(e)},u.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},u.assertIsObject=function(e,t){if(!u.isObject(e))throw new Error(t+" is not an object!")},u.addJitter=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;t=Math.min(t,1);var n=Math.random()>.5?1:-1;return Math.floor(e+n*e*Math.random()*t)},u.isNetworkOnline=function(){return navigator.onLine},u.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var p=u;function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){for(var n=0;n=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var t=e.prefix||"";return this._logsDestination===o?this.consoleLoggerWrapper:new C(t)}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||E.DEBUG,this._clientLogger=t.logger||null,this._logsDestination="NULL",t.debug&&(this._logsDestination=o),t.logger&&(this._logsDestination="CLIENT_LOGGER")}}]),e}(),b=function(){function e(){g(this,e)}return v(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),C=function(e){function t(e){var n;return g(this,t),(n=function(e,t){return!t||"object"!==d(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}(this,h(t).call(this))).prefix=e||"",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}(t,b),v(t,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:2e3;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}var t,n;return t=e,(n=[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout((function(){e._execute()}),this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}}])&&_(t.prototype,n),e}();n.d(t,"a",(function(){return R}));var w=function(){var e=I.getLogger({}),t=p.isNetworkOnline(),n={primary:null,secondary:null},r={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},o={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},c={pendingResponse:!1,intervalHandle:null},u={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},l={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},h={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},f=new A((function(){B()})),g=new Set([i,"aws/unsubscribe",s]),m=setInterval((function(){if(t!==p.isNetworkOnline()){if(!(t=p.isNetworkOnline()))return void H(e.info("Network offline"));var n=T();t&&(!n||S(n,WebSocket.CLOSING)||S(n,WebSocket.CLOSED))&&(H(e.info("Network online, connecting to WebSocket server")),B())}}),250),v=function(t,n){t.forEach((function(t){try{t(n)}catch(t){H(e.error("Error executing callback",t))}}))},y=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},E=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";H(e.debug("["+t+"] Primary WebSocket: "+y(n.primary)+" | Secondary WebSocket: "+y(n.secondary)))},S=function(e,t){return e&&e.readyState===t},b=function(e){return S(e,WebSocket.OPEN)},C=function(e){return null===e||void 0===e.readyState||S(e,WebSocket.CLOSED)},T=function(){return null!==n.secondary?n.secondary:n.primary},_=function(){return b(T())},w=function(){if(c.pendingResponse)return H(e.warn("Heartbeat response not received")),clearInterval(c.intervalHandle),c.pendingResponse=!1,void B();_()?(H(e.debug("Sending heartbeat")),T().send(F(s)),c.pendingResponse=!0):(H(e.warn("Failed to send heartbeat since WebSocket is not open")),E("sendHeartBeat"),B())},R=function(){r.exponentialBackOffTime=1e3,c.pendingResponse=!1,r.reconnectWebSocket=!0,clearTimeout(r.lifeTimeTimeoutHandle),clearInterval(c.intervalHandle),clearTimeout(r.exponentialTimeoutHandle),clearTimeout(r.webSocketInitCheckerTimeoutId)},N=function(){h.consecutiveFailedSubscribeAttempts=0,h.consecutiveNoResponseRequest=0,clearInterval(h.responseCheckIntervalId),clearInterval(h.reSubscribeIntervalId)},k=function(){o.connectWebSocketRetryCount=0,o.connectionAttemptStartTime=null,o.noOpenConnectionsTimestamp=null},O=function(){try{H(e.info("WebSocket connection established!")),E("webSocketOnOpen"),null!==r.connState&&r.connState!==a||v(u.connectionGain),r.connState="connected";var t=Date.now();v(u.connectionOpen,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,noOpenConnectionsTimestamp:o.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-o.connectionAttemptStartTime,timeWithoutConnection:o.noOpenConnectionsTimestamp?t-o.noOpenConnectionsTimestamp:null}),k(),R(),T().openTimestamp=Date.now(),0===d.subscribed.size&&b(n.secondary)&&x(n.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(b(n.secondary)&&H(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach((function(e){d.subscriptionHistory.add(e),d.pending.add(e)})),d.subscribed.clear(),P()),w(),c.intervalHandle=setInterval(w,1e4);var i=1e3*l.connConfig.webSocketTransport.transportLifeTimeInSeconds;H(e.debug("Scheduling WebSocket manager reconnection, after delay "+i+" ms")),r.lifeTimeTimeoutHandle=setTimeout((function(){H(e.debug("Starting scheduled WebSocket manager reconnection")),B()}),i)}catch(t){H(e.error("Error after establishing WebSocket connection",t))}},L=function(t){E("webSocketOnError"),H(e.error("WebSocketManager Error, error_event: ",JSON.stringify(t))),B()},D=function(t){var r=JSON.parse(t.data);switch(r.topic){case i:if(H(e.debug("Subscription Message received from webSocket server",t.data)),h.requestCompleted=!0,h.consecutiveNoResponseRequest=0,"success"===r.content.status)h.consecutiveFailedSubscribeAttempts=0,r.content.topics.forEach((function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)})),0===d.subscriptionHistory.size?b(n.secondary)&&(H(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),x(n.primary,"[Primary WebSocket] Closing WebSocket")):P(),v(u.subscriptionUpdate,r);else{if(clearInterval(h.reSubscribeIntervalId),++h.consecutiveFailedSubscribeAttempts,5===h.consecutiveFailedSubscribeAttempts)return v(u.subscriptionFailure,r),void(h.consecutiveFailedSubscribeAttempts=0);h.reSubscribeIntervalId=setInterval((function(){P()}),500)}break;case s:H(e.debug("Heartbeat response received")),c.pendingResponse=!1;break;default:if(r.topic){if(H(e.debug("Message received for topic "+r.topic)),b(n.primary)&&b(n.secondary)&&0===d.subscriptionHistory.size&&this===n.primary)return void H(e.warn("Ignoring Message for Topic "+r.topic+", to avoid duplicates"));if(0===u.allMessage.size&&0===u.topic.size)return void H(e.warn("No registered callback listener for Topic",r.topic));v(u.allMessage,r),u.topic.has(r.topic)&&v(u.topic.get(r.topic),r)}else r.message?H(e.warn("WebSocketManager Message Error",r)):H(e.warn("Invalid incoming message",r))}},P=function t(){if(h.consecutiveNoResponseRequest>3)return H(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void v(u.subscriptionFailure,p.getSubscriptionResponse(i,!1,Array.from(d.pending)));_()?0!==Array.from(d.pending).length&&(clearInterval(h.responseCheckIntervalId),T().send(F(i,{topics:Array.from(d.pending)})),h.requestCompleted=!1,h.responseCheckIntervalId=setInterval((function(){h.requestCompleted||(++h.consecutiveNoResponseRequest,t())}),1e3)):H(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},x=function(t,n){S(t,WebSocket.CONNECTING)||S(t,WebSocket.OPEN)?t.close(1e3,n):H(e.warn("Ignoring WebSocket Close request, WebSocket State: "+y(t)))},M=function(e){x(n.primary,"[Primary] WebSocket "+e),x(n.secondary,"[Secondary] WebSocket "+e)},U=function(t){R(),N(),H(e.error("WebSocket Initialization failed")),r.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(m),v(u.initFailure,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,reason:t}),k()},F=function(e,t){return JSON.stringify({topic:e,content:t})},q=function(t){return!!(p.isObject(t)&&p.isObject(t.webSocketTransport)&&p.isNonEmptyString(t.webSocketTransport.url)&&p.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(H(e.error("Invalid WebSocket Connection Configuration",t)),!1)},B=function(){if(p.isNetworkOnline())if(r.websocketInitFailed)H(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(l.promiseCompleted)return R(),H(e.info("Fetching new WebSocket connection configuration")),o.connectionAttemptStartTime=o.connectionAttemptStartTime||Date.now(),l.promiseCompleted=!1,l.promiseHandle=u.getWebSocketTransport(),l.promiseHandle.then((function(t){return l.promiseCompleted=!0,H(e.debug("Successfully fetched webSocket connection configuration",t)),q(t)?(l.connConfig=t,l.connConfig.urlConnValidTime=Date.now()+85e3,f.connected(),j()):(U("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return l.promiseCompleted=!0,H(e.error("Failed to fetch webSocket connection configuration",t)),p.isNetworkFailure(t)?(H(e.info("Retrying fetching new WebSocket connection configuration")),f.retry()):U("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));H(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else H(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},j=function(){if(r.websocketInitFailed)return H(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!p.isNetworkOnline())return H(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};H(e.info("Initializing Websocket Manager")),E("initWebSocket");try{if(q(l.connConfig)){var t=null;return b(n.primary)?(H(e.debug("Primary Socket connection is already open")),S(n.secondary,WebSocket.CONNECTING)||(H(e.debug("Establishing a secondary web-socket connection")),n.secondary=V()),t=n.secondary):(S(n.primary,WebSocket.CONNECTING)||(H(e.debug("Establishing a primary web-socket connection")),n.primary=V()),t=n.primary),r.webSocketInitCheckerTimeoutId=setTimeout((function(){b(t)||function(){o.connectWebSocketRetryCount++;var t=p.addJitter(r.exponentialBackOffTime,.3);Date.now()+t<=l.connConfig.urlConnValidTime?(H(e.debug("Scheduling WebSocket reinitialization, after delay "+t+" ms")),r.exponentialTimeoutHandle=setTimeout((function(){return j()}),t),r.exponentialBackOffTime*=2):(H(e.warn("WebSocket URL cannot be used to establish connection")),B())}()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return H(e.error("Error Initializing web-socket-manager",t)),U("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},V=function(){var t=new WebSocket(l.connConfig.webSocketTransport.url);return t.addEventListener("open",O),t.addEventListener("message",D),t.addEventListener("error",L),t.addEventListener("close",(function(i){return function(t,i){H(e.info("Socket connection is closed",JSON.stringify(t))),E("webSocketOnClose before-cleanup"),v(u.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),C(n.primary)&&(n.primary=null),C(n.secondary)&&(n.secondary=null),r.reconnectWebSocket&&(b(n.primary)||b(n.secondary)?C(n.primary)&&b(n.secondary)&&(H(e.info("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(H(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),r.connState===a?H(e.info("Ignoring connectionLost callback invocation")):(v(u.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),o.noOpenConnectionsTimestamp=Date.now()),r.connState=a,B()),E("webSocketOnClose after-cleanup"))}(i,t)})),t},H=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(p.assertTrue(p.isFunction(t),"transportHandle must be a function"),null===u.getWebSocketTransport)return u.getWebSocketTransport=t,B();H(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.initFailure.add(e),r.websocketInitFailed&&e(),function(){return u.initFailure.delete(e)}},this.onConnectionOpen=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionOpen.add(e),function(){return u.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionClose.add(e),function(){return u.connectionClose.delete(e)}},this.onConnectionGain=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionGain.add(e),_()&&e(),function(){return u.connectionGain.delete(e)}},this.onConnectionLost=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionLost.add(e),r.connState===a&&e(),function(){return u.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.subscriptionUpdate.add(e),function(){return u.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.subscriptionFailure.add(e),function(){return u.subscriptionFailure.delete(e)}},this.onMessage=function(e,t){return p.assertNotNull(e,"topicName"),p.assertTrue(p.isFunction(t),"cb must be a function"),u.topic.has(e)?u.topic.get(e).add(t):u.topic.set(e,new Set([t])),function(){return u.topic.get(e).delete(t)}},this.onAllMessage=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.allMessage.add(e),function(){return u.allMessage.delete(e)}},this.subscribeTopics=function(e){p.assertNotNull(e,"topics"),p.assertIsList(e),e.forEach((function(e){d.subscribed.has(e)||d.pending.add(e)})),h.consecutiveNoResponseRequest=0,P()},this.sendMessage=function(t){if(p.assertIsObject(t,"payload"),void 0===t.topic||g.has(t.topic))H(e.warn("Cannot send message, Invalid topic",t));else{try{t=JSON.stringify(t)}catch(n){return void H(e.warn("Error stringify message",t))}_()?T().send(t):H(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){R(),N(),r.reconnectWebSocket=!1,clearInterval(m),M("User request to close WebSocket")},this.terminateWebSocketManager=U},R={create:function(){return new w},setGlobalConfig:function(e){var t=e.loggerConfig;I.updateLoggerConfig(t)},LogLevel:E,Logger:y}},function(e,t,n){var r;!function(){"use strict";var o={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,t){var n,r,s,a,c,u,l,p,d,h=1,f=e.length,g="";for(r=0;r=0),a.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}o.json.test(a.type)?g+=n:(!o.number.test(a.type)||p&&!a.sign?d="":(d=p?"+":"-",n=n.toString().replace(o.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(d+n).length,c=a.width&&l>0?u.repeat(l):"",g+=a.align?d+n+c:"0"===u?d+c+n:c+d+n)}return g}(function(e){if(a[e])return a[e];for(var t,n=e,r=[],i=0;n;){if(null!==(t=o.text.exec(n)))r.push(t[0]);else if(null!==(t=o.modulo.exec(n)))r.push("%");else{if(null===(t=o.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){i|=1;var s=[],c=t[2],u=[];if(null===(u=o.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=o.key_access.exec(c)))s.push(u[1]);else{if(null===(u=o.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}t[2]=s}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");r.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return a[e]=r}(e),arguments)}function s(e,t){return i.apply(null,[e].concat(t||[]))}var a=Object.create(null);t.sprintf=i,t.vsprintf=s,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=s,void 0===(r=function(){return{sprintf:i,vsprintf:s}}.call(t,n,t,e))||(e.exports=r))}()},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"WebSocketManager",(function(){return o}));var r=n(0);e.connect=e.connect||{},connect.WebSocketManager=r.a;var o=r.a}.call(this,n(3))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n}])},151:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n={TEST:"TEST",TRACE:"TRACE",DEBUG:"DEBUG",INFO:"INFO",LOG:"LOG",WARN:"WARN",ERROR:"ERROR",CRITICAL:"CRITICAL"},r={CCP:"ccp",SOFTPHONE:"softphone",CHAT:"chat",TASK:"task"},o={TEST:0,TRACE:10,DEBUG:20,INFO:30,LOG:40,WARN:50,ERROR:100,CRITICAL:200},i={TRACE:function(e){console.info(e)},DEBUG:function(e){console.info(e)},INFO:function(e){console.info(e)},LOG:function(e){console.log(e)},TEST:function(e){console.log(e)},WARN:function(e){console.warn(e)},ERROR:function(e){console.error(e)},CRITICAL:function(e){console.error(e)}},s=function(e){var t,n,o=Array.prototype.slice.call(e,0),i=o.shift();return function(e){return-1!==Object.values(r).indexOf(e)}(i)?(n=i,t=o.shift()):(t=i,n=r.CCP),{format:t,component:n,args:o}},a=function(e,n,r,o){this.component=e,this.level=n,this.text=r,this.time=new Date,this.exception=null,this.objects=[],this.line=0,this.agentResourceId=null;try{t.agent.initialized&&(this.agentResourceId=(new t.Agent)._getResourceId())}catch(e){console.log("Issue finding agentResourceId: ",e)}this.loggerId=o};a.fromObject=function(e){var t=new a(r.CCP,e.level,e.text,e.loggerId);return"[object Date]"===Object.prototype.toString.call(e.time)?t.time=new Date(e.time.getTime()):"number"==typeof e.time?t.time=new Date(e.time):"string"==typeof e.time?t.time=Date.parse(e.time):t.time=new Date,t.exception=e.exception,t.objects=e.objects,t};var c=function(e){var t=/AuthToken.*\=/g;e&&"object"==typeof e&&Object.keys(e).forEach((function(n){"object"==typeof e[n]?c(e[n]):"string"==typeof e[n]&&("url"===n||"text"===n?e[n]=e[n].replace(t,"[redacted]"):"quickConnectName"===n&&(e[n]="[redacted]"))}))},u=function(e){if(this.type=e instanceof Error?e.name:e.code||Object.prototype.toString.call(e),this.message=e.message,this.stack=[],e.stack)try{Array.isArray(e.stack)?this.stack=e.stack:"object"==typeof e.stack?this.stack=[JSON.stringify(e.stack)]:"string"==typeof e.stack&&(this.stack=e.stack.split("\n"))}catch{}};a.prototype.toString=function(){return t.sprintf("[%s] [%s] [%s]: %s",this.getTime()&&this.getTime().toISOString?this.getTime().toISOString():"???",this.getLevel(),this.getAgentResourceId(),this.getText())},a.prototype.getTime=function(){return this.time},a.prototype.getAgentResourceId=function(){return this.agentResourceId},a.prototype.getLevel=function(){return this.level},a.prototype.getText=function(){return this.text},a.prototype.getComponent=function(){return this.component},a.prototype.withException=function(e){return this.exception=new u(e),this},a.prototype.withObject=function(e){var n=t.deepcopy(e);return c(n),this.objects.push(n),this},a.prototype.withCrossOriginEventObject=function(e){var n=t.deepcopyCrossOriginEvent(e);return c(n),this.objects.push(n),this},a.prototype.sendInternalLogToServer=function(){return t.getLog()._serverBoundInternalLogs.push(this),this};var l=function(){this._logs=[],this._rolledLogs=[],this._logsToPush=[],this._serverBoundInternalLogs=[],this._echoLevel=o.INFO,this._logLevel=o.INFO,this._lineCount=0,this._logRollInterval=0,this._logRollTimer=null,this._loggerId=(new Date).getTime()+"-"+Math.random().toString(36).slice(2),this.setLogRollInterval(18e5),this._startLogIndexToPush=0};l.prototype.setLogRollInterval=function(t){var n=this;this._logRollTimer&&t===this._logRollInterval?this.warn("Logger is already set to the given interval: %d",this._logRollInterval):(this._logRollTimer&&e.clearInterval(this._logRollTimer),this._logRollInterval=t,this._logRollTimer=e.setInterval((function(){n._rolledLogs=n._logs,n._logs=[],n._startLogIndexToPush=0,n.info("Log roll interval occurred.")}),this._logRollInterval))},l.prototype.setLogLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._logLevel=o[e]},l.prototype.setEchoLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._echoLevel=o[e]},l.prototype.write=function(e,t,n){var r=new a(e,t,n,this.getLoggerId());return c(r),this.addLogEntry(r),r},l.prototype.addLogEntry=function(e){c(e),this._logs.push(e),r.SOFTPHONE===e.component&&this._logsToPush.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.sendInternalLogEntryToServer=function(e){this._serverBoundInternalLogs.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=i._logLevel})));var a=new e.Blob([JSON.stringify(s,void 0,4)],["text/plain"]),c=document.createElement("a");n=n||"agent-log",c.href=e.URL.createObjectURL(a),c.download=n+".txt",document.body.appendChild(c),c.click(),document.body.removeChild(c)},l.prototype.scheduleUpstreamLogPush=function(n){t.upstreamLogPushScheduled||(t.upstreamLogPushScheduled=!0,e.setInterval(t.hitch(this,this.reportMasterLogsUpStream,n),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var n=this._logsToPush.slice();this._logsToPush=[],t.ifMaster(t.MasterTopics.SEND_LOGS,(function(){n.length>0&&e.sendUpstream(t.EventType.SEND_LOGS,n)}))},l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPserverBoundLogsUpstream,n),1e3)},l.prototype.scheduleUpstreamOuterContextCCPLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPLogsUpstream,n),1e3)},l.prototype.pushOuterContextCCPserverBoundLogsUpstream=function(e){if(this._serverBoundInternalLogs.length>0){for(var n=0;n500?e=this._serverBoundInternalLogs.splice(0,500):(e=this._serverBoundInternalLogs,this._serverBoundInternalLogs=[]),t.publishClientSideLogs(e))};var p=function(n){l.call(this),this.conduit=n,e.setInterval(t.hitch(this,this._pushLogsDownstream),p.LOG_PUSH_INTERVAL),e.clearInterval(this._logRollTimer),this._logRollTimer=null};p.LOG_PUSH_INTERVAL=1e3,p.prototype=Object.create(l.prototype),p.prototype.constructor=p,p.prototype.pushLogsDownstream=function(e){var n=this;e.forEach((function(e){n.conduit.sendDownstream(t.EventType.LOG,e)}))},p.prototype._pushLogsDownstream=function(){var e=this;this._logs.forEach((function(n){e.conduit.sendDownstream(t.EventType.LOG,n)})),this._logs=[];for(var n=0;n{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.ChatMediaController=function(e,n){var r=t.getLog(),o=t.LogComponent.CHAT,i=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},s=function(e){e.onConnectionBroken((function(e){r.error(o,"Chat Session connection broken").withException(e).sendInternalLogToServer(),i("Chat Session connection broken",e)})),e.onConnectionEstablished((function(e){r.info(o,"Chat Session connection established").withObject(e).sendInternalLogToServer(),i("Chat Session connection established",e)}))};return{get:function(){return function(){i("Chat media controller init",e.contactId),r.info(o,"Chat media controller init").withObject(e).sendInternalLogToServer(),t.ChatSession.setGlobalConfig({loggerConfig:{logger:r},region:n.region});var a=t.ChatSession.create({chatDetails:e,type:"AGENT",websocketManager:t.core.getWebSocketManager()});return s(a),a.connect().then((function(t){return r.info(o,"Chat Session Successfully established for contactId %s",e.contactId).sendInternalLogToServer(),i("Chat Session Successfully established",e.contactId),a})).catch((function(t){throw r.error(o,"Chat Session establishement failed for contact %s",e.contactId).withException(t).sendInternalLogToServer(),i("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},279:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.MediaFactory=function(e){var n={},r=new Set,o=t.getLog(),i=t.LogComponent.CHAT,s=t.merge({},e)||{};s.region=s.region||"us-west-2";var a=function(e){n[e]&&!r.has(e)&&(o.info(i,"Destroying mediaController for %s",e),r.add(e),n[e].then((function(){"function"==typeof controller.cleanUp&&controller.cleanUp(),delete n[e],r.delete(e)})).catch((function(){delete n[e],r.delete(e)})))};return{get:function(e){return function(e){return e.isActive()}(e)?function(e){var r=e.getConnectionId();if(!e.getMediaInfo())return o.error(i,"Media info does not exist for a media type %s",e.getMediaType()).withObject(e).sendInternalLogToServer(),Promise.reject("Media info does not exist for this connection");if(n[r])return n[r];switch(o.info(i,"media controller of type %s init",e.getMediaType()).withObject(e).sendInternalLogToServer(),e.getMediaType()){case t.MediaType.CHAT:return n[r]=new t.ChatMediaController(e.getMediaInfo(),s).get();case t.MediaType.SOFTPHONE:return n[r]=new t.SoftphoneMediaController(e.getMediaInfo()).get();case t.MediaType.TASK:return n[r]=new t.TaskMediaController(e.getMediaInfo()).get();default:return o.error(i,"Unrecognized media type %s ",e.getMediaType()).sendInternalLogToServer(),Promise.reject()}}(e):(a(e.getConnectionId()),Promise.reject("Media Controller is no longer available for this connection"))},destroy:a}}}()},418:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.SoftphoneMediaController=function(e){return{get:function(){return Promise.resolve(e)}}}}()},187:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.TaskMediaController=function(e){var n=t.getLog(),r=t.LogComponent.TASK,o=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},i=function(e){e.onConnectionBroken((function(e){n.error(r,"Task Session connection broken").withException(e),o("Task Session connection broken",e)})),e.onConnectionEstablished((function(e){n.info(r,"Task Session connection established").withObject(e),o("Task Session connection established",e)}))};return{get:function(){return function(){o("Task media controller init",e.contactId),n.info(r,"Task media controller init").withObject(e);var s=t.TaskSession.create({contactId:e.contactId,initialContactId:e.initialContactId,websocketManager:t.core.getWebSocketManager()});return i(s),s.connect().then((function(){return n.info(r,"Task Session Successfully established for contactId %s",e.contactId),o("Task Session Successfully established",e.contactId),s})).catch((function(t){throw n.error(r,"Task Session establishement failed for contact %s",e.contactId).withException(t),o("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},743:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(n){var r=this;if(this._prevContactId=null,t.assertNotNull(n,"ringtoneConfig"),!n.ringtoneUrl)throw new Error("ringtoneUrl is required!");e.Audio&&void 0!==e.Promise?this._playableAudioPromise=new Promise((function(e,t){r._audio=new Audio(n.ringtoneUrl),r._audio.loop=!0,r._audio.addEventListener("canplay",(function(){r._audioPlayable=!0,e(r._audio)}))})):(this._audio=null,t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()),r._driveRingtone()};n.prototype._driveRingtone=function(){throw new Error("Not implemented.")},n.prototype._startRingtone=function(e){var n=this;this._audio&&(this._audio.play().catch((function(r){n._publishTelemetryEvent("Ringtone Playback Failure",e),t.getLog().error("Ringtone Playback Failure").withException(r).withObject({currentSrc:n._audio.currentSrc,sinkId:n._audio.sinkId,volume:n._audio.volume}).sendInternalLogToServer()})),n._publishTelemetryEvent("Ringtone Start",e),t.getLog().info("Ringtone Start").sendInternalLogToServer())},n.prototype._stopRingtone=function(e){this._audio&&(this._audio.pause(),this._audio.currentTime=0,this._publishTelemetryEvent("Ringtone Stop",e),t.getLog().info("Ringtone Stop").sendInternalLogToServer())},n.prototype.stopRingtone=function(){this._stopRingtone()},n.prototype._ringtoneSetup=function(e){var n=this;t.ifMaster(t.MasterTopics.RINGTONE,(function(){n._startRingtone(e),n._prevContactId=e.getContactId(),e.onConnected(lily.hitch(n,n._stopRingtone)),e.onAccepted(lily.hitch(n,n._stopRingtone)),e.onEnded(lily.hitch(n,n._stopRingtone)),e.onRefresh((function(e){e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING&&n._stopRingtone()}))}))},n.prototype._publishTelemetryEvent=function(e,n){n&&n.getContactId()&&t.publishMetric({name:e,contactId:n.getContactId()})},n.prototype.setOutputDevice=function(t){return this._playableAudioPromise?Promise.race([this._playableAudioPromise,new Promise((function(t,n){e.setTimeout((function(){n("Timed out waiting for playable audio")}),3e3)}))]).then((function(e){return e?e.setSinkId?Promise.resolve(e.setSinkId(t)):Promise.reject("Not supported"):Promise.reject("No audio found")})):e.Promise?Promise.reject("Not eligible ringtone owner"):void 0};var r=function(e){n.call(this,e)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.VOICE&&n.isSoftphoneCall()&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Ringtone Connecting",n),t.getLog().info("Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)})),(new t.Agent).getContacts().forEach((function(e){e.getStatus().type===t.ContactStatusType.CONNECTING&&n(e)}))};var o=function(e){n.call(this,e)};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.CHAT&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Chat Ringtone Connecting",n),t.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var i=function(e){n.call(this,e)};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.TASK&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Task Ringtone Connecting",n),t.getLog().info("Task Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var s=function(e){n.call(this,e)};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype._driveRingtone=function(){var e=this;t.contact((function(n){n.onIncoming((function(){n.getType()===lily.ContactType.QUEUE_CALLBACK&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Callback Ringtone Connecting",n),t.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer())}))}))},t.VoiceRingtoneEngine=r,t.ChatRingtoneEngine=o,t.TaskRingtoneEngine=i,t.QueueCallbackRingtoneEngine=s}()},642:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,e.ccpVersion="V2";var n={};n[t.SoftphoneCallType.AUDIO_ONLY]="Audio",n[t.SoftphoneCallType.VIDEO_ONLY]="Video",n[t.SoftphoneCallType.AUDIO_VIDEO]="AudioVideo",n[t.SoftphoneCallType.NONE]="None";var r="audio_input",o="audio_output";({})[t.ContactType.VOICE]="Voice";var i=[],s={},a={},c=null,u=null,l=null,p=t.SoftphoneErrorTypes,d={},h=t.randomId(),f=function(e){return new Promise((function(n,r){t.core.getClient().call(t.ClientMethods.CREATE_TRANSPORT,e,{success:function(e){n(e.softphoneTransport.softphoneMediaConnections)},failure:function(e){e.message&&e.message.includes("SoftphoneConnectionLimitBreachedException")&&w("multiple_softphone_active_sessions","Number of active sessions are more then allowed limit.",""),r(Error("requestIceAccess failed"))},authFailure:function(){r(Error("Authentication failed while requestIceAccess"))},accessDenied:function(){r(Error("Access Denied while requestIceAccess"))}})}))},g=function(e){var n=t.core.getUpstream(),r=e.getAgentConnection();if(r){var o=r.getSoftphoneMediaInfo();o?!0===o.autoAccept?(l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(),n.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(e.contactId)}),n.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,e.contactId),data:new t.Contact(e.contactId)})):l.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer():l.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer()}else l.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer()},m=function(){t.core.getEventBus().subscribe(t.EventType.MUTE,b)},v=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_SPEAKER_DEVICE,C)},y=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_MICROPHONE_DEVICE,T)},E=function(){try{t.isChromeBrowser()&&t.getChromeBrowserVersion()>43&&navigator.permissions.query({name:"microphone"}).then((function(e){e.onchange=function(){l.info("Microphone Permission: "+e.state),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:e.state}),"denied"===e.state&&w(p.MICROPHONE_NOT_SHARED,"Your microphone is not enabled in your browser. ","")}}))}catch(e){l.error("Failed in detecting microphone permission status: "+e)}},S=function(e){delete d[e],t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:!1}})},b=function(e){var n;if(0!==t.keys(d).length){for(var r in e&&void 0!==e.mute&&(n=e.mute),d)if(d.hasOwnProperty(r)){var o=d[r].stream;if(o){var i=o.getAudioTracks()[0];void 0!==n?(i.enabled=!n,d[r].muted=n,n?l.info("Agent has muted the contact, connectionId - "+r).sendInternalLogToServer():l.info("Agent has unmuted the contact, connectionId - "+r).sendInternalLogToServer()):n=d[r].muted||!1}}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:n}})}},C=function(e){if(0!==t.keys(d).length&&e&&e.deviceId){var n=e.deviceId,r=document.getElementById("remote-audio");try{l.info("Trying to set speaker to device "+n),r&&"function"==typeof r.setSinkId&&r.setSinkId(n)}catch(e){l.error("Failed to set speaker to device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,data:{deviceId:n}})}},T=function(e){if(0!==t.keys(d).length&&e&&e.deviceId){var n=e.deviceId,r=t.core.getSoftphoneManager();try{navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:n}}}).then((function(e){var t=e.getAudioTracks()[0];for(var n in d)d.hasOwnProperty(n)&&(d[n].stream,r.getSession(n)._pc.getSenders()[0].replaceTrack(t).then((function(){r.replaceLocalMediaTrack(n,t)})))}))}catch(e){l.error("Failed to set microphone device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,data:{deviceId:n}})}},I=function(e,n){if(n===t.RTCErrors.ICE_COLLECTION_TIMEOUT){for(var r="\n",o=0;o0?t.success(e):t.failure(p.MICROPHONE_NOT_SHARED)}),(function(e){t.failure(p.MICROPHONE_NOT_SHARED)})),r}t.failure(p.UNSUPPORTED_BROWSER)},w=function(e,n,r){l.error("Softphone error occurred : ",e,n||"").sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.SOFTPHONE_ERROR,data:new t.SoftphoneError(e,n,r)})},R=function(e,t){N("Softphone Session Failed",e,{failedReason:t})},N=function(e,n,r){t.publishMetric({name:e,contactId:n,data:r})},k=function(e,t,n){N(e,t,[{name:"AgentConnectionId",value:n}]),l.info("Publish multiple session error metrics",e,"contactId "+t,"agent connectionId "+n).sendInternalLogToServer()},O=function(){return!!(t.isOperaBrowser()&&t.getOperaBrowserVersion()>17)||!!(t.isChromeBrowser()&&t.getChromeBrowserVersion()>22)||!!(t.isFirefoxBrowser()&&t.getFirefoxBrowserVersion()>21)},L=function(e){var t=i.slice();i=[],t.length>0&&e.sendSoftphoneMetrics(t,{success:function(){l.info("sendSoftphoneMetrics success"+JSON.stringify(t)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneMetrics failed.").withObject(e).sendInternalLogToServer()}})},D=function(e){c=window.setInterval((function(){e.getUserAudioStats().then((function(e){var t=s;s=e,i.push(M(s,t,r))}),(function(e){l.debug("Failed to get user audio stats.",e).sendInternalLogToServer()})),e.getRemoteAudioStats().then((function(e){var t=a;a=e,i.push(M(a,t,o))}),(function(e){l.debug("Failed to get remote audio stats.",e).sendInternalLogToServer()}))}),1e3)},P=function(e){u=window.setInterval((function(){L(e)}),3e4)},x=function(){s=null,a=null,i=[],c=null,u=null},M=function(e,t,n){if(t&&e){var r=e.packetsLost>t.packetsLost?e.packetsLost-t.packetsLost:0,o=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new q(e.timestamp,r,o,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new q(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},U=function(e){return null!==e&&window.clearInterval(e),null},F=function(e,t){c=U(c),u=U(u),function(e,t,n,i){t.streamStats=[B(n,r),B(i,o)];var s={callStartTime:t.sessionStartTime,callEndTime:t.sessionEndTime,gumTimeMillis:t.gumTimeMillis,initializationTimeMillis:t.initializationTimeMillis,iceCollectionTimeMillis:t.iceCollectionTimeMillis,signallingConnectTimeMillis:t.signallingConnectTimeMillis,handshakingTimeMillis:t.handshakingTimeMillis,preTalkingTimeMillis:t.preTalkingTimeMillis,talkingTimeMillis:t.talkingTimeMillis,cleanupTimeMillis:t.cleanupTimeMillis,iceCollectionFailure:t.iceCollectionFailure,signallingConnectionFailure:t.signallingConnectionFailure,handshakingFailure:t.handshakingFailure,gumOtherFailure:t.gumOtherFailure,gumTimeoutFailure:t.gumTimeoutFailure,createOfferFailure:t.createOfferFailure,setLocalDescriptionFailure:t.setLocalDescriptionFailure,userBusyFailure:t.userBusyFailure,invalidRemoteSDPFailure:t.invalidRemoteSDPFailure,noRemoteIceCandidateFailure:t.noRemoteIceCandidateFailure,setRemoteDescriptionFailure:t.setRemoteDescriptionFailure,softphoneStreamStatistics:t.streamStats};e.sendSoftphoneReport(s,{success:function(){l.info("sendSoftphoneReport success"+JSON.stringify(s)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneReport failed.").withObject(e).sendInternalLogToServer()}})}(e,t,B(s,r),B(a,o)),L(e)},q=function(e,t,n,r,o,i,s){this.softphoneStreamType=r,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=o,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},B=function(e,t){return new q((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},j=function(e){this._originalLogger=e;var n=this;this._tee=function(e,r){return function(){var e=Array.prototype.slice.call(arguments[0]),o="";return e.forEach((function(){o+=" %s"})),r.apply(n._originalLogger,[t.LogComponent.SOFTPHONE,o].concat(e))}}};j.prototype.debug=function(){return this._tee(1,this._originalLogger.debug)(arguments)},j.prototype.info=function(){return this._tee(2,this._originalLogger.info)(arguments)},j.prototype.log=function(){return this._tee(3,this._originalLogger.log)(arguments)},j.prototype.warn=function(){return this._tee(4,this._originalLogger.warn)(arguments)},j.prototype.error=function(){return this._tee(5,this._originalLogger.error)(arguments)},t.SoftphoneManager=function(e){var n,r=this;(l=new j(t.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),t.RtcPeerConnectionFactory&&(n=new t.RtcPeerConnectionFactory(l,t.core.getWebSocketManager(),h,t.hitch(r,f,{transportType:"softphone",softphoneClientId:h}),t.hitch(r,w))),O()||w(p.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ",""),A({success:function(e){N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"granted"})},failure:function(e){w(e,"Your microphone is not enabled in your browser. ",""),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"denied"})}}),m(),v(),y(),E(),this.ringtoneEngine=null;var o={},i={};this.onInitContactSub={},this.onInitContactSub.unsubscribe=function(){};var s=!1,a=null,c=null,u=function(){s=!1,a=null,c=null};this.getSession=function(e){return o[e]},this.replaceLocalMediaTrack=function(e,t){var n=d[e].stream;if(n){var r=n.getAudioTracks()[0];t.enabled=r.enabled,r.enabled=!1,n.removeTrack(r),n.addTrack(t)}};var b=function(e){if(o.hasOwnProperty(e)){var t=o[e];new Promise((function(n,r){delete o[e],delete i[e],t.hangup()})).catch((function(t){lily.getLog().warn("Clean up the session locally "+e,t.message).sendInternalLogToServer()}))}};this.startSession=function(e,r){var p=s?a:e,h=s?c:r;if(p&&h){u(),i[h]=!0,l.info("Softphone call detected:","contactId "+p.getContactId(),"agent connectionId "+h).sendInternalLogToServer(),function(e){if(Object.keys(e).length>0){for(var t in e)e.hasOwnProperty(t)&&(k("MultiSessionHangUp",e[t].callId,t),b(t));throw new Error("duplicate session detected, refusing to setup new connection")}}(o),p.getStatus().type===t.ContactStatusType.CONNECTING&&N("Softphone Connecting",p.getContactId()),x();var f,m=p.getAgentConnection().getSoftphoneMediaInfo(),v=_(m.callConfigJson);v.useWebSocketProvider&&(f=t.core.getWebSocketManager());var y=new t.RTCSession(v.signalingEndpoint,v.iceServers,m.callContextToken,l,p.getContactId(),h,f);o[h]=y,t.core.getSoftphoneUserMediaStream()&&(y.mediaStream=t.core.getSoftphoneUserMediaStream()),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConnectionEvents.SESSION_INIT,data:{connectionId:h}}),y.onSessionFailed=function(e,t){delete o[h],delete i[h],I(e,t),R(p.getContactId(),t),F(p,e.sessionReport)},y.onSessionConnected=function(e){N("Softphone Session Connected",p.getContactId()),t.becomeMaster(t.MasterTopics.SEND_LOGS),D(e),P(p),g(p)},y.onSessionCompleted=function(e){N("Softphone Session Completed",p.getContactId()),delete o[h],delete i[h],F(p,e.sessionReport),S(h)},y.onLocalStreamAdded=function(e,n){d[h]={stream:n},t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,data:{connectionId:h}})},y.remoteAudioElement=document.getElementById("remote-audio"),n?y.connect(n.get(v.iceServers)):y.connect()}};var C=function(e,n){o[n]&&function(e){return e.getStatus().type===t.ContactStatusType.ENDED||e.getStatus().type===t.ContactStatusType.ERROR||e.getStatus().type===t.ContactStatusType.MISSED}(e)&&(b(n),u()),!e.isSoftphoneCall()||i[n]||e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING||(t.isFirefoxBrowser()&&t.hasOtherConnectedCCPs()?function(e,t){s=!0,a=e,c=t}(e,n):r.startSession(e,n))},T=function(e){var t=e.getAgentConnection().connectionId;l.info("Contact detected:","contactId "+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),i[t]||e.onRefresh((function(){C(e,t)}))};r.onInitContactSub=t.contact(T),(new t.Agent).getContacts().forEach((function(e){var t=e.getAgentConnection().connectionId;l.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId"+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),T(e),C(e,t)}))}}()},944:()=>{!function(){var e=this||window,t=function(){return t.cache.hasOwnProperty(arguments[0])||(t.cache[arguments[0]]=t.parse(arguments[0])),t.format.call(null,t.cache[arguments[0]],arguments)};function n(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function r(e,t){for(var n=[];t>0;n[--t]=e);return n.join("")}t.format=function(e,o){var i,s,a,c,u,l,p,d=1,h=e.length,f="",g=[];for(s=0;s>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}i=/[def]/.test(c[8])&&c[3]&&i>=0?"+"+i:i,l=c[4]?"0"==c[4]?"0":c[4].charAt(1):" ",p=c[6]-String(i).length,u=c[6]?r(l,p):"",g.push(c[5]?i+u:u+i)}return g.join("")},t.cache={},t.parse=function(e){for(var t=e,n=[],r=[],o=0;t;){if(null!==(n=/^[^\x25]+/.exec(t)))r.push(n[0]);else if(null!==(n=/^\x25{2}/.exec(t)))r.push("%");else{if(null===(n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t)))throw"[sprintf] huh?";if(n[2]){o|=1;var i=[],s=n[2],a=[];if(null===(a=/^([a-z_][a-z_\d]*)/i.exec(s)))throw"[sprintf] huh?";for(i.push(a[1]);""!==(s=s.substring(a[0].length));)if(null!==(a=/^\.([a-z_][a-z_\d]*)/i.exec(s)))i.push(a[1]);else{if(null===(a=/^\[(\d+)\]/.exec(s)))throw"[sprintf] huh?";i.push(a[1])}n[2]=i}else o|=2;if(3===o)throw"[sprintf] mixing positional and named placeholders is not (yet) supported";r.push(n)}t=t.substring(n[0].length)}return r},e.sprintf=t,e.vsprintf=function(e,n,r){return(r=n.slice(0)).splice(0,0,e),t.apply(null,r)}}()},82:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(){};n.prototype.send=function(e){throw new t.NotImplementedError},n.prototype.onMessage=function(e){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.onMessage=function(e){},r.prototype.send=function(e){};var o=function(e,t){n.call(this),this.window=e,this.domain=t||"*"};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.send=function(e){this.window.postMessage(e,this.domain)},o.prototype.onMessage=function(e){this.window.addEventListener("message",e)};var i=function(e,t,r){n.call(this),this.input=e,this.output=t,this.domain=r||"*"};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype.send=function(e){this.output.postMessage(e,this.domain)},i.prototype.onMessage=function(e){this.input.addEventListener("message",(t=>{t.source===this.output&&e(t)}))};var s=function(e){n.call(this),this.port=e,this.id=t.randomId()};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype.send=function(e){this.port.postMessage(e)},s.prototype.onMessage=function(e){this.port.addEventListener("message",e)},s.prototype.getId=function(){return this.id};var a=function(e){n.call(this),this.streamMap=e?t.index(e,(function(e){return e.getId()})):{},this.messageListeners=[]};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype.send=function(e){this.getStreams().forEach((function(t){try{t.send(e)}catch(e){}}))},a.prototype.onMessage=function(e){this.messageListeners.push(e),this.getStreams().forEach((function(t){t.onMessage(e)}))},a.prototype.addStream=function(e){this.streamMap[e.getId()]=e,this.messageListeners.forEach((function(t){e.onMessage(t)}))},a.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},a.prototype.getStreams=function(e){return t.values(this.streamMap)},a.prototype.getStreamForPort=function(e){return t.find(this.getStreams(),(function(t){return t.port===e}))};var c=function(e,n,o){this.name=e,this.upstream=n||new r,this.downstream=o||new r,this.downstreamBus=new t.EventBus,this.upstreamBus=new t.EventBus,this.upstream.onMessage(t.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(t.hitch(this,this._dispatchEvent,this.downstreamBus))};c.prototype.onUpstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.upstreamBus.subscribe(e,n)},c.prototype.onAllUpstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},c.prototype.onDownstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.downstreamBus.subscribe(e,n)},c.prototype.onAllDownstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},c.prototype.sendUpstream=function(e,n){t.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:n})},c.prototype.sendDownstream=function(e,n){t.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:n})},c.prototype._dispatchEvent=function(e,t){var n=t.data;n.event&&e.trigger(n.event,n.data)},c.prototype.passUpstream=function(){var e=this;return function(t,n){e.upstream.send({event:n,data:t})}},c.prototype.passDownstream=function(){var e=this;return function(t,n){e.downstream.send({event:n,data:t})}},c.prototype.shutdown=function(){this.upstreamBus.unsubscribeAll(),this.downstreamBus.unsubscribeAll()};var u=function(e,t,n,r){c.call(this,e,new i(t,n.contentWindow,r||"*"),null)};(u.prototype=Object.create(c.prototype)).constructor=u,t.Stream=n,t.NullStream=r,t.WindowStream=o,t.WindowIOStream=i,t.PortStream=s,t.StreamMultiplexer=a,t.Conduit=c,t.IFrameConduit=u}()},833:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(e,n){t.assertNotNull(e,"fromState"),t.assertNotNull(n,"toState"),this.fromState=e,this.toState=n};n.prototype.getAssociations=function(e){throw t.NotImplementedError()},n.prototype.getFromState=function(){return this.fromState},n.prototype.getToState=function(){return this.toState};var r=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"associations"),n.call(this,e,r),this.associations=o};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.getAssociations=function(e){return this.associations};var o=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"closure"),t.assertTrue(t.isFunction(o),"closure must be a function"),n.call(this,e,r),this.closure=o};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};var i=function(){this.fromMap={}};i.ANY="<>",i.prototype.assoc=function(e,t,n){var i=this;if(!e)throw new Error("fromStateObj is not defined.");if(!t)throw new Error("toStateObj is not defined.");if(!n)throw new Error("assocObj is not defined.");return e instanceof Array?e.forEach((function(e){i.assoc(e,t,n)})):t instanceof Array?t.forEach((function(t){i.assoc(e,t,n)})):"function"==typeof n?this._addAssociation(new o(e,t,n)):n instanceof Array?this._addAssociation(new r(e,t,n)):this._addAssociation(new r(e,t,[n])),this},i.prototype.getAssociations=function(e,n,r){t.assertNotNull(n,"fromState"),t.assertNotNull(r,"toState");var o=[],s=this.fromMap[i.ANY]||{},a=this.fromMap[n]||{};return o=(o=o.concat(this._getAssociationsFromMap(s,e,n,r))).concat(this._getAssociationsFromMap(a,e,n,r))},i.prototype._addAssociation=function(e){var t=this.fromMap[e.getFromState()];t||(t=this.fromMap[e.getFromState()]={});var n=t[e.getToState()];n||(n=t[e.getToState()]=[]),n.push(e)},i.prototype._getAssociationsFromMap=function(e,t,n,r){return(e[i.ANY]||[]).concat(e[r]||[]).reduce((function(e,n){return e.concat(n.getAssociations(t))}),[])},t.EventGraph=i}()},891:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=navigator.userAgent,r=["bubbles","cancelBubble","cancelable","composed","data","defaultPrevented","eventPhase","isTrusted","lastEventId","origin","returnValue","timeStamp","type"];t.sprintf=e.sprintf,t.vsprintf=e.vsprintf,delete e.sprintf,delete e.vsprintf,t.HTTP_STATUS_CODES={SUCCESS:200,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},t.TRANSPORT_TYPES={CHAT_TOKEN:"chat_token",WEB_SOCKET:"web_socket"},t.hitch=function(){var e=Array.prototype.slice.call(arguments),n=e.shift(),r=e.shift();return t.assertNotNull(n,"scope"),t.assertNotNull(r,"method"),t.assertTrue(t.isFunction(r),"method must be a function"),function(){var t=Array.prototype.slice.call(arguments);return r.apply(n,e.concat(t))}},t.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},t.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},t.keys=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(r);return n},t.values=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(e[r]);return n},t.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},t.merge=function(){var e=Array.prototype.slice.call(arguments,0),n={};return e.forEach((function(e){t.entries(e).forEach((function(e){n[e.key]=e.value}))})),n},t.now=function(){return(new Date).getTime()},t.find=function(e,t){for(var n=0;n{try{n[r]=e[r]}catch(e){t.getLog().info("deepcopyCrossOriginEvent failed on key: ",r).sendInternalLogToServer()}})),t.deepcopy(n)},t.getBaseUrl=function(){var n=e.location;return t.sprintf("%s//%s:%s",n.protocol,n.hostname,n.port)},t.getUrlWithProtocol=function(n){var r=e.location.protocol;return n.substr(0,r.length)!==r?t.sprintf("%s//%s",r,n):n},t.isFramed=function(){try{return window.self!==window.top}catch(e){return!0}},t.hasOtherConnectedCCPs=function(){return t.numberOfConnectedCCPs>1},t.fetch=function(e,n,r,o){return o=o||5,r=r||1e3,n=n||{},new Promise((function(i,s){!function o(a){fetch(e,n).then((function(e){e.status===t.HTTP_STATUS_CODES.SUCCESS?e.json().then((e=>i(e))).catch((()=>i({}))):1!==a&&(e.status>=t.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===t.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout((function(){o(--a)}),r):s(e)})).catch((function(e){s(e)}))}(o)}))},t.backoff=function(n,r,o,i){t.assertTrue(t.isFunction(n),"func must be a Function");var s=this;n({success:function(e){i&&i.success&&i.success(e)},failure:function(t,a){if(o>0){var c=2*r*Math.random();e.setTimeout((function(){s.backoff(n,2*c,--o,i)}),c)}else i&&i.failure&&i.failure(t,a)}})},t.publishMetric=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.CLIENT_METRIC,data:e})},t.publishSoftphoneStats=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_STATS,data:e})},t.publishSoftphoneReport=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_REPORT,data:e})},t.publishClientSideLogs=function(e){t.core.getEventBus().trigger(t.EventType.CLIENT_SIDE_LOGS,e)},t.addNamespaceToLogs=function(e){["log","error","warn","info","debug"].forEach((t=>{const n=window.console[t];window.console[t]=function(){const t=Array.from(arguments);t.unshift(`[${e}]`),n.apply(window.console,t)}}))},t.PopupManager=function(){},t.PopupManager.prototype.open=function(e,t,n){var r=this._getLastOpenedTimestamp(t),o=(new Date).getTime(),i=null;if(o-r>864e5){if(n){var s=n.height||578,a=n.width||433,c=n.top||0,u=n.left||0;(i=window.open("",t,"width="+a+", height="+s+", top="+c+", left="+u)).location!==e&&(i=window.open(e,t,"width="+a+", height="+s+", top="+c+", left="+u))}else(i=window.open("",t)).location!==e&&(i=window.open(e,t));this._setLastOpenedTimestamp(t,o)}return i},t.PopupManager.prototype.clear=function(t){var n=this._getLocalStorageKey(t);e.localStorage.removeItem(n)},t.PopupManager.prototype._getLastOpenedTimestamp=function(t){var n=this._getLocalStorageKey(t),r=e.localStorage.getItem(n);return r?parseInt(r,10):0},t.PopupManager.prototype._setLastOpenedTimestamp=function(t,n){var r=this._getLocalStorageKey(t);e.localStorage.setItem(r,""+n)},t.PopupManager.prototype._getLocalStorageKey=function(e){return"connectPopupManager::"+e};var o=t.makeEnum(["granted","denied","default"]);t.NotificationManager=function(){this.queue=[],this.permission=o.DEFAULT},t.NotificationManager.prototype.requestPermission=function(){var n=this;"Notification"in e?e.Notification.permission===o.DENIED?(t.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(),this.permission=o.DENIED):this.permission!==o.GRANTED&&e.Notification.requestPermission().then((function(e){n.permission=e,e===o.GRANTED?n._showQueued():n.queue=[]})):(t.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(),this.permission=o.DENIED)},t.NotificationManager.prototype.show=function(e,n){if(this.permission===o.GRANTED)return this._showImpl({title:e,options:n});if(this.permission===o.DENIED)t.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({title:e,options:n});else{var r={title:e,options:n};t.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(r).sendInternalLogToServer(),this.queue.push(r)}},t.NotificationManager.prototype._showQueued=function(){var e=this,t=this.queue.map((function(t){return e._showImpl(t)}));return this.queue=[],t},t.NotificationManager.prototype._showImpl=function(t){var n=new e.Notification(t.title,t.options);return t.options.clicked&&(n.onclick=function(){t.options.clicked.call(n)}),n},t.BaseError=function(n,r){e.Error.call(this,t.vsprintf(n,r))},t.BaseError.prototype=Object.create(Error.prototype),t.BaseError.prototype.constructor=t.BaseError,t.ValueError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.ValueError.prototype=Object.create(t.BaseError.prototype),t.ValueError.prototype.constructor=t.ValueError,t.NotImplementedError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.NotImplementedError.prototype=Object.create(t.BaseError.prototype),t.NotImplementedError.prototype.constructor=t.NotImplementedError,t.StateError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.StateError.prototype=Object.create(t.BaseError.prototype),t.StateError.prototype.constructor=t.StateError,t.VoiceIdError=function(e,t,n){var r={};return r.type=e,r.message=t,r.stack=Error(t).stack,r.err=n,r},t.isCCP=function(){return"ConnectSharedWorkerConduit"===t.core.getUpstream().name}}()},736:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.worker={};var n=function(){this.topicMasterMap={}};n.prototype.getMaster=function(e){return t.assertNotNull(e,"topic"),this.topicMasterMap[e]||null},n.prototype.setMaster=function(e,n){t.assertNotNull(e,"topic"),t.assertNotNull(n,"id"),this.topicMasterMap[e]=n},n.prototype.removeMaster=function(e){t.assertNotNull(e,"id");var n=this;t.entries(this.topicMasterMap).filter((function(t){return t.value===e})).forEach((function(e){delete n.topicMasterMap[e.key]}))};var r=function(e){t.ClientBase.call(this),this.conduit=e};(r.prototype=Object.create(t.ClientBase.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){var o=this,i=(new Date).getTime();t.containsValue(t.AgentAppClientMethods,e)?t.core.getAgentAppClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.containsValue(t.TaskTemplatesClientMethods,e)?t.core.getTaskTemplatesClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.core.getClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t,n){o._recordAPILatency(e,i,t),r.failure(t,n)},authFailure:function(){o._recordAPILatency(e,i),r.authFailure()},accessDenied:function(){r.accessDenied&&r.accessDenied()}})},r.prototype._recordAPILatency=function(e,t,n){var r=(new Date).getTime()-t;this._sendAPIMetrics(e,r,n)},r.prototype._sendAPIMetrics=function(e,n,r){this.conduit.sendDownstream(t.EventType.API_METRIC,{name:e,time:n,dimensions:[{name:"Category",value:"API"}],error:r})};var o=function(){var o=this;this.multiplexer=new t.StreamMultiplexer,this.conduit=new t.Conduit("AmazonConnectSharedWorker",null,this.multiplexer),this.client=new r(this.conduit),this.timeout=null,this.agent=null,this.nextToken=null,this.initData={},this.portConduitMap={},this.streamMapByTabId={},this.masterCoord=new n,this.logsBuffer=[],this.suppress=!1,this.forceOffline=!1,this.longPollingOptions={allowLongPollingShadowMode:!1,allowLongPollingWebsocketOnlyMode:!1};var i=null;t.rootLogger=new t.DownstreamConduitLogger(this.conduit),this.conduit.onDownstream(t.EventType.SEND_LOGS,(function(e){t.getLog().pushLogsDownstream(e),o.logsBuffer=o.logsBuffer.concat(e),o.logsBuffer.length>400&&o.handleSendLogsRequest(o.logsBuffer)})),this.conduit.onDownstream(t.EventType.CONFIGURE,(function(n){n.authToken&&n.authToken!==o.initData.authToken&&(o.initData=n,t.core.init(n),n.longPollingOptions&&("boolean"==typeof n.longPollingOptions.allowLongPollingShadowMode&&(o.longPollingOptions.allowLongPollingShadowMode=n.longPollingOptions.allowLongPollingShadowMode),"boolean"==typeof n.longPollingOptions.allowLongPollingWebsocketOnlyMode&&(o.longPollingOptions.allowLongPollingWebsocketOnlyMode=n.longPollingOptions.allowLongPollingWebsocketOnlyMode)),i?t.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(t.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),t.WebSocketManager.setGlobalConfig({loggerConfig:{logger:t.getLog()}}),(i=t.WebSocketManager.create()).onInitFailure((function(){o.conduit.sendDownstream(t.WebSocketEvents.INIT_FAILURE)})),i.onConnectionOpen((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_OPEN,e)})),i.onConnectionClose((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_CLOSE,e)})),i.onConnectionGain((function(){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_GAIN)})),i.onConnectionLost((function(e){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_LOST,e)})),i.onSubscriptionUpdate((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,e)})),i.onSubscriptionFailure((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,e)})),i.onAllMessage((function(e){o.conduit.sendDownstream(t.WebSocketEvents.ALL_MESSAGE,e)})),o.conduit.onDownstream(t.WebSocketEvents.SEND,(function(e){i.sendMessage(e)})),o.conduit.onDownstream(t.WebSocketEvents.SUBSCRIBE,(function(e){i.subscribeTopics(e)})),i.init(t.hitch(o,o.getWebSocketUrl)).then((function(n){try{if(n&&!n.webSocketConnectionFailed)t.getLog().info("Kicking off agent polling").sendInternalLogToServer(),o.pollForAgent(),t.getLog().info("Kicking off config polling").sendInternalLogToServer(),o.pollForAgentConfiguration({repeatForever:!0}),t.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),e.setInterval(t.hitch(o,o.checkAuthToken),3e5);else if(!t.webSocketInitFailed){const e=t.WebSocketEvents.INIT_FAILURE;throw o.conduit.sendDownstream(e),t.webSocketInitFailed=!0,new Error(e)}}catch(e){t.getLog().error("WebSocket failed to initialize").withException(e).sendInternalLogToServer()}}))))})),this.conduit.onDownstream(t.EventType.TERMINATE,(function(){o.handleSendLogsRequest(o.logsBuffer),t.core.terminate(),o.conduit.sendDownstream(t.EventType.TERMINATED)})),this.conduit.onDownstream(t.EventType.SYNCHRONIZE,(function(){o.conduit.sendDownstream(t.EventType.ACKNOWLEDGE)})),this.conduit.onDownstream(t.EventType.BROADCAST,(function(e){o.conduit.sendDownstream(e.event,e.data)})),e.onconnect=function(e){var n=e.ports[0],r=new t.PortStream(n);o.multiplexer.addStream(r),n.start();var i=new t.Conduit(r.getId(),null,r);i.sendDownstream(t.EventType.ACKNOWLEDGE,{id:r.getId()}),o.portConduitMap[r.getId()]=i,o.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length}),null!==o.agent&&o.updateAgent(),i.onDownstream(t.EventType.API_REQUEST,t.hitch(o,o.handleAPIRequest,i)),i.onDownstream(t.EventType.MASTER_REQUEST,t.hitch(o,o.handleMasterRequest,i,r.getId())),i.onDownstream(t.EventType.RELOAD_AGENT_CONFIGURATION,t.hitch(o,o.pollForAgentConfiguration)),i.onDownstream(t.EventType.TAB_ID,t.hitch(o,o.handleTabIdEvent,r)),i.onDownstream(t.EventType.CLOSE,t.hitch(o,o.handleCloseEvent,r))}};o.prototype.pollForAgent=function(){var n=this,r=t.hitch(n,n.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:n.nextToken,timeout:3e4},{success:function(r){try{n.agent=n.agent||{},n.agent.snapshot=r.snapshot,n.agent.snapshot.localTimestamp=t.now(),n.agent.snapshot.skew=n.agent.snapshot.snapshotTimestamp-n.agent.snapshot.localTimestamp,n.nextToken=r.nextToken,t.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(r).sendInternalLogToServer(),n.updateAgent()}catch(e){t.getLog().error("Long poll failed to update agent.").withObject(r).withException(e).sendInternalLogToServer()}finally{e.setTimeout(t.hitch(n,n.pollForAgent),100)}},failure:function(r,o){try{t.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:r,data:o})}finally{e.setTimeout(t.hitch(n,n.pollForAgent),5e3)}},authFailure:function(){r()},accessDenied:t.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentConfiguration=function(n){var r=this,o=n||{},i=t.hitch(r,r.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(n){var i=n.configuration;r.pollForAgentPermissions(i),r.pollForAgentStates(i),r.pollForDialableCountryCodes(i),r.pollForRoutingProfileQueues(i),o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration,o),3e4)},failure:function(n,i){try{t.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:n,data:i})}finally{o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration),3e4,o)}},authFailure:function(){i()},accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentStates=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentStates(e,{states:(o.states||[]).concat(t.states),nextToken:t.nextToken,maxResults:o.maxResults}):(e.agentStates=(o.states||[]).concat(t.states),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentPermissions=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentPermissions(e,{permissions:(o.permissions||[]).concat(t.permissions),nextToken:t.nextToken,maxResults:o.maxResults}):(e.permissions=(o.permissions||[]).concat(t.permissions),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForDialableCountryCodes=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForDialableCountryCodes(e,{countryCodes:(o.countryCodes||[]).concat(t.countryCodes),nextToken:t.nextToken,maxResults:o.maxResults}):(e.dialableCountries=(o.countryCodes||[]).concat(t.countryCodes),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForRoutingProfileQueues=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:e.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForRoutingProfileQueues(e,{countryCodes:(o.queues||[]).concat(t.queues),nextToken:t.nextToken,maxResults:o.maxResults}):(e.routingProfile.queues=(o.queues||[]).concat(t.queues),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.handleAPIRequest=function(e,n){var r=this;this.client.call(n.method,n.params,{success:function(r){var o=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,r);e.sendDownstream(o.event,o)},failure:function(o,i){var s=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,i,JSON.stringify(o));e.sendDownstream(s.event,s),t.getLog().error("'%s' API request failed",n.method).withObject({request:r.filterAuthToken(n),response:s}).withException(o).sendInternalLogToServer()},authFailure:t.hitch(r,r.handleAuthFail,{authorize:!0})})},o.prototype.handleMasterRequest=function(e,n,r){var o=this.conduit,i=null;switch(r.method){case t.MasterMethods.BECOME_MASTER:var s=this.masterCoord.getMaster(r.params.topic),a=Boolean(s)&&s!==n;this.masterCoord.setMaster(r.params.topic,n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:n,takeOver:a,topic:r.params.topic}),a&&o.sendDownstream(i.event,i);break;case t.MasterMethods.CHECK_MASTER:(s=this.masterCoord.getMaster(r.params.topic))||r.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(r.params.topic,n),s=n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:s,isMaster:n===s,topic:r.params.topic});break;default:throw new Error("Unknown master method: "+r.method)}e.sendDownstream(i.event,i)},o.prototype.handleTabIdEvent=function(e,n){var r=this;try{let o=n.tabId,i=r.streamMapByTabId[o],s=e.getId(),a=Object.keys(r.streamMapByTabId).filter((e=>r.streamMapByTabId[e].length>0)).length;if(i&&i.length>0){if(!i.includes(s)){r.streamMapByTabId[o].push(s);let e={length:Object.keys(r.portConduitMap).length,tabId:o,streamsTabsAcrossBrowser:a};e[o]={length:i.length},r.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,e)}}else{r.streamMapByTabId[o]=[e.getId()];let n={length:Object.keys(r.portConduitMap).length,tabId:o,streamsTabsAcrossBrowser:a+1};n[o]={length:r.streamMapByTabId[o].length},r.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,n)}}catch(e){t.getLog().error("[Tab Ids] Issue updating connected CCPs within the same tab").withException(e).sendInternalLogToServer()}},o.prototype.handleCloseEvent=function(e){var n=this;n.multiplexer.removeStream(e),delete n.portConduitMap[e.getId()],n.masterCoord.removeMaster(e.getId());let r={length:Object.keys(n.portConduitMap).length},o=Object.keys(n.streamMapByTabId);try{let t=o.find((t=>n.streamMapByTabId[t].includes(e.getId())));if(t){let o=n.streamMapByTabId[t].findIndex((t=>e.getId()===t));n.streamMapByTabId[t].splice(o,1);let i=n.streamMapByTabId[t]?n.streamMapByTabId[t].length:0;r[t]={length:i},r.tabId=t}let i=o.filter((e=>n.streamMapByTabId[e].length>0)).length;r.streamsTabsAcrossBrowser=i}catch(e){t.getLog().error("[Tab Ids] Issue updating tabId-specific stream data").withException(e).sendInternalLogToServer()}n.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,r)},o.prototype.updateAgentConfiguration=function(e){e.permissions&&e.dialableCountries&&e.agentStates&&e.routingProfile.queues?(this.agent=this.agent||{},this.agent.configuration=e,this.updateAgent()):t.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer()},o.prototype.updateAgent=function(){this.agent?this.agent.snapshot?this.agent.configuration?(this.agent.snapshot.status=this.agent.state,this.agent.snapshot.contacts&&this.agent.snapshot.contacts.length>1&&this.agent.snapshot.contacts.sort((function(e,t){return e.state.timestamp.getTime()-t.state.timestamp.getTime()})),this.agent.snapshot.contacts.forEach((function(e){e.status=e.state,e.connections.forEach((function(e){e.address=e.endpoint}))})),this.agent.configuration.routingProfile.defaultOutboundQueue.queueId=this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN,this.agent.configuration.routingProfile.queues.forEach((function(e){e.queueId=e.queueARN})),this.agent.snapshot.contacts.forEach((function(e){void 0!==e.queue&&(e.queue.queueId=e.queue.queueARN)})),this.agent.configuration.routingProfile.routingProfileId=this.agent.configuration.routingProfile.routingProfileARN,this.conduit.sendDownstream(t.AgentEvents.UPDATE,this.agent)):t.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer()},o.prototype.getWebSocketUrl=function(){var e=this,n=t.core.getClient(),r=t.hitch(e,e.handleAuthFail),o=t.hitch(e,e.handleAccessDenied);return new Promise((function(e,i){n.call(t.ClientMethods.CREATE_TRANSPORT,{transportType:t.TRANSPORT_TYPES.WEB_SOCKET},{success:function(n){t.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(),e(n)},failure:function(e,n){t.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({err:e,data:n}),i({reason:"getWebSocketUrl failed",_debug:e})},authFailure:function(){t.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(),i(Error("Authentication failed while getting getWebSocketUrl")),r()},accessDenied:function(){t.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(),i(Error("Access Denied Failure while getting getWebSocketUrl")),o()}})}))},o.prototype.handleSendLogsRequest=function(){var e=this,n=[],r=e.logsBuffer.slice();e.logsBuffer=[],r.forEach((function(e){n.push({timestamp:e.time,component:e.component,message:e.text})})),this.client.call(t.ClientMethods.SEND_CLIENT_LOGS,{logEvents:n},{success:function(e){t.getLog().info("SendLogs request succeeded.").sendInternalLogToServer()},failure:function(e,n){t.getLog().error("SendLogs request failed.").withObject(n).withException(e).sendInternalLogToServer()},authFailure:t.hitch(e,e.handleAuthFail)})},o.prototype.handleAuthFail=function(e){e?this.conduit.sendDownstream(t.EventType.AUTH_FAIL,e):this.conduit.sendDownstream(t.EventType.AUTH_FAIL)},o.prototype.handleAccessDenied=function(){this.conduit.sendDownstream(t.EventType.ACCESS_DENIED)},o.prototype.checkAuthToken=function(){var e=this,n=new Date(e.initData.authTokenExpiration),r=(new Date).getTime();n.getTime(){var e={821:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,t.agentApp={};var n="ccp";t.agentApp.initCCP=t.core.initCCP,t.agentApp.isInitialized=function(e){},t.agentApp.initAppCommunication=function(e,n){var r=document.getElementById(e),o=new t.IFrameConduit(n,window,r),i=[t.AgentEvents.UPDATE,t.ContactEvents.VIEW,t.EventType.ACKNOWLEDGE,t.EventType.TERMINATED,t.TaskEvents.CREATED];r.addEventListener("load",(function(e){i.forEach((function(e){t.core.getUpstream().onUpstream(e,(function(t){o.sendUpstream(e,t)}))}))}))};var r=function(e){var t=e.indexOf("ccp-v2");return e.slice(0,t-1)};t.agentApp.initApp=function(e,o,i,s){s=s||{};var a=i.endsWith("/")?i:i+"/",c=s.onLoad?s.onLoad:null,u={endpoint:a,style:s.style,onLoad:c};t.agentApp.AppRegistry.register(e,u,document.getElementById(o)),t.agentApp.AppRegistry.start(e,(function(o){var i=o.endpoint,a=o.containerDOM;return{init:function(){return e===n?(s.ccpParams=s.ccpParams?s.ccpParams:{},s.style&&(s.ccpParams.style=s.style),function(e,n,o){var i={ccpUrl:e,ccpLoadTimeout:1e4,loginPopup:!0,loginUrl:r(e)+"/login",softphone:{allowFramedSoftphone:!0,disableRingtone:!1}},s=t.merge(i,o.ccpParams);t.core.initCCP(n,s)}(i,a,s)):t.agentApp.initAppCommunication(e,i)},destroy:function(){return e===n?(o=r(i)+"/logout",t.fetch(o,{credentials:"include"}).then((function(){return t.core.getEventBus().trigger(t.EventType.TERMINATE),!0})).catch((function(e){return t.getLog().error("An error occured on logout."+e).withException(e),window.location.href=o,!1}))):null;var o}}}))},t.agentApp.stopApp=function(e){return t.agentApp.AppRegistry.stop(e)}}()},500:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t;var n,r="ccp";e.connect.agentApp.AppRegistry=(n={},{register:function(e,t,r){n[e]={containerDOM:r,endpoint:t.endpoint,style:t.style,instance:void 0,onLoad:t.onLoad}},start:function(e,t){if(n[e]){var o=n[e].containerDOM,i=n[e].endpoint,s=n[e].style,a=n[e].onLoad;if(e!==r){var c=function(e,t,n,r){var o=document.createElement("iframe");return o.src=t,o.style=n||"width: 100%; height:100%;",o.id=e,o["aria-label"]=e,o.onload=r,o.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),o}(e,i,s,a);o.appendChild(c)}return n[e].instance=t(n[e]),n[e].instance.init()}},stop:function(e){if(n[e]){var t,r=n[e],o=r.containerDOM.querySelector("iframe");return r.containerDOM.removeChild(o),r.instance&&(t=r.instance.destroy(),delete r.instance),t}}})}()},965:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,t.AgentStateType=t.makeEnum(["init","routable","not_routable","offline"]),t.AgentStatusType=t.AgentStateType,t.AgentAvailStates=t.makeEnum(["Init","Busy","AfterCallWork","CallingCustomer","Dialing","Joining","PendingAvailable","PendingBusy"]),t.AgentErrorStates=t.makeEnum(["Error","AgentHungUp","BadAddressAgent","BadAddressCustomer","Default","FailedConnectAgent","FailedConnectCustomer","InvalidLocale","LineEngagedAgent","LineEngagedCustomer","MissedCallAgent","MissedCallCustomer","MultipleCcpWindows","RealtimeCommunicationError"]),t.EndpointType=t.makeEnum(["phone_number","agent","queue"]),t.AddressType=t.EndpointType,t.ConnectionType=t.makeEnum(["agent","inbound","outbound","monitoring"]),t.ConnectionStateType=t.makeEnum(["init","connecting","connected","hold","disconnected"]),t.ConnectionStatusType=t.ConnectionStateType,t.CONNECTION_ACTIVE_STATES=t.set([t.ConnectionStateType.CONNECTING,t.ConnectionStateType.CONNECTED,t.ConnectionStateType.HOLD]),t.ContactStateType=t.makeEnum(["init","incoming","pending","connecting","connected","missed","error","ended"]),t.ContactStatusType=t.ContactStateType,t.CONTACT_ACTIVE_STATES=t.makeEnum(["incoming","pending","connecting","connected"]),t.ContactType=t.makeEnum(["voice","queue_callback","chat","task"]),t.ContactInitiationMethod=t.makeEnum(["inbound","outbound","transfer","queue_transfer","callback","api","disconnect"]),t.ChannelType=t.makeEnum(["VOICE","CHAT","TASK"]),t.MediaType=t.makeEnum(["softphone","chat","task"]),t.SoftphoneCallType=t.makeEnum(["audio_video","video_only","audio_only","none"]),t.SoftphoneErrorTypes=t.makeEnum(["unsupported_browser","microphone_not_shared","signalling_handshake_failure","signalling_connection_failure","ice_collection_timeout","user_busy_error","webrtc_error","realtime_communication_error","other"]),t.ClickType=t.makeEnum(["Accept","Reject","Hangup"]),t.VoiceIdErrorTypes=t.makeEnum(["no_speaker_id_found","speaker_id_not_enrolled","get_speaker_id_failed","get_speaker_status_failed","opt_out_speaker_failed","opt_out_speaker_in_lcms_failed","delete_speaker_failed","start_session_failed","evaluate_speaker_failed","session_not_exists","describe_session_failed","enroll_speaker_failed","update_speaker_id_failed","update_speaker_id_in_lcms_failed","not_supported_on_conference_calls","enroll_speaker_timeout","evaluate_speaker_timeout","get_domain_id_failed","no_domain_id_found"]),t.CTIExceptions=t.makeEnum(["AccessDeniedException","InvalidStateException","BadEndpointException","InvalidAgentARNException","InvalidConfigurationException","InvalidContactTypeException","PaginationException","RefreshTokenExpiredException","SendDataFailedException","UnauthorizedException","QuotaExceededException"]),t.VoiceIdStreamingStatus=t.makeEnum(["ONGOING","ENDED","PENDING_CONFIGURATION"]),t.VoiceIdAuthenticationDecision=t.makeEnum(["ACCEPT","REJECT","NOT_ENOUGH_SPEECH","SPEAKER_NOT_ENROLLED","SPEAKER_OPTED_OUT","SPEAKER_ID_NOT_PROVIDED","SPEAKER_EXPIRED"]),t.VoiceIdFraudDetectionDecision=t.makeEnum(["NOT_ENOUGH_SPEECH","HIGH_RISK","LOW_RISK"]),t.ContactFlowAuthenticationDecision=t.makeEnum(["Authenticated","NotAuthenticated","Inconclusive","NotEnrolled","OptedOut","NotEnabled","Error"]),t.ContactFlowFraudDetectionDecision=t.makeEnum(["HighRisk","LowRisk","Inconclusive","NotEnabled","Error"]),t.VoiceIdEnrollmentRequestStatus=t.makeEnum(["NOT_ENOUGH_SPEECH","IN_PROGRESS","COMPLETED","FAILED"]),t.VoiceIdSpeakerStatus=t.makeEnum(["OPTED_OUT","ENROLLED","PENDING"]),t.VoiceIdConstants={EVALUATE_SESSION_DELAY:1e4,EVALUATION_MAX_POLL_TIMES:24,EVALUATION_POLLING_INTERVAL:5e3,ENROLLMENT_MAX_POLL_TIMES:120,ENROLLMENT_POLLING_INTERVAL:5e3,START_SESSION_DELAY:8e3},t.AgentPermissions={OUTBOUND_CALL:"outboundCall",VOICE_ID:"voiceId"};var n=function(){if(!t.agent.initialized)throw new t.StateError("The agent is not yet initialized!")};n.prototype._getData=function(){return t.core.getAgentDataProvider().getAgentData()},n.prototype._createContactAPI=function(e){return new t.Contact(e.contactId)},n.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(t.AgentEvents.REFRESH,e)},n.prototype.onRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ROUTABLE,e)},n.prototype.onNotRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.NOT_ROUTABLE,e)},n.prototype.onOffline=function(e){t.core.getEventBus().subscribe(t.AgentEvents.OFFLINE,e)},n.prototype.onError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ERROR,e)},n.prototype.onSoftphoneError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.SOFTPHONE_ERROR,e)},n.prototype.onWebSocketConnectionLost=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e)},n.prototype.onWebSocketConnectionGained=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED,e)},n.prototype.onAfterCallWork=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ACW,e)},n.prototype.onStateChange=function(e){t.core.getEventBus().subscribe(t.AgentEvents.STATE_CHANGE,e)},n.prototype.onMuteToggle=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.MUTE_TOGGLE,e)},n.prototype.onLocalMediaStreamCreated=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,e)},n.prototype.onSpeakerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,e)},n.prototype.onMicrophoneDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,e)},n.prototype.onRingerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.RINGER_DEVICE_CHANGED,e)},n.prototype.mute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!0}})},n.prototype.unmute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!1}})},n.prototype.setSpeakerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_SPEAKER_DEVICE,data:{deviceId:e}})},n.prototype.setMicrophoneDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_MICROPHONE_DEVICE,data:{deviceId:e}})},n.prototype.setRingerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_RINGER_DEVICE,data:{deviceId:e}})},n.prototype.getState=function(){return this._getData().snapshot.state},n.prototype.getNextState=function(){return this._getData().snapshot.nextState},n.prototype.getAvailabilityState=function(){return this._getData().snapshot.agentAvailabilityState},n.prototype.getStatus=n.prototype.getState,n.prototype.getStateDuration=function(){return t.now()-this._getData().snapshot.state.startTimestamp.getTime()+t.core.getSkew()},n.prototype.getStatusDuration=n.prototype.getStateDuration,n.prototype.getPermissions=function(){return this.getConfiguration().permissions},n.prototype.getContacts=function(e){var t=this;return this._getData().snapshot.contacts.map((function(e){return t._createContactAPI(e)})).filter((function(t){return!e||t.getType()===e}))},n.prototype.getConfiguration=function(){return this._getData().configuration},n.prototype.getAgentStates=function(){return this.getConfiguration().agentStates},n.prototype.getRoutingProfile=function(){return this.getConfiguration().routingProfile},n.prototype.getChannelConcurrency=function(e){var n=this.getRoutingProfile().channelConcurrencyMap;return n||(n=Object.keys(t.ChannelType).reduce((function(e,n){return"TASK"!==n&&(e[t.ChannelType[n]]=1),e}),{})),e?n[e]||0:n},n.prototype.getName=function(){return this.getConfiguration().name},n.prototype.getExtension=function(){return this.getConfiguration().extension},n.prototype.getDialableCountries=function(){return this.getConfiguration().dialableCountries},n.prototype.isSoftphoneEnabled=function(){return this.getConfiguration().softphoneEnabled},n.prototype.setConfiguration=function(e,n){var r=t.core.getClient();e&&e.agentPreferences&&e.agentPreferences.LANGUAGE&&!e.agentPreferences.locale&&(e.agentPreferences.locale=e.agentPreferences.LANGUAGE),e&&e.agentPreferences&&!t.isValidLocale(e.agentPreferences.locale)?n&&n.failure&&n.failure(t.AgentErrorStates.INVALID_LOCALE):r.call(t.ClientMethods.UPDATE_AGENT_CONFIGURATION,{configuration:t.assertNotNull(e,"configuration")},{success:function(e){t.core.getUpstream().sendUpstream(t.EventType.RELOAD_AGENT_CONFIGURATION),n.success&&n.success(e)},failure:n&&n.failure})},n.prototype.setState=function(e,n,r){t.core.getClient().call(t.ClientMethods.PUT_AGENT_STATE,{state:t.assertNotNull(e,"state"),enqueueNextState:r&&!!r.enqueueNextState},n)},n.prototype.onEnqueuedNextState=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ENQUEUED_NEXT_STATE,e)},n.prototype.setStatus=n.prototype.setState,n.prototype.connect=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_OUTBOUND_CONTACT,{endpoint:t.assertNotNull(o,"endpoint"),queueARN:n&&(n.queueARN||n.queueId)||this.getRoutingProfile().defaultOutboundQueue.queueARN},n&&{success:n.success,failure:n.failure})},n.prototype.getAllQueueARNs=function(){return this.getConfiguration().routingProfile.queues.map((function(e){return e.queueARN}))},n.prototype.getEndpoints=function(e,n,r){var o=this,i=t.core.getClient();t.assertNotNull(n,"callbacks"),t.assertNotNull(n.success,"callbacks.success");var s=r||{};s.endpoints=s.endpoints||[],s.maxResults=s.maxResults||t.DEFAULT_BATCH_SIZE,t.isArray(e)||(e=[e]),i.call(t.ClientMethods.GET_ENDPOINTS,{queueARNs:e,nextToken:s.nextToken||null,maxResults:s.maxResults},{success:function(r){if(r.nextToken)o.getEndpoints(e,n,{nextToken:r.nextToken,maxResults:s.maxResults,endpoints:s.endpoints.concat(r.endpoints)});else{s.endpoints=s.endpoints.concat(r.endpoints);var i=s.endpoints.map((function(e){return new t.Endpoint(e)}));n.success({endpoints:i,addresses:i})}},failure:n.failure})},n.prototype.getAddresses=n.prototype.getEndpoints,n.prototype._getResourceId=function(){var e=this.getAllQueueARNs();for(let t of e){const e=t.match(/\/agent\/([^/]+)/);if(e)return e[1]}return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ",e)},n.prototype.toSnapshot=function(){return new t.AgentSnapshot(this._getData())};var r=function(e){t.Agent.call(this),this.agentData=e};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._getData=function(){return this.agentData},r.prototype._createContactAPI=function(e){return new t.ContactSnapshot(e)};var o=function(e){this.contactId=e};o.prototype._getData=function(){return t.core.getAgentDataProvider().getContactData(this.getContactId())},o.prototype._createConnectionAPI=function(e){return this.getType()===t.ContactType.CHAT?new t.ChatConnection(this.contactId,e.connectionId):this.getType()===t.ContactType.TASK?new t.TaskConnection(this.contactId,e.connectionId):new t.VoiceConnection(this.contactId,e.connectionId)},o.prototype.getEventName=function(e){return t.core.getContactEventName(e,this.getContactId())},o.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.REFRESH),e)},o.prototype.onIncoming=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.INCOMING),e)},o.prototype.onConnecting=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTING),e)},o.prototype.onPending=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.PENDING),e)},o.prototype.onAccepted=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACCEPTED),e)},o.prototype.onMissed=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.MISSED),e)},o.prototype.onEnded=function(e){var n=t.core.getEventBus();n.subscribe(this.getEventName(t.ContactEvents.ENDED),e),n.subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onDestroy=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onACW=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACW),e)},o.prototype.onConnected=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTED),e)},o.prototype.onError=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ERROR),e)},o.prototype.getContactId=function(){return this.contactId},o.prototype.getOriginalContactId=function(){return this._getData().initialContactId},o.prototype.getInitialContactId=o.prototype.getOriginalContactId,o.prototype.getType=function(){return this._getData().type},o.prototype.getContactDuration=function(){return this._getData().contactDuration},o.prototype.getState=function(){return this._getData().state},o.prototype.getStatus=o.prototype.getState,o.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},o.prototype.getStatusDuration=o.prototype.getStateDuration,o.prototype.getQueue=function(){return this._getData().queue},o.prototype.getQueueTimestamp=function(){return this._getData().queueTimestamp},o.prototype.getConnections=function(){var e=this;return this._getData().connections.map((function(n){return e.getType()===t.ContactType.CHAT?new t.ChatConnection(e.contactId,n.connectionId):e.getType()===t.ContactType.TASK?new t.TaskConnection(e.contactId,n.connectionId):new t.VoiceConnection(e.contactId,n.connectionId)}))},o.prototype.getInitialConnection=function(){return t.find(this.getConnections(),(function(e){return e.isInitialConnection()}))||null},o.prototype.getActiveInitialConnection=function(){var e=this.getInitialConnection();return null!=e&&e.isActive()?e:null},o.prototype.getThirdPartyConnections=function(){return this.getConnections().filter((function(e){return!e.isInitialConnection()&&e.getType()!==t.ConnectionType.AGENT}))},o.prototype.getSingleActiveThirdPartyConnection=function(){return this.getThirdPartyConnections().filter((function(e){return e.isActive()}))[0]||null},o.prototype.getAgentConnection=function(){return t.find(this.getConnections(),(function(e){var n=e.getType();return n===t.ConnectionType.AGENT||n===t.ConnectionType.MONITORING}))},o.prototype.getName=function(){return this._getData().name},o.prototype.getContactMetadata=function(){return this._getData().contactMetadata},o.prototype.getDescription=function(){return this._getData().description},o.prototype.getReferences=function(){return this._getData().references},o.prototype.getAttributes=function(){return this._getData().attributes},o.prototype.getContactFeatures=function(){return this._getData().contactFeatures},o.prototype.getChannelContext=function(){return this._getData().channelContext},o.prototype.isSoftphoneCall=function(){return null!=t.find(this.getConnections(),(function(e){return null!=e.getSoftphoneMediaInfo()}))},o.prototype._isInbound=function(){return this._getData().initiationMethod!==t.ContactInitiationMethod.OUTBOUND},o.prototype.isInbound=function(){var e=this.getInitialConnection();return e.getMediaType()===t.MediaType.TASK?this._isInbound():!!e&&e.getType()===t.ConnectionType.INBOUND},o.prototype.isConnected=function(){return this.getStatus().type===t.ContactStateType.CONNECTED},o.prototype.accept=function(e){var n=t.core.getClient(),r=this,o=this.getContactId();t.publishClickStreamData({contactId:this.getContactId(),clickType:t.ClickType.ACCEPT,clickTime:(new Date).toISOString()}),n.call(t.ClientMethods.ACCEPT_CONTACT,{contactId:o},{success:function(n){var i=t.core.getUpstream();i.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(o)}),i.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,r.getContactId()),data:new t.Contact(o)});var s=new t.Contact(o);t.isFirefoxBrowser()&&s.isSoftphoneCall()&&t.core.triggerReadyToStartSessionEvent(),e&&e.success&&e.success(n)},failure:e?e.failure:null})},o.prototype.destroy=function(){t.getLog().warn("contact.destroy() has been deprecated.")},o.prototype.reject=function(e){var n=t.core.getClient();t.publishClickStreamData({contactId:this.getContactId(),clickType:t.ClickType.REJECT,clickTime:(new Date).toISOString()}),n.call(t.ClientMethods.REJECT_CONTACT,{contactId:this.getContactId()},e)},o.prototype.complete=function(e){t.core.getClient().call(t.ClientMethods.COMPLETE_CONTACT,{contactId:this.getContactId()},e)},o.prototype.clear=function(e){t.core.getClient().call(t.ClientMethods.CLEAR_CONTACT,{contactId:this.getContactId()},e)},o.prototype.notifyIssue=function(e,n,r){t.core.getClient().call(t.ClientMethods.NOTIFY_CONTACT_ISSUE,{contactId:this.getContactId(),issueCode:e,description:n},r)},o.prototype.addConnection=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_ADDITIONAL_CONNECTION,{contactId:this.getContactId(),endpoint:o},n)},o.prototype.toggleActiveConnections=function(e){var n=t.core.getClient(),r=null,o=t.find(this.getConnections(),(function(e){return e.getStatus().type===t.ConnectionStateType.HOLD}));if(null!=o)r=o.getConnectionId();else{var i=this.getConnections().filter((function(e){return e.isActive()}));i.length>0&&(r=i[0].getConnectionId())}n.call(t.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:r},e)},o.prototype.sendSoftphoneMetrics=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,softphoneStreamStatistics:n},r),t.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:e.ccpVersion,stats:n})},o.prototype.sendSoftphoneReport=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n},r),t.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n})},o.prototype.conferenceConnections=function(e){t.core.getClient().call(t.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},o.prototype.toSnapshot=function(){return new t.ContactSnapshot(this._getData())},o.prototype.isMultiPartyConferenceEnabled=function(){var e=this.getContactFeatures();return!(!e||!e.multiPartyConferenceEnabled)};var i=function(e){t.Contact.call(this,e.contactId),this.contactData=e};(i.prototype=Object.create(o.prototype)).constructor=i,i.prototype._getData=function(){return this.contactData},i.prototype._createConnectionAPI=function(e){return new t.ConnectionSnapshot(e)};var s=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};s.prototype._getData=function(){return t.core.getAgentDataProvider().getConnectionData(this.getContactId(),this.getConnectionId())},s.prototype.getContactId=function(){return this.contactId},s.prototype.getConnectionId=function(){return this.connectionId},s.prototype.getEndpoint=function(){return new t.Endpoint(this._getData().endpoint)},s.prototype.getAddress=s.prototype.getEndpoint,s.prototype.getState=function(){return this._getData().state},s.prototype.getStatus=s.prototype.getState,s.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},s.prototype.getStatusDuration=s.prototype.getStateDuration,s.prototype.getType=function(){return this._getData().type},s.prototype.isInitialConnection=function(){return this._getData().initial},s.prototype.isActive=function(){return t.contains(t.CONNECTION_ACTIVE_STATES,this.getStatus().type)},s.prototype.isConnected=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTED},s.prototype.isConnecting=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTING},s.prototype.isOnHold=function(){return this.getStatus().type===t.ConnectionStateType.HOLD},s.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},s.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},s.prototype.destroy=function(e){t.publishClickStreamData({contactId:this.getContactId(),clickType:t.ClickType.HANGUP,clickTime:(new Date).toISOString()}),t.core.getClient().call(t.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.sendDigits=function(e,n){t.core.getClient().call(t.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},n)},s.prototype.hold=function(e){t.core.getClient().call(t.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.resume=function(e){t.core.getClient().call(t.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.toSnapshot=function(){return new t.ConnectionSnapshot(this._getData())},s.prototype._initMediaController=function(){this.getMediaInfo()&&t.core.mediaFactory.get(this).catch((function(){}))},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING};var a=function(e){this.contactId=e};a.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){n.call(t.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),awsAccountId:t.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){if(e.contactData.customerId){var n={speakerId:e.contactData.customerId};t.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),r(n)}else{var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call");o(i)}},failure:function(e){t.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(n)}})}))},a.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){var n=JSON.parse(e);switch(n.status){case 400:case 404:var i=n;i.type=i.type?i.type:t.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,t.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),r(i);break;default:t.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();var s=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);o(s)}}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},a.prototype._optOutSpeakerInLcms=function(e,n){var r=this,o=t.core.getClient();return new Promise((function(i,s){o.call(t.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:r.contactId,InstanceId:t.core.getAgentDataProvider().getInstanceId(),AWSAccountId:t.core.getAgentDataProvider().getAWSAccountId(),CustomerId:t.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0,generatedSpeakerId:n}},{success:function(e){t.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),i(e)},failure:function(e){t.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);s(n)}})}))},a.prototype.optOutSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(s){var a=i.speakerId;n.call(t.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:t.assertNotNull(a,"speakerId"),DomainId:s},{success:function(n){e._optOutSpeakerInLcms(a,n.generatedSpeakerId).catch((function(){})),t.getLog().info("optOutSpeaker succeeded").withObject(n).sendInternalLogToServer(),r(n)},failure:function(e){t.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},a.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){t.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},a.prototype.startSession=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getDomainId().then((function(i){n.call(t.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),customerAccountId:t.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:i},{success:function(e){if(e.sessionId)r(e);else{t.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api");o(n)}},failure:function(e){t.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);o(n)}})})).catch((function(e){o(e)}))}))},a.prototype.evaluateSpeaker=function(e){var n=this;n.checkConferenceCall();var r=t.core.getClient(),o=t.core.getAgentDataProvider().getContactData(this.contactId),i=0;return new Promise((function(s,a){function c(){n.getDomainId().then((function(e){r.call(t.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:o.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++i=1&&(o=r.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i,"")),!o){t.getLog().info("getDomainId: no domainId found").sendInternalLogToServer();var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND);return void n(i)}t.getLog().info("getDomainId succeeded").withObject(r).sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.VoiceIdEvents.UPDATE_DOMAIN_ID,data:{domainId:o}}),e(o)}catch(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer(),i=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e),n(i)}},failure:function(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer();var r=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e);n(r)}}):n(new Error("Agent doesn't have the permission for Voice ID"))}))},a.prototype.checkConferenceCall=function(){if(t.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return t.contains(t.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new t.NotImplementedError("VoiceId is not supported for conference calls")},a.prototype.isAuthEnabled=function(e){return e!==t.ContactFlowAuthenticationDecision.NOT_ENABLED},a.prototype.isAuthResultNotEnoughSpeech=function(e){return e===t.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH},a.prototype.isAuthResultInconclusive=function(e){return e===t.ContactFlowAuthenticationDecision.INCONCLUSIVE},a.prototype.isFraudEnabled=function(e){return e!==t.ContactFlowFraudDetectionDecision.NOT_ENABLED},a.prototype.isFraudResultNotEnoughSpeech=function(e){return e===t.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH},a.prototype.isFraudResultInconclusive=function(e){return e===t.ContactFlowFraudDetectionDecision.INCONCLUSIVE};var c=function(e,t){this._speakerAuthenticator=new a(e),s.call(this,e,t)};(c.prototype=Object.create(s.prototype)).constructor=c,c.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},c.prototype.getMediaInfo=function(){return this._getData().softphoneMediaInfo},c.prototype.getMediaType=function(){return t.MediaType.SOFTPHONE},c.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},c.prototype.getVoiceIdSpeakerId=function(){return this._speakerAuthenticator.getSpeakerId()},c.prototype.getVoiceIdSpeakerStatus=function(){return this._speakerAuthenticator.getSpeakerStatus()},c.prototype.optOutVoiceIdSpeaker=function(){return this._speakerAuthenticator.optOutSpeaker()},c.prototype.deleteVoiceIdSpeaker=function(){return this._speakerAuthenticator.deleteSpeaker()},c.prototype.evaluateSpeakerWithVoiceId=function(e){return this._speakerAuthenticator.evaluateSpeaker(e)},c.prototype.enrollSpeakerInVoiceId=function(e){return this._speakerAuthenticator.enrollSpeaker(e)},c.prototype.updateVoiceIdSpeakerId=function(e){return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e)},c.prototype.getQuickConnectName=function(){return this._getData().quickConnectName},c.prototype.isMute=function(){return this._getData().mute},c.prototype.muteParticipant=function(e){t.core.getClient().call(t.ClientMethods.MUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},c.prototype.unmuteParticipant=function(e){t.core.getClient().call(t.ClientMethods.UNMUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)};var u=function(e,t){s.call(this,e,t)};(u.prototype=Object.create(s.prototype)).constructor=u,u.prototype.getMediaInfo=function(){var e=this._getData().chatMediaInfo;if(e){var n=t.core.getAgentDataProvider().getContactData(this.contactId),r={contactId:this.contactId,initialContactId:n.initialContactId||this.contactId,participantId:this.connectionId,getConnectionToken:t.hitch(this,this.getConnectionToken)};if(e.connectionData)try{r.participantToken=JSON.parse(e.connectionData).ConnectionAuthenticationToken}catch(n){t.getLog().error(t.LogComponent.CHAT,"Connection data is invalid").withObject(e).withException(n).sendInternalLogToServer(),r.participantToken=null}return r.participantToken=r.participantToken||null,r.originalInfo=this._getData().chatMediaInfo,r}return null},u.prototype.getConnectionToken=function(){var e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(this.contactId),r={transportType:t.TRANSPORT_TYPES.CHAT_TOKEN,participantId:this.connectionId,contactId:n.initialContactId||this.contactId};return new Promise((function(n,o){e.call(t.ClientMethods.CREATE_TRANSPORT,r,{success:function(e){t.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(),n(e)},failure:function(e,n){t.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({err:e,data:n}),o(Error("getConnectionToken failed"))}})}))},u.prototype.getMediaType=function(){return t.MediaType.CHAT},u.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},u.prototype._initMediaController=function(){this._isAgentConnectionType()&&t.core.mediaFactory.get(this).catch((function(){}))};var l=function(e,t){s.call(this,e,t)};(l.prototype=Object.create(s.prototype)).constructor=l,l.prototype.getMediaType=function(){return t.MediaType.TASK},l.prototype.getMediaInfo=function(){var e=t.core.getAgentDataProvider().getContactData(this.contactId);return{contactId:this.contactId,initialContactId:e.initialContactId||this.contactId}},l.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)};var p=function(e){t.Connection.call(this,e.contactId,e.connectionId),this.connectionData=e};(p.prototype=Object.create(s.prototype)).constructor=p,p.prototype._getData=function(){return this.connectionData},p.prototype._initMediaController=function(){};var d=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};d.prototype.stripPhoneNumber=function(){return this.phoneNumber?this.phoneNumber.replace(/sip:([^@]*)@.*/,"$1"):""},d.byPhoneNumber=function(e,n){return new d({type:t.EndpointType.PHONE_NUMBER,phoneNumber:e,name:n||null})};var h=function(e,t,n){this.errorType=e,this.errorMessage=t,this.endPointUrl=n};h.prototype.getErrorType=function(){return this.errorType},h.prototype.getErrorMessage=function(){return this.errorMessage},h.prototype.getEndPointUrl=function(){return this.endPointUrl},t.agent=function(e){var n=t.core.getEventBus().subscribe(t.AgentEvents.INIT,e);return t.agent.initialized&&e(new t.Agent),n},t.agent.initialized=!1,t.contact=function(e){return t.core.getEventBus().subscribe(t.ContactEvents.INIT,e)},t.onWebsocketInitFailure=function(e){var n=t.core.getEventBus().subscribe(t.WebSocketEvents.INIT_FAILURE,e);return t.webSocketInitFailed&&e(),n},t.ifMaster=function(e,n,r,o){if(t.assertNotNull(e,"A topic must be provided."),t.assertNotNull(n,"A true callback must be provided."),!t.core.masterClient)return t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e).sendInternalLogToServer(),void(r&&r());t.core.getMasterClient().call(t.MasterMethods.CHECK_MASTER,{topic:e,shouldNotBecomeMasterIfNone:o},{success:function(e){e.isMaster?n():r&&r()}})},t.becomeMaster=function(e,n,r){t.assertNotNull(e,"A topic must be provided."),t.core.masterClient?t.core.getMasterClient().call(t.MasterMethods.BECOME_MASTER,{topic:e},{success:function(){n&&n()}}):(t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e),r&&r())},t.Agent=n,t.AgentSnapshot=r,t.Contact=o,t.ContactSnapshot=i,t.Connection=c,t.BaseConnection=s,t.VoiceConnection=c,t.ChatConnection=u,t.TaskConnection=l,t.ConnectionSnapshot=p,t.Endpoint=d,t.Address=d,t.SoftphoneError=h,t.VoiceId=a}()},827:(e,t,n)=>{var r;!function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return o(t[s][1][e]||e)}),u,u.exports,e,t,n,r)}return n[s].exports}for(var i=void 0,s=0;s-1});var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]","[object DataView]"];t.exports={isEmptyData:function(e){return"string"==typeof e?0===e.length:0===e.byteLength},convertToBuffer:function(e){return"string"==typeof e&&(e=new r(e,"utf8")),ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}}},{"buffer/":85}],12:[function(e,t,n){var r=e("./browserHashUtils");function o(e,t){this.hash=new e,this.outer=new e;var n=function(e,t){var n=r.convertToBuffer(t);if(n.byteLength>e.BLOCK_SIZE){var o=new e;o.update(n),n=o.digest()}var i=new Uint8Array(e.BLOCK_SIZE);return i.set(n),i}(e,t),o=new Uint8Array(e.BLOCK_SIZE);o.set(n);for(var i=0;i>>32-o)+n&4294967295}function c(e,t,n,r,o,i,s){return a(t&n|~t&r,e,t,o,i,s)}function u(e,t,n,r,o,i,s){return a(t&r|n&~r,e,t,o,i,s)}function l(e,t,n,r,o,i,s){return a(t^n^r,e,t,o,i,s)}function p(e,t,n,r,o,i,s){return a(n^(t|~r),e,t,o,i,s)}t.exports=s,s.BLOCK_SIZE=i,s.prototype.update=function(e){if(r.isEmptyData(e))return this;if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=r.convertToBuffer(e),n=0,o=t.byteLength;for(this.bytesHashed+=o;o>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),o--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},s.prototype.digest=function(e){if(!this.finished){var t=this,n=t.buffer,r=t.bufferLength,s=8*t.bytesHashed;if(n.setUint8(this.bufferLength++,128),r%i>=56){for(var a=this.bufferLength;a>>0,!0),n.setUint32(60,Math.floor(s/4294967296),!0),this.hashBuffer(),this.finished=!0}var c=new DataView(new ArrayBuffer(16));for(a=0;a<4;a++)c.setUint32(4*a,this.state[a],!0);var u=new o(c.buffer,c.byteOffset,c.byteLength);return e?u.toString(e):u},s.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],i=t[3];n=c(n,r,o,i,e.getUint32(0,!0),7,3614090360),i=c(i,n,r,o,e.getUint32(4,!0),12,3905402710),o=c(o,i,n,r,e.getUint32(8,!0),17,606105819),r=c(r,o,i,n,e.getUint32(12,!0),22,3250441966),n=c(n,r,o,i,e.getUint32(16,!0),7,4118548399),i=c(i,n,r,o,e.getUint32(20,!0),12,1200080426),o=c(o,i,n,r,e.getUint32(24,!0),17,2821735955),r=c(r,o,i,n,e.getUint32(28,!0),22,4249261313),n=c(n,r,o,i,e.getUint32(32,!0),7,1770035416),i=c(i,n,r,o,e.getUint32(36,!0),12,2336552879),o=c(o,i,n,r,e.getUint32(40,!0),17,4294925233),r=c(r,o,i,n,e.getUint32(44,!0),22,2304563134),n=c(n,r,o,i,e.getUint32(48,!0),7,1804603682),i=c(i,n,r,o,e.getUint32(52,!0),12,4254626195),o=c(o,i,n,r,e.getUint32(56,!0),17,2792965006),n=u(n,r=c(r,o,i,n,e.getUint32(60,!0),22,1236535329),o,i,e.getUint32(4,!0),5,4129170786),i=u(i,n,r,o,e.getUint32(24,!0),9,3225465664),o=u(o,i,n,r,e.getUint32(44,!0),14,643717713),r=u(r,o,i,n,e.getUint32(0,!0),20,3921069994),n=u(n,r,o,i,e.getUint32(20,!0),5,3593408605),i=u(i,n,r,o,e.getUint32(40,!0),9,38016083),o=u(o,i,n,r,e.getUint32(60,!0),14,3634488961),r=u(r,o,i,n,e.getUint32(16,!0),20,3889429448),n=u(n,r,o,i,e.getUint32(36,!0),5,568446438),i=u(i,n,r,o,e.getUint32(56,!0),9,3275163606),o=u(o,i,n,r,e.getUint32(12,!0),14,4107603335),r=u(r,o,i,n,e.getUint32(32,!0),20,1163531501),n=u(n,r,o,i,e.getUint32(52,!0),5,2850285829),i=u(i,n,r,o,e.getUint32(8,!0),9,4243563512),o=u(o,i,n,r,e.getUint32(28,!0),14,1735328473),n=l(n,r=u(r,o,i,n,e.getUint32(48,!0),20,2368359562),o,i,e.getUint32(20,!0),4,4294588738),i=l(i,n,r,o,e.getUint32(32,!0),11,2272392833),o=l(o,i,n,r,e.getUint32(44,!0),16,1839030562),r=l(r,o,i,n,e.getUint32(56,!0),23,4259657740),n=l(n,r,o,i,e.getUint32(4,!0),4,2763975236),i=l(i,n,r,o,e.getUint32(16,!0),11,1272893353),o=l(o,i,n,r,e.getUint32(28,!0),16,4139469664),r=l(r,o,i,n,e.getUint32(40,!0),23,3200236656),n=l(n,r,o,i,e.getUint32(52,!0),4,681279174),i=l(i,n,r,o,e.getUint32(0,!0),11,3936430074),o=l(o,i,n,r,e.getUint32(12,!0),16,3572445317),r=l(r,o,i,n,e.getUint32(24,!0),23,76029189),n=l(n,r,o,i,e.getUint32(36,!0),4,3654602809),i=l(i,n,r,o,e.getUint32(48,!0),11,3873151461),o=l(o,i,n,r,e.getUint32(60,!0),16,530742520),n=p(n,r=l(r,o,i,n,e.getUint32(8,!0),23,3299628645),o,i,e.getUint32(0,!0),6,4096336452),i=p(i,n,r,o,e.getUint32(28,!0),10,1126891415),o=p(o,i,n,r,e.getUint32(56,!0),15,2878612391),r=p(r,o,i,n,e.getUint32(20,!0),21,4237533241),n=p(n,r,o,i,e.getUint32(48,!0),6,1700485571),i=p(i,n,r,o,e.getUint32(12,!0),10,2399980690),o=p(o,i,n,r,e.getUint32(40,!0),15,4293915773),r=p(r,o,i,n,e.getUint32(4,!0),21,2240044497),n=p(n,r,o,i,e.getUint32(32,!0),6,1873313359),i=p(i,n,r,o,e.getUint32(60,!0),10,4264355552),o=p(o,i,n,r,e.getUint32(24,!0),15,2734768916),r=p(r,o,i,n,e.getUint32(52,!0),21,1309151649),n=p(n,r,o,i,e.getUint32(16,!0),6,4149444226),i=p(i,n,r,o,e.getUint32(44,!0),10,3174756917),o=p(o,i,n,r,e.getUint32(8,!0),15,718787259),r=p(r,o,i,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=r+t[1]&4294967295,t[2]=o+t[2]&4294967295,t[3]=i+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":85}],14:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils");function i(){this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=new Uint32Array(80),this.offset=0,this.shift=24,this.totalLength=0}new Uint32Array([1518500249,1859775393,-1894007588,-899497514]),Math.pow(2,53),t.exports=i,i.BLOCK_SIZE=64,i.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=(e=o.convertToBuffer(e)).length;this.totalLength+=8*t;for(var n=0;n14||14===this.offset&&this.shift<24)&&this.processBlock(),this.offset=14,this.shift=24,this.write(0),this.write(0),this.write(this.totalLength>0xffffffffff?this.totalLength/1099511627776:0),this.write(this.totalLength>4294967295?this.totalLength/4294967296:0);for(var t=24;t>=0;t-=8)this.write(this.totalLength>>t);var n=new r(20),o=new DataView(n.buffer);return o.setUint32(0,this.h0,!1),o.setUint32(4,this.h1,!1),o.setUint32(8,this.h2,!1),o.setUint32(12,this.h3,!1),o.setUint32(16,this.h4,!1),e?n.toString(e):n},i.prototype.processBlock=function(){for(var e=16;e<80;e++){var t=this.block[e-3]^this.block[e-8]^this.block[e-14]^this.block[e-16];this.block[e]=t<<1|t>>>31}var n,r,o=this.h0,i=this.h1,s=this.h2,a=this.h3,c=this.h4;for(e=0;e<80;e++){e<20?(n=a^i&(s^a),r=1518500249):e<40?(n=i^s^a,r=1859775393):e<60?(n=i&s|a&(i|s),r=2400959708):(n=i^s^a,r=3395469782);var u=(o<<5|o>>>27)+n+c+r+(0|this.block[e]);c=a,a=s,s=i<<30|i>>>2,i=o,o=u}for(this.h0=this.h0+o|0,this.h1=this.h1+i|0,this.h2=this.h2+s|0,this.h3=this.h3+a|0,this.h4=this.h4+c|0,this.offset=0,e=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":85}],15:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils"),i=64,s=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=Math.pow(2,53)-1;function c(){this.state=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}t.exports=c,c.BLOCK_SIZE=i,c.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=0,n=(e=o.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>a)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},c.prototype.digest=function(e){if(!this.finished){var t=8*this.bytesHashed,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),o=this.bufferLength;if(n.setUint8(this.bufferLength++,128),o%i>=56){for(var s=this.bufferLength;s>>24&255,a[4*s+1]=this.state[s]>>>16&255,a[4*s+2]=this.state[s]>>>8&255,a[4*s+3]=this.state[s]>>>0&255;return e?a.toString(e):a},c.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],a=t[3],c=t[4],u=t[5],l=t[6],p=t[7],d=0;d>>17|h<<15)^(h>>>19|h<<13)^h>>>10,g=((h=this.temp[d-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(f+this.temp[d-7]|0)+(g+this.temp[d-16]|0)}var m=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(p+(s[d]+this.temp[d]|0)|0)|0,v=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&o^r&o)|0;p=l,l=u,u=c,c=a+m|0,a=o,o=r,r=n,n=m+v|0}t[0]+=n,t[1]+=r,t[2]+=o,t[3]+=a,t[4]+=c,t[5]+=u,t[6]+=l,t[7]+=p}},{"./browserHashUtils":11,"buffer/":85}],16:[function(e,t,n){(function(n){(function(){var n=e("./util");n.crypto.lib=e("./browserCryptoLib"),n.Buffer=e("buffer/").Buffer,n.url=e("url/"),n.querystring=e("querystring/"),n.realClock=e("./realclock/browserClock"),n.environment="js",n.createEventStream=e("./event-stream/buffered-create-event-stream").createEventStream,n.isBrowser=function(){return!0},n.isNode=function(){return!1};var r=e("./core");if(t.exports=r,e("./credentials"),e("./credentials/credential_provider_chain"),e("./credentials/temporary_credentials"),e("./credentials/chainable_temporary_credentials"),e("./credentials/web_identity_credentials"),e("./credentials/cognito_identity_credentials"),e("./credentials/saml_credentials"),r.XML.Parser=e("./xml/browser_parser"),e("./http/xhr"),void 0===o)var o={browser:!0}}).call(this)}).call(this,e("_process"))},{"./browserCryptoLib":10,"./core":19,"./credentials":20,"./credentials/chainable_temporary_credentials":21,"./credentials/cognito_identity_credentials":22,"./credentials/credential_provider_chain":23,"./credentials/saml_credentials":24,"./credentials/temporary_credentials":25,"./credentials/web_identity_credentials":26,"./event-stream/buffered-create-event-stream":28,"./http/xhr":36,"./realclock/browserClock":53,"./util":72,"./xml/browser_parser":73,_process:90,"buffer/":85,"querystring/":96,"url/":98}],17:[function(e,t,n){var r,o=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),o.Config=o.util.inherit({constructor:function(e){void 0===e&&(e={}),e=this.extractCredentials(e),o.util.each.call(this,this.keys,(function(t,n){this.set(t,e[t],n)}))},getCredentials:function(e){var t,n=this;function r(t){e(t,t?null:n.credentials)}function i(e,t){return new o.util.error(t||new Error,{code:"CredentialsError",message:e,name:"CredentialsError"})}n.credentials?"function"==typeof n.credentials.get?n.credentials.get((function(e){e&&(e=i("Could not load credentials from "+n.credentials.constructor.name,e)),r(e)})):(t=null,n.credentials.accessKeyId&&n.credentials.secretAccessKey||(t=i("Missing credentials")),r(t)):n.credentialProvider?n.credentialProvider.resolve((function(e,t){e&&(e=i("Could not load credentials from any providers",e)),n.credentials=t,r(e)})):r(i("No credentials to load"))},update:function(e,t){t=t||!1,e=this.extractCredentials(e),o.util.each.call(this,e,(function(e,n){(t||Object.prototype.hasOwnProperty.call(this.keys,e)||o.Service.hasService(e))&&this.set(e,n)}))},loadFromPath:function(e){this.clear();var t=JSON.parse(o.util.readFileSync(e)),n=new o.FileSystemCredentials(e),r=new o.CredentialProviderChain;return r.providers.unshift(n),r.resolve((function(e,n){if(e)throw e;t.credentials=n})),this.constructor(t),this},clear:function(){o.util.each.call(this,this.keys,(function(e){delete this[e]})),this.set("credentials",void 0),this.set("credentialProvider",void 0)},set:function(e,t,n){void 0===t?(void 0===n&&(n=this.keys[e]),this[e]="function"==typeof n?n.call(this):n):"httpOptions"===e&&this[e]?this[e]=o.util.merge(this[e],t):this[e]=t},keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:void 0,httpOptions:{timeout:12e4},maxRetries:void 0,maxRedirects:10,paramValidation:!0,sslEnabled:!0,s3ForcePathStyle:!1,s3BucketEndpoint:!1,s3DisableBodySigning:!0,s3UsEast1RegionalEndpoint:"legacy",s3UseArnRegion:void 0,computeChecksums:!0,convertResponseTypes:!0,correctClockSkew:!1,customUserAgent:null,dynamoDbCrc32:!0,systemClockOffset:0,signatureVersion:null,signatureCache:!0,retryDelayOptions:{},useAccelerateEndpoint:!1,clientSideMonitoring:!1,endpointDiscoveryEnabled:void 0,endpointCacheSize:1e3,hostPrefixEnabled:!0,stsRegionalEndpoints:"legacy",useFipsEndpoint:!1,useDualstackEndpoint:!1},extractCredentials:function(e){return e.accessKeyId&&e.secretAccessKey&&((e=o.util.copy(e)).credentials=new o.Credentials(e)),e},setPromisesDependency:function(e){r=e,null===e&&"function"==typeof Promise&&(r=Promise);var t=[o.Request,o.Credentials,o.CredentialProviderChain];o.S3&&(t.push(o.S3),o.S3.ManagedUpload&&t.push(o.S3.ManagedUpload)),o.util.addPromises(t,r)},getPromisesDependency:function(){return r}}),o.config=new o.Config},{"./core":19,"./credentials":20,"./credentials/credential_provider_chain":23}],18:[function(e,t,n){(function(n){(function(){var r=e("./core");function o(e,t){if("string"==typeof e){if(["legacy","regional"].indexOf(e.toLowerCase())>=0)return e.toLowerCase();throw r.util.error(new Error,t)}}t.exports=function(e,t){var i;if((e=e||{})[t.clientConfig]&&(i=o(e[t.clientConfig],{code:"InvalidConfiguration",message:'invalid "'+t.clientConfig+'" configuration. Expect "legacy" or "regional". Got "'+e[t.clientConfig]+'".'})))return i;if(!r.util.isNode())return i;if(Object.prototype.hasOwnProperty.call(n.env,t.env)&&(i=o(n.env[t.env],{code:"InvalidEnvironmentalVariable",message:"invalid "+t.env+' environmental variable. Expect "legacy" or "regional". Got "'+n.env[t.env]+'".'})))return i;var s={};try{s=r.util.getProfilesFromSharedConfig(r.util.iniLoader)[n.env.AWS_PROFILE||r.util.defaultProfile]}catch(e){}return s&&Object.prototype.hasOwnProperty.call(s,t.sharedConfig)&&(i=o(s[t.sharedConfig],{code:"InvalidConfiguration",message:"invalid "+t.sharedConfig+' profile config. Expect "legacy" or "regional". Got "'+s[t.sharedConfig]+'".'})),i}}).call(this)}).call(this,e("_process"))},{"./core":19,_process:90}],19:[function(e,t,n){var r={util:e("./util")};({}).toString(),t.exports=r,r.util.update(r,{VERSION:"2.1189.0",Signers:{},Protocol:{Json:e("./protocol/json"),Query:e("./protocol/query"),Rest:e("./protocol/rest"),RestJson:e("./protocol/rest_json"),RestXml:e("./protocol/rest_xml")},XML:{Builder:e("./xml/builder"),Parser:null},JSON:{Builder:e("./json/builder"),Parser:e("./json/parser")},Model:{Api:e("./model/api"),Operation:e("./model/operation"),Shape:e("./model/shape"),Paginator:e("./model/paginator"),ResourceWaiter:e("./model/resource_waiter")},apiLoader:e("./api_loader"),EndpointCache:e("../vendor/endpoint-cache").EndpointCache}),e("./sequential_executor"),e("./service"),e("./config"),e("./http"),e("./event_listeners"),e("./request"),e("./response"),e("./resource_waiter"),e("./signers/request_signer"),e("./param_validator"),r.events=new r.SequentialExecutor,r.util.memoizedProperty(r,"endpointCache",(function(){return new r.EndpointCache(r.config.endpointCacheSize)}),!0)},{"../vendor/endpoint-cache":109,"./api_loader":9,"./config":17,"./event_listeners":34,"./http":35,"./json/builder":37,"./json/parser":38,"./model/api":39,"./model/operation":41,"./model/paginator":42,"./model/resource_waiter":43,"./model/shape":44,"./param_validator":45,"./protocol/json":47,"./protocol/query":48,"./protocol/rest":49,"./protocol/rest_json":50,"./protocol/rest_xml":51,"./request":57,"./resource_waiter":58,"./response":59,"./sequential_executor":60,"./service":61,"./signers/request_signer":64,"./util":72,"./xml/builder":74}],20:[function(e,t,n){var r=e("./core");r.Credentials=r.util.inherit({constructor:function(){if(r.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"==typeof arguments[0]){var e=arguments[0].credentials||arguments[0];this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken}else this.accessKeyId=arguments[0],this.secretAccessKey=arguments[1],this.sessionToken=arguments[2]},expiryWindow:15,needsRefresh:function(){var e=r.util.date.getDate().getTime(),t=new Date(e+1e3*this.expiryWindow);return!!(this.expireTime&&t>this.expireTime)||this.expired||!this.accessKeyId||!this.secretAccessKey},get:function(e){var t=this;this.needsRefresh()?this.refresh((function(n){n||(t.expired=!1),e&&e(n)})):e&&e()},refresh:function(e){this.expired=!1,e()},coalesceRefresh:function(e,t){var n=this;1===n.refreshCallbacks.push(e)&&n.load((function(e){r.util.arrayEach(n.refreshCallbacks,(function(n){t?n(e):r.util.defer((function(){n(e)}))})),n.refreshCallbacks.length=0}))},load:function(e){e()}}),r.Credentials.addPromisesToClass=function(e){this.prototype.getPromise=r.util.promisifyMethod("get",e),this.prototype.refreshPromise=r.util.promisifyMethod("refresh",e)},r.Credentials.deletePromisesFromClass=function(){delete this.prototype.getPromise,delete this.prototype.refreshPromise},r.util.addPromises(r.Credentials)},{"./core":19}],21:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.ChainableTemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=r.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new r.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}var n=r.util.merge({params:t,credentials:e.masterCredentials||r.config.credentials},e.stsConfig||{});this.service=new o(n)},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this,n=t.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode((function(r,o){var i={};r?e(r):(o&&(i.TokenCode=o),t.service[n](i,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)})))}))},getTokenCode:function(e){var t=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,(function(n,o){if(n){var i=n;return n instanceof Error&&(i=n.message),void e(r.util.error(new Error("Error fetching MFA token: "+i),{code:t.errorCode}))}e(null,o)})):e(null)}})},{"../../clients/sts":8,"../core":19}],22:[function(e,t,n){var r=e("../core"),o=e("../../clients/cognitoidentity"),i=e("../../clients/sts");r.CognitoIdentityCredentials=r.util.inherit(r.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=r.util.copy(t||{}),this.loadCachedId();var n=this;Object.defineProperty(this,"identityId",{get:function(){return n.loadCachedId(),n._identityId||n.params.IdentityId},set:function(e){n._identityId=e}})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.data=null,t._identityId=null,t.getId((function(n){n?(t.clearIdOnNotAuthorized(n),e(n)):t.params.RoleArn?t.getCredentialsFromSTS(e):t.getCredentialsForIdentity(e)}))},clearCachedId:function(){this._identityId=null,delete this.params.IdentityId;var e=this.params.IdentityPoolId,t=this.params.LoginId||"";delete this.storage[this.localStorageKey.id+e+t],delete this.storage[this.localStorageKey.providers+e+t]},clearIdOnNotAuthorized:function(e){"NotAuthorizedException"==e.code&&this.clearCachedId()},getId:function(e){var t=this;if("string"==typeof t.params.IdentityId)return e(null,t.params.IdentityId);t.cognito.getId((function(n,r){!n&&r.IdentityId?(t.params.IdentityId=r.IdentityId,e(null,r.IdentityId)):e(n)}))},loadCredentials:function(e,t){e&&t&&(t.expired=!1,t.accessKeyId=e.Credentials.AccessKeyId,t.secretAccessKey=e.Credentials.SecretKey,t.sessionToken=e.Credentials.SessionToken,t.expireTime=e.Credentials.Expiration)},getCredentialsForIdentity:function(e){var t=this;t.cognito.getCredentialsForIdentity((function(n,r){n?t.clearIdOnNotAuthorized(n):(t.cacheId(r),t.data=r,t.loadCredentials(t.data,t)),e(n)}))},getCredentialsFromSTS:function(e){var t=this;t.cognito.getOpenIdToken((function(n,r){n?(t.clearIdOnNotAuthorized(n),e(n)):(t.cacheId(r),t.params.WebIdentityToken=r.Token,t.webIdentityCredentials.refresh((function(n){n||(t.data=t.webIdentityCredentials.data,t.sts.credentialsFrom(t.data,t)),e(n)})))}))},loadCachedId:function(){var e=this;if(r.util.isBrowser()&&!e.params.IdentityId){var t=e.getStorage("id");if(t&&e.params.Logins){var n=Object.keys(e.params.Logins);0!==(e.getStorage("providers")||"").split(",").filter((function(e){return-1!==n.indexOf(e)})).length&&(e.params.IdentityId=t)}else t&&(e.params.IdentityId=t)}},createClients:function(){var e=this._clientConfig;if(this.webIdentityCredentials=this.webIdentityCredentials||new r.WebIdentityCredentials(this.params,e),!this.cognito){var t=r.util.merge({},e);t.params=this.params,this.cognito=new o(t)}this.sts=this.sts||new i(e)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,r.util.isBrowser()&&(this.setStorage("id",e.IdentityId),this.params.Logins&&this.setStorage("providers",Object.keys(this.params.Logins).join(",")))},getStorage:function(e){return this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]},setStorage:function(e,t){try{this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]=t}catch(e){}},storage:function(){try{var e=r.util.isBrowser()&&null!==window.localStorage&&"object"==typeof window.localStorage?window.localStorage:{};return e["aws.test-storage"]="foobar",delete e["aws.test-storage"],e}catch(e){return{}}}()})},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":19}],23:[function(e,t,n){var r=e("../core");r.CredentialProviderChain=r.util.inherit(r.Credentials,{constructor:function(e){this.providers=e||r.CredentialProviderChain.defaultProviders.slice(0),this.resolveCallbacks=[]},resolve:function(e){var t=this;if(0===t.providers.length)return e(new Error("No providers")),t;if(1===t.resolveCallbacks.push(e)){var n=0,o=t.providers.slice(0);!function e(i,s){if(!i&&s||n===o.length)return r.util.arrayEach(t.resolveCallbacks,(function(e){e(i,s)})),void(t.resolveCallbacks.length=0);var a=o[n++];(s="function"==typeof a?a.call():a).get?s.get((function(t){e(t,t?null:s)})):e(null,s)}()}return t}}),r.CredentialProviderChain.defaultProviders=[],r.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=r.util.promisifyMethod("resolve",e)},r.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},r.util.addPromises(r.CredentialProviderChain)},{"../core":19}],24:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.SAMLCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithSAML((function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":19}],25:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.TemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.loadMasterCredentials(t),this.expired=!0,this.params=e||{},this.params.RoleArn&&(this.params.RoleSessionName=this.params.RoleSessionName||"temporary-credentials")},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.masterCredentials.get((function(){t.service.config.credentials=t.masterCredentials,(t.params.RoleArn?t.service.assumeRole:t.service.getSessionToken).call(t.service,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))}))},loadMasterCredentials:function(e){for(this.masterCredentials=e||r.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new r.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":19}],26:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.WebIdentityCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=r.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithWebIdentity((function(n,r){t.data=null,n||(t.data=r,t.service.credentialsFrom(r,t)),e(n)}))},createClients:function(){if(!this.service){var e=r.util.merge({},this._clientConfig);e.params=this.params,this.service=new o(e)}}})},{"../../clients/sts":8,"../core":19}],27:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./util"),i=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function s(e){var t=e.service,n=t.api||{},r=(n.operations,{});return t.config.region&&(r.region=t.config.region),n.serviceId&&(r.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(r.accessKeyId=t.config.credentials.accessKeyId),r}function a(e,t,n){n&&null!=t&&"structure"===n.type&&n.required&&n.required.length>0&&o.arrayEach(n.required,(function(r){var o=n.members[r];if(!0===o.endpointDiscoveryId){var i=o.isLocationName?o.name:r;e[i]=String(t[r])}else a(e,t[r],o)}))}function c(e,t){var n={};return a(n,e.params,t),n}function u(e){var t=e.service,n=t.api,i=n.operations?n.operations[e.operation]:void 0,a=c(e,i?i.input:void 0),u=s(e);Object.keys(a).length>0&&(u=o.update(u,a),i&&(u.operation=i.name));var l=r.endpointCache.get(u);if(!l||1!==l.length||""!==l[0].Address)if(l&&l.length>0)e.httpRequest.updateEndpoint(l[0].Address);else{var p=t.makeRequest(n.endpointOperation,{Operation:i.name,Identifiers:a});d(p),p.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),p.removeListener("retry",r.EventListeners.Core.RETRY_CHECK),r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}]),p.send((function(e,t){t&&t.Endpoints?r.endpointCache.put(u,t.Endpoints):e&&r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}])}))}}var l={};function p(e,t){var n=e.service,i=n.api,a=i.operations?i.operations[e.operation]:void 0,u=a?a.input:void 0,p=c(e,u),h=s(e);Object.keys(p).length>0&&(h=o.update(h,p),a&&(h.operation=a.name));var f=r.EndpointCache.getKeyString(h),g=r.endpointCache.get(f);if(g&&1===g.length&&""===g[0].Address)return l[f]||(l[f]=[]),void l[f].push({request:e,callback:t});if(g&&g.length>0)e.httpRequest.updateEndpoint(g[0].Address),t();else{var m=n.makeRequest(i.endpointOperation,{Operation:a.name,Identifiers:p});m.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),d(m),r.endpointCache.put(f,[{Address:"",CachePeriodInMinutes:60}]),m.send((function(n,i){if(n){if(e.response.error=o.error(n,{retryable:!1}),r.endpointCache.remove(h),l[f]){var s=l[f];o.arrayEach(s,(function(e){e.request.response.error=o.error(n,{retryable:!1}),e.callback()})),delete l[f]}}else i&&(r.endpointCache.put(f,i.Endpoints),e.httpRequest.updateEndpoint(i.Endpoints[0].Address),l[f])&&(s=l[f],o.arrayEach(s,(function(e){e.request.httpRequest.updateEndpoint(i.Endpoints[0].Address),e.callback()})),delete l[f]);t()}))}}function d(e){var t=e.service.api.apiVersion;t&&!e.httpRequest.headers["x-amz-api-version"]&&(e.httpRequest.headers["x-amz-api-version"]=t)}function h(e){var t=e.error,n=e.httpResponse;if(t&&("InvalidEndpointException"===t.code||421===n.statusCode)){var i=e.request,a=i.service.api.operations||{},u=c(i,a[i.operation]?a[i.operation].input:void 0),l=s(i);Object.keys(u).length>0&&(l=o.update(l,u),a[i.operation]&&(l.operation=a[i.operation].name)),r.endpointCache.remove(l)}}function f(e){return["false","0"].indexOf(e)>=0}t.exports={discoverEndpoint:function(e,t){var s=e.service||{};if(function(e){if(e._originalConfig&&e._originalConfig.endpoint&&!0===e._originalConfig.endpointDiscoveryEnabled)throw o.error(new Error,{code:"ConfigurationException",message:"Custom endpoint is supplied; endpointDiscoveryEnabled must not be true."});var t=r.config[e.serviceIdentifier]||{};return Boolean(r.config.endpoint||t.endpoint||e._originalConfig&&e._originalConfig.endpoint)}(s)||e.isPresigned())return t();var a=(s.api.operations||{})[e.operation],c=a?a.endpointDiscoveryRequired:"NULL",l=function(e){var t=e.service||{};if(void 0!==t.config.endpointDiscoveryEnabled)return t.config.endpointDiscoveryEnabled;if(!o.isBrowser()){for(var s=0;s-1&&(e[t]++,0===e[t]);t--);}i.fromNumber=function(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(e+" is too large (or, if negative, too small) to represent as an Int64");for(var t=new Uint8Array(8),n=7,r=Math.abs(Math.round(e));n>-1&&r>0;n--,r/=256)t[n]=r;return e<0&&s(t),new i(t)},i.prototype.valueOf=function(){var e=this.bytes.slice(0),t=128&e[0];return t&&s(e),parseInt(e.toString("hex"),16)*(t?-1:1)},i.prototype.toString=function(){return String(this.valueOf())},t.exports={Int64:i}},{"../core":19}],31:[function(e,t,n){var r=e("./parse-message").parseMessage;t.exports={parseEvent:function(e,t,n){var o=r(t),i=o.headers[":message-type"];if(i){if("error"===i.value)throw function(e){var t=e.headers[":error-code"],n=e.headers[":error-message"],r=new Error(n.value||n);return r.code=r.name=t.value||t,r}(o);if("event"!==i.value)return}var s=o.headers[":event-type"],a=n.members[s.value];if(a){var c={},u=a.eventPayloadMemberName;if(u){var l=a.members[u];"binary"===l.type?c[u]=o.body:c[u]=e.parse(o.body.toString(),l)}for(var p=a.eventHeaderMemberNames,d=0;d=0)return e.httpRequest.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",t();n.util.computeSha256(i,(function(n,r){n?t(n):(e.httpRequest.headers["X-Amz-Content-Sha256"]=r,t())}))}else t()}})),e("SET_CONTENT_LENGTH","afterBuild",(function(e){var t=function(e){if(!e.service.api.operations)return"";var t=e.service.api.operations[e.operation];return t?t.authtype:""}(e),r=n.util.getRequestPayloadShape(e);if(void 0===e.httpRequest.headers["Content-Length"])try{var o=n.util.string.byteLength(e.httpRequest.body);e.httpRequest.headers["Content-Length"]=o}catch(n){if(r&&r.isStreaming){if(r.requiresLength)throw n;if(t.indexOf("unsigned-body")>=0)return void(e.httpRequest.headers["Transfer-Encoding"]="chunked");throw n}throw n}})),e("SET_HTTP_HOST","afterBuild",(function(e){e.httpRequest.headers.Host=e.httpRequest.endpoint.host})),e("SET_TRACE_ID","afterBuild",(function(e){var r="X-Amzn-Trace-Id";if(n.util.isNode()&&!Object.hasOwnProperty.call(e.httpRequest.headers,r)){var o=t.env.AWS_LAMBDA_FUNCTION_NAME,i=t.env._X_AMZN_TRACE_ID;"string"==typeof o&&o.length>0&&"string"==typeof i&&i.length>0&&(e.httpRequest.headers[r]=i)}})),e("RESTART","restart",(function(){var e=this.response.error;e&&e.retryable&&(this.httpRequest=new n.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,r,o){r.httpResponse.statusCode=e,r.httpResponse.statusMessage=o,r.httpResponse.headers=t,r.httpResponse.body=n.util.buffer.toBuffer(""),r.httpResponse.buffers=[],r.httpResponse.numBytes=0;var i=t.date||t.Date,s=r.request.service;if(i){var a=Date.parse(i);s.config.correctClockSkew&&s.isClockSkewed(a)&&s.applyClockOffset(a)}})),e("HTTP_DATA","httpData",(function(e,t){if(e){if(n.util.isNode()){t.httpResponse.numBytes+=e.length;var r=t.httpResponse.headers["content-length"],o={loaded:t.httpResponse.numBytes,total:r};t.request.emit("httpDownloadProgress",[o,t])}t.httpResponse.buffers.push(n.util.buffer.toBuffer(e))}})),e("HTTP_DONE","httpDone",(function(e){if(e.httpResponse.buffers&&e.httpResponse.buffers.length>0){var t=n.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 n.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=0?(e.error=null,setTimeout(t,n)):t()}))})),CorePost:(new r).addNamedListeners((function(e){e("EXTRACT_REQUEST_ID","extractData",n.util.extractRequestId),e("EXTRACT_REQUEST_ID","extractError",n.util.extractRequestId),e("ENOTFOUND_ERROR","httpError",(function(e){if("NetworkingError"===e.code&&function(e){return"ENOTFOUND"===e.errno||"number"==typeof e.errno&&"function"==typeof n.util.getSystemErrorName&&["EAI_NONAME","EAI_NODATA"].indexOf(n.util.getSystemErrorName(e.errno)>=0)}(e)){var t="Inaccessible host: `"+e.hostname+"' at port `"+e.port+"'. This service may not be available in the `"+e.region+"' region.";this.response.error=n.util.error(new Error(t),{code:"UnknownEndpoint",region:e.region,hostname:e.hostname,retryable:!0,originalError:e})}}))})),Logger:(new r).addNamedListeners((function(t){t("LOG_REQUEST","complete",(function(t){var r=t.request,o=r.service.config.logger;if(o){var i=function(){var i=(t.request.service.getSkewCorrectedDate().getTime()-r.startTime.getTime())/1e3,a=!!o.isTTY,c=t.httpResponse.statusCode,u=r.params;r.service.api.operations&&r.service.api.operations[r.operation]&&r.service.api.operations[r.operation].input&&(u=s(r.service.api.operations[r.operation].input,r.params));var l=e("util").inspect(u,!0,null),p="";return a&&(p+=""),p+="[AWS "+r.service.serviceIdentifier+" "+c,p+=" "+i.toString()+"s "+t.retryCount+" retries]",a&&(p+=""),p+=" "+n.util.string.lowerFirst(r.operation),p+="("+l+")",a&&(p+=""),p}();"function"==typeof o.log?o.log(i):"function"==typeof o.write&&o.write(i+"\n")}function s(e,t){if(!t)return t;if(e.isSensitive)return"***SensitiveInformation***";switch(e.type){case"structure":var r={};return n.util.each(t,(function(t,n){Object.prototype.hasOwnProperty.call(e.members,t)?r[t]=s(e.members[t],n):r[t]=n})),r;case"list":var o=[];return n.util.arrayEach(t,(function(t,n){o.push(s(e.member,t))})),o;case"map":var i={};return n.util.each(t,(function(t,n){i[t]=s(e.value,n)})),i;default:return t}}}))})),Json:(new r).addNamedListeners((function(t){var n=e("./protocol/json");t("BUILD","build",n.buildRequest),t("EXTRACT_DATA","extractData",n.extractData),t("EXTRACT_ERROR","extractError",n.extractError)})),Rest:(new r).addNamedListeners((function(t){var n=e("./protocol/rest");t("BUILD","build",n.buildRequest),t("EXTRACT_DATA","extractData",n.extractData),t("EXTRACT_ERROR","extractError",n.extractError)})),RestJson:(new r).addNamedListeners((function(t){var n=e("./protocol/rest_json");t("BUILD","build",n.buildRequest),t("EXTRACT_DATA","extractData",n.extractData),t("EXTRACT_ERROR","extractError",n.extractError)})),RestXml:(new r).addNamedListeners((function(t){var n=e("./protocol/rest_xml");t("BUILD","build",n.buildRequest),t("EXTRACT_DATA","extractData",n.extractData),t("EXTRACT_ERROR","extractError",n.extractError)})),Query:(new r).addNamedListeners((function(t){var n=e("./protocol/query");t("BUILD","build",n.buildRequest),t("EXTRACT_DATA","extractData",n.extractData),t("EXTRACT_ERROR","extractError",n.extractError)}))}}).call(this)}).call(this,e("_process"))},{"./core":19,"./discover_endpoint":27,"./protocol/json":47,"./protocol/query":48,"./protocol/rest":49,"./protocol/rest_json":50,"./protocol/rest_xml":51,"./sequential_executor":60,_process:90,util:84}],35:[function(e,t,n){var r=e("./core"),o=r.util.inherit;r.Endpoint=o({constructor:function(e,t){if(r.util.hideProperties(this,["slashes","auth","hash","search","query"]),null==e)throw new Error("Invalid endpoint: "+e);if("string"!=typeof e)return r.util.copy(e);e.match(/^http/)||(e=((t&&void 0!==t.sslEnabled?t.sslEnabled:r.config.sslEnabled)?"https":"http")+"://"+e),r.util.update(this,r.util.urlParse(e)),this.port?this.port=parseInt(this.port,10):this.port="https:"===this.protocol?443:80}}),r.HttpRequest=o({constructor:function(e,t){e=new r.Endpoint(e),this.method="POST",this.path=e.path||"/",this.headers={},this.body="",this.endpoint=e,this.region=t,this._userAgent="",this.setUserAgent()},setUserAgent:function(){this._userAgent=this.headers[this.getUserAgentHeaderName()]=r.util.userAgent()},getUserAgentHeaderName:function(){return(r.util.isBrowser()?"X-Amz-":"")+"User-Agent"},appendToUserAgent:function(e){"string"==typeof e&&e&&(this._userAgent+=" "+e),this.headers[this.getUserAgentHeaderName()]=this._userAgent},getUserAgent:function(){return this._userAgent},pathname:function(){return this.path.split("?",1)[0]},search:function(){var e=this.path.split("?",2)[1];return e?(e=r.util.queryStringParse(e),r.util.queryParamsToString(e)):""},updateEndpoint:function(e){var t=new r.Endpoint(e);this.endpoint=t,this.path=t.path||"/",this.headers.Host&&(this.headers.Host=t.host)}}),r.HttpResponse=o({constructor:function(){this.statusCode=void 0,this.headers={},this.body=void 0,this.streaming=!1,this.stream=null},createUnbufferedStream:function(){return this.streaming=!0,this.stream}}),r.HttpClient=o({}),r.HttpClient.getInstance=function(){return void 0===this.singleton&&(this.singleton=new this),this.singleton}},{"./core":19}],36:[function(e,t,n){var r=e("../core"),o=e("events").EventEmitter;e("../http"),r.XHRClient=r.util.inherit({handleRequest:function(e,t,n,i){var s=this,a=e.endpoint,c=new o,u=a.protocol+"//"+a.hostname;80!==a.port&&443!==a.port&&(u+=":"+a.port),u+=e.path;var l=new XMLHttpRequest,p=!1;e.stream=l,l.addEventListener("readystatechange",(function(){try{if(0===l.status)return}catch(e){return}this.readyState>=this.HEADERS_RECEIVED&&!p&&(c.statusCode=l.status,c.headers=s.parseHeaders(l.getAllResponseHeaders()),c.emit("headers",c.statusCode,c.headers,l.statusText),p=!0),this.readyState===this.DONE&&s.finishRequest(l,c)}),!1),l.upload.addEventListener("progress",(function(e){c.emit("sendProgress",e)})),l.addEventListener("progress",(function(e){c.emit("receiveProgress",e)}),!1),l.addEventListener("timeout",(function(){i(r.util.error(new Error("Timeout"),{code:"TimeoutError"}))}),!1),l.addEventListener("error",(function(){i(r.util.error(new Error("Network Failure"),{code:"NetworkingError"}))}),!1),l.addEventListener("abort",(function(){i(r.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))}),!1),n(c),l.open(e.method,u,!1!==t.xhrAsync),r.util.each(e.headers,(function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&l.setRequestHeader(e,t)})),t.timeout&&!1!==t.xhrAsync&&(l.timeout=t.timeout),t.xhrWithCredentials&&(l.withCredentials=!0);try{l.responseType="arraybuffer"}catch(e){}try{e.body?l.send(e.body):l.send()}catch(t){if(!e.body||"object"!=typeof e.body.buffer)throw t;l.send(e.body.buffer)}return c},parseHeaders:function(e){var t={};return r.util.arrayEach(e.split(/\r?\n/),(function(e){var n=e.split(":",1)[0],r=e.substring(n.length+2);n.length>0&&(t[n.toLowerCase()]=r)})),t},finishRequest:function(e,t){var n;if("arraybuffer"===e.responseType&&e.response){var o=e.response;n=new r.util.Buffer(o.byteLength);for(var i=new Uint8Array(o),s=0;s-1?t||"":t,this.isJsonValue?JSON.parse(t):t&&"function"==typeof t.toString?t.toString():t},this.toWireFormat=function(e){return this.isJsonValue?JSON.stringify(e):e}}function h(){a.apply(this,arguments),this.toType=function(e){var t=o.base64.decode(e);if(this.isSensitive&&o.isNode()&&"function"==typeof o.Buffer.alloc){var n=o.Buffer.alloc(t.length,t);t.fill(0),t=n}return t},this.toWireFormat=o.base64.encode}function f(){h.apply(this,arguments)}function g(){a.apply(this,arguments),this.toType=function(e){return"boolean"==typeof e?e:null==e?null:"true"===e}}a.normalizedTypes={character:"string",double:"float",long:"integer",short:"integer",biginteger:"integer",bigdecimal:"float",blob:"binary"},a.types={structure:u,list:l,map:p,boolean:g,timestamp:function(e){var t=this;if(a.apply(this,arguments),e.timestampFormat)i(this,"timestampFormat",e.timestampFormat);else if(t.isTimestampFormatSet&&this.timestampFormat)i(this,"timestampFormat",this.timestampFormat);else if("header"===this.location)i(this,"timestampFormat","rfc822");else if("querystring"===this.location)i(this,"timestampFormat","iso8601");else if(this.api)switch(this.api.protocol){case"json":case"rest-json":i(this,"timestampFormat","unixTimestamp");break;case"rest-xml":case"query":case"ec2":i(this,"timestampFormat","iso8601")}this.toType=function(e){return null==e?null:"function"==typeof e.toUTCString?e:"string"==typeof e||"number"==typeof e?o.date.parseTimestamp(e):null},this.toWireFormat=function(e){return o.date.format(e,t.timestampFormat)}},float:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseFloat(e)},this.toWireFormat=this.toType},integer:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseInt(e,10)},this.toWireFormat=this.toType},string:d,base64:f,binary:h},a.resolve=function(e,t){if(e.shape){var n=t.api.shapes[e.shape];if(!n)throw new Error("Cannot find shape reference: "+e.shape);return n}return null},a.create=function(e,t,n){if(e.isShape)return e;var r=a.resolve(e,t);if(r){var o=Object.keys(e);t.documentation||(o=o.filter((function(e){return!e.match(/documentation/)})));var i=function(){r.constructor.call(this,e,t,n)};return i.prototype=r,new i}e.type||(e.members?e.type="structure":e.member?e.type="list":e.key?e.type="map":e.type="string");var s=e.type;if(a.normalizedTypes[e.type]&&(e.type=a.normalizedTypes[e.type]),a.types[e.type])return new a.types[e.type](e,t,n);throw new Error("Unrecognized shape type: "+s)},a.shapes={StructureShape:u,ListShape:l,MapShape:p,StringShape:d,BooleanShape:g,Base64Shape:f},t.exports=a},{"../util":72,"./collection":40}],45:[function(e,t,n){var r=e("./core");r.ParamValidator=r.util.inherit({constructor:function(e){!0!==e&&void 0!==e||(e={min:!0}),this.validation=e},validate:function(e,t,n){if(this.errors=[],this.validateMember(e,t||{},n||"params"),this.errors.length>1){var o=this.errors.join("\n* ");throw o="There were "+this.errors.length+" validation errors:\n* "+o,r.util.error(new Error(o),{code:"MultipleValidationErrors",errors:this.errors})}if(1===this.errors.length)throw this.errors[0];return!0},fail:function(e,t){this.errors.push(r.util.error(new Error(t),{code:e}))},validateStructure:function(e,t,n){if(e.isDocument)return!0;var r;this.validateType(t,n,["object"],"structure");for(var o=0;e.required&&o= 1, but found "'+t+'" for '+n)},validatePattern:function(e,t,n){this.validation.pattern&&void 0!==e.pattern&&(new RegExp(e.pattern).test(t)||this.fail("PatternMatchError",'Provided value "'+t+'" does not match regex pattern /'+e.pattern+"/ for "+n))},validateRange:function(e,t,n,r){this.validation.min&&void 0!==e.min&&t= "+e.min+", but found "+t+" for "+n),this.validation.max&&void 0!==e.max&&t>e.max&&this.fail("MaxRangeError","Expected "+r+" <= "+e.max+", but found "+t+" for "+n)},validateEnum:function(e,t,n){this.validation.enum&&void 0!==e.enum&&-1===e.enum.indexOf(t)&&this.fail("EnumError","Found string value of "+t+", but expected "+e.enum.join("|")+" for "+n)},validateType:function(e,t,n,o){if(null==e)return!1;for(var i=!1,s=0;s63)throw r.error(new Error,{code:"ValidationError",message:"Hostname label length should be between 1 to 63 characters, inclusive."});if(!i.test(e))throw o.util.error(new Error,{code:"ValidationError",message:e+" is not hostname compatible."})}))}return e}}},{"../core":19,"../util":72}],47:[function(e,t,n){var r=e("../util"),o=e("../json/builder"),i=e("../json/parser"),s=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.httpRequest,n=e.service.api,r=n.targetPrefix+"."+n.operations[e.operation].name,i=n.jsonVersion||"1.0",a=n.operations[e.operation].input,c=new o;1===i&&(i="1.0"),t.body=c.build(e.params||{},a),t.headers["Content-Type"]="application/x-amz-json-"+i,t.headers["X-Amz-Target"]=r,s(e)},extractError:function(e){var t={},n=e.httpResponse;if(t.code=n.headers["x-amzn-errortype"]||"UnknownError","string"==typeof t.code&&(t.code=t.code.split(":")[0]),n.body.length>0)try{var o=JSON.parse(n.body.toString()),i=o.__type||o.code||o.Code;i&&(t.code=i.split("#").pop()),"RequestEntityTooLarge"===t.code?t.message="Request body must be less than 1 MB":t.message=o.message||o.Message||null}catch(o){t.statusCode=n.statusCode,t.message=n.statusMessage}else t.statusCode=n.statusCode,t.message=n.statusCode.toString();e.error=r.error(new Error,t)},extractData:function(e){var t=e.httpResponse.body.toString()||"{}";if(!1===e.request.service.config.convertResponseTypes)e.data=JSON.parse(t);else{var n=e.request.service.api.operations[e.request.operation].output||{},r=new i;e.data=r.parse(t,n)}}}},{"../json/builder":37,"../json/parser":38,"../util":72,"./helpers":46}],48:[function(e,t,n){var r=e("../core"),o=e("../util"),i=e("../query/query_param_serializer"),s=e("../model/shape"),a=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.service.api.operations[e.operation],n=e.httpRequest;n.headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8",n.params={Version:e.service.api.apiVersion,Action:t.name},(new i).serialize(e.params,t.input,(function(e,t){n.params[e]=t})),n.body=o.queryParamsToString(n.params),a(e)},extractError:function(e){var t,n=e.httpResponse.body.toString();if(n.match("=0?"&":"?";var c=[];r.arrayEach(Object.keys(s).sort(),(function(e){Array.isArray(s[e])||(s[e]=[s[e]]);for(var t=0;t0){var p=(t=new r.XML.Parser).parse(s.toString(),c);o.update(e.data,p)}}}},{"../core":19,"../util":72,"./rest":49}],52:[function(e,t,n){var r=e("../util");function o(){}function i(e){return e.isQueryName||"ec2"!==e.api.protocol?e.name:e.name[0].toUpperCase()+e.name.substr(1)}function s(e,t,n,o){r.each(n.members,(function(n,r){var s=t[n];if(null!=s){var c=i(r);a(c=e?e+"."+c:c,s,r,o)}}))}function a(e,t,n,o){null!=t&&("structure"===n.type?s(e,t,n,o):"list"===n.type?function(e,t,n,o){var s=n.member||{};0!==t.length?r.arrayEach(t,(function(t,r){var c="."+(r+1);if("ec2"===n.api.protocol)c+="";else if(n.flattened){if(s.name){var u=e.split(".");u.pop(),u.push(i(s)),e=u.join(".")}}else c="."+(s.name?s.name:"member")+c;a(e+c,t,s,o)})):o.call(this,e,null)}(e,t,n,o):"map"===n.type?function(e,t,n,o){var i=1;r.each(t,(function(t,r){var s=(n.flattened?".":".entry.")+i+++".",c=s+(n.key.name||"key"),u=s+(n.value.name||"value");a(e+c,t,n.key,o),a(e+u,r,n.value,o)}))}(e,t,n,o):o(e,n.toWireFormat(t).toString()))}o.prototype.serialize=function(e,t,n){s("",e,t,n)},t.exports=o},{"../util":72}],53:[function(e,t,n){t.exports={now:function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}}},{}],54:[function(e,t,n){t.exports={isFipsRegion:function(e){return"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips"))},isGlobalRegion:function(e){return"string"==typeof e&&["aws-global","aws-us-gov-global"].includes(e)},getRealRegion:function(e){return["fips-aws-global","aws-fips","aws-global"].includes(e)?"us-east-1":["fips-aws-us-gov-global","aws-us-gov-global"].includes(e)?"us-gov-west-1":e.replace(/fips-(dkr-|prod-)?|-fips/,"")}}},{}],55:[function(e,t,n){var r=e("./util"),o=e("./region_config_data.json");function i(e,t){r.each(t,(function(t,n){"globalEndpoint"!==t&&(void 0!==e.config[t]&&null!==e.config[t]||(e.config[t]=n))}))}t.exports={configureEndpoint:function(e){for(var t=function(e){var t=e.config.region,n=function(e){if(!e)return null;var t=e.split("-");return t.length<3?null:t.slice(0,t.length-2).join("-")+"-*"}(t),r=e.api.endpointPrefix;return[[t,r],[n,r],[t,"*"],[n,"*"],["*",r],["*","*"]].map((function(e){return e[0]&&e[1]?e.join("/"):null}))}(e),n=e.config.useFipsEndpoint,r=e.config.useDualstackEndpoint,s=0;s=0){c=!0;var u=0}var l=function(){c&&u!==a?o.emit("error",n.util.error(new Error("Stream content length mismatch. Received "+u+" of "+a+" bytes."),{code:"StreamContentLengthMismatch"})):2===n.HttpClient.streamsApiVersion?o.end():o.emit("end")},p=s.httpResponse.createUnbufferedStream();if(2===n.HttpClient.streamsApiVersion)if(c){var d=new e.PassThrough;d._write=function(t){return t&&t.length&&(u+=t.length),e.PassThrough.prototype._write.apply(this,arguments)},d.on("end",l),o.on("error",(function(e){c=!1,p.unpipe(d),d.emit("end"),d.end()})),p.pipe(d).pipe(o,{end:!1})}else p.pipe(o);else c&&p.on("data",(function(e){e&&e.length&&(u+=e.length)})),p.on("data",(function(e){o.emit("data",e)})),p.on("end",l);p.on("error",(function(e){c=!1,o.emit("error",e)}))}})),o},emitEvent:function(e,t,r){"function"==typeof t&&(r=t,t=null),r||(r=function(){}),t||(t=this.eventParameters(e,this.response)),n.SequentialExecutor.prototype.emit.call(this,e,t,(function(e){e&&(this.response.error=e),r.call(this,e)}))},eventParameters:function(e){switch(e){case"restart":case"validate":case"sign":case"build":case"afterValidate":case"afterBuild":return[this];case"error":return[this.response.error,this.response];default:return[this.response]}},presign:function(e,t){return t||"function"!=typeof e||(t=e,e=null),(new n.Signers.Presign).sign(this.toGet(),e,t)},isPresigned:function(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,"presigned-expires")},toUnauthenticated:function(){return this._unAuthenticated=!0,this.removeListener("validate",n.EventListeners.Core.VALIDATE_CREDENTIALS),this.removeListener("sign",n.EventListeners.Core.SIGN),this},toGet:function(){return"query"!==this.service.api.protocol&&"ec2"!==this.service.api.protocol||(this.removeListener("build",this.buildAsGet),this.addListener("build",this.buildAsGet)),this},buildAsGet:function(e){e.httpRequest.method="GET",e.httpRequest.path=e.service.endpoint.path+"?"+e.httpRequest.body,e.httpRequest.body="",delete e.httpRequest.headers["Content-Length"],delete e.httpRequest.headers["Content-Type"]},haltHandlersOnError:function(){this._haltHandlersOnError=!0}}),n.Request.addPromisesToClass=function(e){this.prototype.promise=function(){var t=this;return this.httpRequest.appendToUserAgent("promise"),new e((function(e,n){t.on("complete",(function(t){t.error?n(t.error):e(Object.defineProperty(t.data||{},"$response",{value:t}))})),t.runTo()}))}},n.Request.deletePromisesFromClass=function(){delete this.prototype.promise},n.util.addPromises(n.Request),n.util.mixin(n.Request,n.SequentialExecutor)}).call(this)}).call(this,e("_process"))},{"./core":19,"./state_machine":71,_process:90,jmespath:89}],58:[function(e,t,n){var r=e("./core"),o=r.util.inherit,i=e("jmespath");function s(e){var t=e.request._waiter,n=t.config.acceptors,r=!1,o="retry";n.forEach((function(n){if(!r){var i=t.matchers[n.matcher];i&&i(e,n.expected,n.argument)&&(r=!0,o=n.state)}})),!r&&e.error&&(o="failure"),"success"===o?t.setSuccess(e):t.setError(e,"retry"===o)}r.ResourceWaiter=o({constructor:function(e,t){this.service=e,this.state=t,this.loadWaiterConfig(this.state)},service:null,state:null,config:null,matchers:{path:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}return i.strictDeepEqual(r,t)},pathAll:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}Array.isArray(r)||(r=[r]);var o=r.length;if(!o)return!1;for(var s=0;s-1&&n.splice(o,1)}return this},removeAllListeners:function(e){return e?delete this._events[e]:this._events={},this},emit:function(e,t,n){n||(n=function(){});var r=this.listeners(e),o=r.length;return this.callListeners(r,t,n),o>0},callListeners:function(e,t,n,o){var i=this,s=o||null;function a(o){if(o&&(s=r.util.error(s||new Error,o),i._haltHandlersOnError))return n.call(i,s);i.callListeners(e,t,n,s)}for(;e.length>0;){var c=e.shift();if(c._isAsync)return void c.apply(i,t.concat([a]));try{c.apply(i,t)}catch(e){s=r.util.error(s||new Error,e)}if(s&&i._haltHandlersOnError)return void n.call(i,s)}n.call(i,s)},addListeners:function(e){var t=this;return e._events&&(e=e._events),r.util.each(e,(function(e,n){"function"==typeof n&&(n=[n]),r.util.arrayEach(n,(function(n){t.on(e,n)}))})),t},addNamedListener:function(e,t,n,r){return this[e]=n,this.addListener(t,n,r),this},addNamedAsyncListener:function(e,t,n,r){return n._isAsync=!0,this.addNamedListener(e,t,n,r)},addNamedListeners:function(e){var t=this;return e((function(){t.addNamedListener.apply(t,arguments)}),(function(){t.addNamedAsyncListener.apply(t,arguments)})),this}}),r.SequentialExecutor.prototype.addListener=r.SequentialExecutor.prototype.on,t.exports=r.SequentialExecutor},{"./core":19}],61:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./model/api"),i=e("./region_config"),s=r.util.inherit,a=0,c=e("./region/utils");r.Service=s({constructor:function(e){if(!this.loadServiceClass)throw r.util.error(new Error,"Service must be constructed with `new' operator");if(e){if(e.region){var t=e.region;c.isFipsRegion(t)&&(e.region=c.getRealRegion(t),e.useFipsEndpoint=!0),c.isGlobalRegion(t)&&(e.region=c.getRealRegion(t))}"boolean"==typeof e.useDualstack&&"boolean"!=typeof e.useDualstackEndpoint&&(e.useDualstackEndpoint=e.useDualstack)}var n=this.loadServiceClass(e||{});if(n){var o=r.util.copy(e),i=new n(e);return Object.defineProperty(i,"_originalConfig",{get:function(){return o},enumerable:!1,configurable:!0}),i._clientId=++a,i}this.initialize(e)},initialize:function(e){var t=r.config[this.serviceIdentifier];if(this.config=new r.Config(r.config),t&&this.config.update(t,!0),e&&this.config.update(e,!0),this.validateService(),this.config.endpoint||i.configureEndpoint(this),this.config.endpoint=this.endpointFromTemplate(this.config.endpoint),this.setEndpoint(this.config.endpoint),r.SequentialExecutor.call(this),r.Service.addDefaultMonitoringListeners(this),(this.config.clientSideMonitoring||r.Service._clientSideMonitoring)&&this.publisher){var o=this.publisher;this.addNamedListener("PUBLISH_API_CALL","apiCall",(function(e){n.nextTick((function(){o.eventHandler(e)}))})),this.addNamedListener("PUBLISH_API_ATTEMPT","apiCallAttempt",(function(e){n.nextTick((function(){o.eventHandler(e)}))}))}},validateService:function(){},loadServiceClass:function(e){var t=e;if(r.util.isEmpty(this.api)){if(t.apiConfig)return r.Service.defineServiceApi(this.constructor,t.apiConfig);if(this.constructor.services){(t=new r.Config(r.config)).update(e,!0);var n=t.apiVersions[this.constructor.serviceIdentifier];return n=n||t.apiVersion,this.getLatestServiceClass(n)}return null}return null},getLatestServiceClass:function(e){return e=this.getLatestServiceVersion(e),null===this.constructor.services[e]&&r.Service.defineServiceApi(this.constructor,e),this.constructor.services[e]},getLatestServiceVersion:function(e){if(!this.constructor.services||0===this.constructor.services.length)throw new Error("No services defined on "+this.constructor.serviceIdentifier);if(e?r.util.isType(e,Date)&&(e=r.util.date.iso8601(e).split("T")[0]):e="latest",Object.hasOwnProperty(this.constructor.services,e))return e;for(var t=Object.keys(this.constructor.services).sort(),n=null,o=t.length-1;o>=0;o--)if("*"!==t[o][t[o].length-1]&&(n=t[o]),t[o].substr(0,10)<=e)return n;throw new Error("Could not find "+this.constructor.serviceIdentifier+" API to satisfy version constraint `"+e+"'")},api:{},defaultRetryCount:3,customizeRequests:function(e){if(e){if("function"!=typeof e)throw new Error("Invalid callback type '"+typeof e+"' provided in customizeRequests");this.customRequestHandler=e}else this.customRequestHandler=null},makeRequest:function(e,t,n){if("function"==typeof t&&(n=t,t=null),t=t||{},this.config.params){var o=this.api.operations[e];o&&(t=r.util.copy(t),r.util.each(this.config.params,(function(e,n){o.input.members[e]&&(void 0!==t[e]&&null!==t[e]||(t[e]=n))})))}var i=new r.Request(this,e,t);return this.addAllRequestListeners(i),this.attachMonitoringEmitter(i),n&&i.send(n),i},makeUnauthenticatedRequest:function(e,t,n){"function"==typeof t&&(n=t,t={});var r=this.makeRequest(e,t).toUnauthenticated();return n?r.send(n):r},waitFor:function(e,t,n){return new r.ResourceWaiter(this,e).wait(t,n)},addAllRequestListeners:function(e){for(var t=[r.events,r.EventListeners.Core,this.serviceInterface(),r.EventListeners.CorePost],n=0;n299?(o.code&&(n.FinalAwsException=o.code),o.message&&(n.FinalAwsExceptionMessage=o.message)):((o.code||o.name)&&(n.FinalSdkException=o.code||o.name),o.message&&(n.FinalSdkExceptionMessage=o.message))}return n},apiAttemptEvent:function(e){var t=e.service.api.operations[e.operation],n={Type:"ApiCallAttempt",Api:t?t.name:e.operation,Version:1,Service:e.service.api.serviceId||e.service.api.endpointPrefix,Fqdn:e.httpRequest.endpoint.hostname,UserAgent:e.httpRequest.getUserAgent()},r=e.response;return r.httpResponse.statusCode&&(n.HttpStatusCode=r.httpResponse.statusCode),!e._unAuthenticated&&e.service.config.credentials&&e.service.config.credentials.accessKeyId&&(n.AccessKey=e.service.config.credentials.accessKeyId),r.httpResponse.headers?(e.httpRequest.headers["x-amz-security-token"]&&(n.SessionToken=e.httpRequest.headers["x-amz-security-token"]),r.httpResponse.headers["x-amzn-requestid"]&&(n.XAmznRequestId=r.httpResponse.headers["x-amzn-requestid"]),r.httpResponse.headers["x-amz-request-id"]&&(n.XAmzRequestId=r.httpResponse.headers["x-amz-request-id"]),r.httpResponse.headers["x-amz-id-2"]&&(n.XAmzId2=r.httpResponse.headers["x-amz-id-2"]),n):n},attemptFailEvent:function(e){var t=this.apiAttemptEvent(e),n=e.response,r=n.error;return n.httpResponse.statusCode>299?(r.code&&(t.AwsException=r.code),r.message&&(t.AwsExceptionMessage=r.message)):((r.code||r.name)&&(t.SdkException=r.code||r.name),r.message&&(t.SdkExceptionMessage=r.message)),t},attachMonitoringEmitter:function(e){var t,n,o,i,s,a,c=0,u=this;e.on("validate",(function(){i=r.util.realClock.now(),a=Date.now()}),!0),e.on("sign",(function(){n=r.util.realClock.now(),t=Date.now(),s=e.httpRequest.region,c++}),!0),e.on("validateResponse",(function(){o=Math.round(r.util.realClock.now()-n)})),e.addNamedListener("API_CALL_ATTEMPT","success",(function(){var n=u.apiAttemptEvent(e);n.Timestamp=t,n.AttemptLatency=o>=0?o:0,n.Region=s,u.emit("apiCallAttempt",[n])})),e.addNamedListener("API_CALL_ATTEMPT_RETRY","retry",(function(){var i=u.attemptFailEvent(e);i.Timestamp=t,o=o||Math.round(r.util.realClock.now()-n),i.AttemptLatency=o>=0?o:0,i.Region=s,u.emit("apiCallAttempt",[i])})),e.addNamedListener("API_CALL","complete",(function(){var t=u.apiCallEvent(e);if(t.AttemptCount=c,!(t.AttemptCount<=0)){t.Timestamp=a;var n=Math.round(r.util.realClock.now()-i);t.Latency=n>=0?n:0;var o=e.response;o.error&&o.error.retryable&&"number"==typeof o.retryCount&&"number"==typeof o.maxRetries&&o.retryCount>=o.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t])}}))},setupRequestListeners:function(e){},getSigningName:function(){return this.api.signingName||this.api.endpointPrefix},getSignerClass:function(e){var t,n=null,o="";return e&&(o=(n=(e.service.api.operations||{})[e.operation]||null)?n.authtype:""),t=this.config.signatureVersion?this.config.signatureVersion:"v4"===o||"v4-unsigned-body"===o?"v4":this.api.signatureVersion,r.Signers.RequestSigner.getVersion(t)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return r.EventListeners.Query;case"json":return r.EventListeners.Json;case"rest-json":return r.EventListeners.RestJson;case"rest-xml":return r.EventListeners.RestXml}if(this.api.protocol)throw new Error("Invalid service `protocol' "+this.api.protocol+" in API config")},successfulResponse:function(e){return e.httpResponse.statusCode<300},numRetries:function(){return void 0!==this.config.maxRetries?this.config.maxRetries:this.defaultRetryCount},retryDelays:function(e,t){return r.util.calculateRetryDelay(e,this.config.retryDelayOptions,t)},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)>=3e5},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":case"EC2ThrottledException":return!0;default:return!1}},endpointFromTemplate:function(e){if("string"!=typeof e)return e;var t=e;return t=(t=(t=t.replace(/\{service\}/g,this.api.endpointPrefix)).replace(/\{region\}/g,this.config.region)).replace(/\{scheme\}/g,this.config.sslEnabled?"https":"http")},setEndpoint:function(e){this.endpoint=new r.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(!n){if(t){var o=new Error;throw r.util.error(o,"No pagination configuration for "+e)}return null}return n}}),r.util.update(r.Service,{defineMethods:function(e){r.util.each(e.prototype.api.operations,(function(t){e.prototype[t]||("none"===e.prototype.api.operations[t].authtype?e.prototype[t]=function(e,n){return this.makeUnauthenticatedRequest(t,e,n)}:e.prototype[t]=function(e,n){return this.makeRequest(t,e,n)})}))},defineService:function(e,t,n){r.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var o=s(r.Service,n||{});if("string"==typeof e){r.Service.addVersions(o,t);var i=o.serviceIdentifier||e;o.serviceIdentifier=i}else o.prototype.api=e,r.Service.defineMethods(o);if(r.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&r.util.clientSideMonitoring){var a=r.util.clientSideMonitoring.Publisher,c=(0,r.util.clientSideMonitoring.configProvider)();this.prototype.publisher=new a(c),c.enabled&&(r.Service._clientSideMonitoring=!0)}return r.SequentialExecutor.call(o.prototype),r.Service.addDefaultMonitoringListeners(o.prototype),o},addVersions:function(e,t){Array.isArray(t)||(t=[t]),e.services=e.services||{};for(var n=0;n604800)throw r.util.error(new Error,{code:"InvalidExpiryTime",message:"Presigning does not support expiry time greater than a week with SigV4 signing.",retryable:!1});e.httpRequest.headers[i]=t}else{if(n!==r.Signers.S3)throw r.util.error(new Error,{message:"Presigning only supports S3 or SigV4 signing.",code:"UnsupportedSigner",retryable:!1});var o=e.service?e.service.getSkewCorrectedDate():r.util.date.getDate();e.httpRequest.headers[i]=parseInt(r.util.date.unixTimestamp(o)+t,10).toString()}}function a(e){var t=e.httpRequest.endpoint,n=r.util.urlParse(e.httpRequest.path),o={};n.search&&(o=r.util.queryStringParse(n.search.substr(1)));var s=e.httpRequest.headers.Authorization.split(" ");if("AWS"===s[0])s=s[1].split(":"),o.Signature=s.pop(),o.AWSAccessKeyId=s.join(":"),r.util.each(e.httpRequest.headers,(function(e,t){e===i&&(e="Expires"),0===e.indexOf("x-amz-meta-")&&(delete o[e],e=e.toLowerCase()),o[e]=t})),delete e.httpRequest.headers[i],delete o.Authorization,delete o.Host;else if("AWS4-HMAC-SHA256"===s[0]){s.shift();var a=s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];o["X-Amz-Signature"]=a,delete o.Expires}t.pathname=n.pathname,t.search=r.util.queryParamsToString(o)}r.Signers.Presign=o({sign:function(e,t,n){if(e.httpRequest.headers[i]=t||3600,e.on("build",s),e.on("sign",a),e.removeListener("afterBuild",r.EventListeners.Core.SET_CONTENT_LENGTH),e.removeListener("afterBuild",r.EventListeners.Core.COMPUTE_SHA256),e.emit("beforePresign",[e]),!n){if(e.build(),e.response.error)throw e.response.error;return r.util.urlFormat(e.httpRequest.endpoint)}e.build((function(){this.response.error?n(this.response.error):n(null,r.util.urlFormat(e.httpRequest.endpoint))}))}}),t.exports=r.Signers.Presign},{"../core":19}],64:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.RequestSigner=o({constructor:function(e){this.request=e},setServiceClientId:function(e){this.serviceClientId=e},getServiceClientId:function(){return this.serviceClientId}}),r.Signers.RequestSigner.getVersion=function(e){switch(e){case"v2":return r.Signers.V2;case"v3":return r.Signers.V3;case"s3v4":case"v4":return r.Signers.V4;case"s3":return r.Signers.S3;case"v3https":return r.Signers.V3Https}throw new Error("Unknown signing version "+e)},e("./v2"),e("./v3"),e("./v3https"),e("./v4"),e("./s3"),e("./presign")},{"../core":19,"./presign":63,"./s3":65,"./v2":66,"./v3":67,"./v3https":68,"./v4":69}],65:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.S3=o(r.Signers.RequestSigner,{subResources:{acl:1,accelerate:1,analytics:1,cors:1,lifecycle:1,delete:1,inventory:1,location:1,logging:1,metrics:1,notification:1,partNumber:1,policy:1,requestPayment:1,replication:1,restore:1,tagging:1,torrent:1,uploadId:1,uploads:1,versionId:1,versioning:1,versions:1,website:1},responseHeaders:{"response-content-type":1,"response-content-language":1,"response-expires":1,"response-cache-control":1,"response-content-disposition":1,"response-content-encoding":1},addAuthorization:function(e,t){this.request.headers["presigned-expires"]||(this.request.headers["X-Amz-Date"]=r.util.date.rfc822(t)),e.sessionToken&&(this.request.headers["x-amz-security-token"]=e.sessionToken);var n=this.sign(e.secretAccessKey,this.stringToSign()),o="AWS "+e.accessKeyId+":"+n;this.request.headers.Authorization=o},stringToSign:function(){var e=this.request,t=[];t.push(e.method),t.push(e.headers["Content-MD5"]||""),t.push(e.headers["Content-Type"]||""),t.push(e.headers["presigned-expires"]||"");var n=this.canonicalizedAmzHeaders();return n&&t.push(n),t.push(this.canonicalizedResource()),t.join("\n")},canonicalizedAmzHeaders:function(){var e=[];r.util.each(this.request.headers,(function(t){t.match(/^x-amz-/i)&&e.push(t)})),e.sort((function(e,t){return e.toLowerCase()=0?"&":"?";this.request.path+=i+r.util.queryParamsToString(o)},authorization:function(e,t){var n=[],r=this.credentialString(t);return n.push(this.algorithm+" Credential="+e.accessKeyId+"/"+r),n.push("SignedHeaders="+this.signedHeaders()),n.push("Signature="+this.signature(e,t)),n.join(", ")},signature:function(e,t){var n=o.getSigningKey(e,t.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return r.util.crypto.hmac(n,this.stringToSign(t),"hex")},stringToSign:function(e){var t=[];return t.push("AWS4-HMAC-SHA256"),t.push(e),t.push(this.credentialString(e)),t.push(this.hexEncodedHash(this.canonicalString())),t.join("\n")},canonicalString:function(){var e=[],t=this.request.pathname();return"s3"!==this.serviceName&&"s3v4"!==this.signatureVersion&&(t=r.util.uriEscapePath(t)),e.push(this.request.method),e.push(t),e.push(this.request.search()),e.push(this.canonicalHeaders()+"\n"),e.push(this.signedHeaders()),e.push(this.hexEncodedBodyHash()),e.join("\n")},canonicalHeaders:function(){var e=[];r.util.each.call(this,this.request.headers,(function(t,n){e.push([t,n])})),e.sort((function(e,t){return e[0].toLowerCase()-1&&!e.body?"UNSIGNED-PAYLOAD":e.headers["X-Amz-Content-Sha256"]?e.headers["X-Amz-Content-Sha256"]:this.hexEncodedHash(this.request.body||"")},unsignableHeaders:["authorization","content-type","content-length","user-agent",s,"expect","x-amzn-trace-id"],isSignableHeader:function(e){return 0===e.toLowerCase().indexOf("x-amz-")||this.unsignableHeaders.indexOf(e)<0},isPresigned:function(){return!!this.request.headers[s]}}),t.exports=r.Signers.V4},{"../core":19,"./v4_credentials":70}],70:[function(e,t,n){var r=e("../core"),o={},i=[],s="aws4_request";t.exports={createScope:function(e,t,n){return[e.substr(0,8),t,n,s].join("/")},getSigningKey:function(e,t,n,a,c){var u=[r.util.crypto.hmac(e.secretAccessKey,e.accessKeyId,"base64"),t,n,a].join("_");if((c=!1!==c)&&u in o)return o[u];var l=r.util.crypto.hmac("AWS4"+e.secretAccessKey,t,"buffer"),p=r.util.crypto.hmac(l,n,"buffer"),d=r.util.crypto.hmac(p,a,"buffer"),h=r.util.crypto.hmac(d,s,"buffer");return c&&(o[u]=h,i.push(u),i.length>50&&delete o[i.shift()]),h},emptyCache:function(){o={},i=[]}}},{"../core":19}],71:[function(e,t,n){function r(e,t){this.currentState=t||null,this.states=e||{}}r.prototype.runTo=function(e,t,n,r){"function"==typeof e&&(r=n,n=t,t=e,e=null);var o=this,i=o.states[o.currentState];i.fn.call(n||o,r,(function(r){if(r){if(!i.fail)return t?t.call(n,r):null;o.currentState=i.fail}else{if(!i.accept)return t?t.call(n):null;o.currentState=i.accept}if(o.currentState===e)return t?t.call(n,r):null;o.runTo(e,t,n,r)}))},r.prototype.addState=function(e,t,n,r){return"function"==typeof t?(r=t,t=null,n=null):"function"==typeof n&&(r=n,n=null),this.currentState||(this.currentState=e),this.states[e]={accept:t,fail:n,fn:r},this},t.exports=r},{}],72:[function(e,t,n){(function(n,r){(function(){var o,i={environment:"nodejs",engine:function(){if(i.isBrowser()&&"undefined"!=typeof navigator)return navigator.userAgent;var e=n.platform+"/"+n.version;return n.env.AWS_EXECUTION_ENV&&(e+=" exec-env/"+n.env.AWS_EXECUTION_ENV),e},userAgent:function(){var t=i.environment,n="aws-sdk-"+t+"/"+e("./core").VERSION;return"nodejs"===t&&(n+=" "+i.engine()),n},uriEscape:function(e){var t=encodeURIComponent(e);return t=(t=t.replace(/[^A-Za-z0-9_.~\-%]+/g,escape)).replace(/[*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))},uriEscapePath:function(e){var t=[];return i.arrayEach(e.split("/"),(function(e){t.push(i.uriEscape(e))})),t.join("/")},urlParse:function(e){return i.url.parse(e)},urlFormat:function(e){return i.url.format(e)},queryStringParse:function(e){return i.querystring.parse(e)},queryParamsToString:function(e){var t=[],n=i.uriEscape,r=Object.keys(e).sort();return i.arrayEach(r,(function(r){var o=e[r],s=n(r),a=s+"=";if(Array.isArray(o)){var c=[];i.arrayEach(o,(function(e){c.push(n(e))})),a=s+"="+c.sort().join("&"+s+"=")}else null!=o&&(a=s+"="+n(o));t.push(a)})),t.join("&")},readFileSync:function(t){return i.isBrowser()?null:e("fs").readFileSync(t,"utf-8")},base64:{encode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 encode number "+e));return null==e?e:i.buffer.toBuffer(e).toString("base64")},decode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 decode number "+e));return null==e?e:i.buffer.toBuffer(e,"base64")}},buffer:{toBuffer:function(e,t){return"function"==typeof i.Buffer.from&&i.Buffer.from!==Uint8Array.from?i.Buffer.from(e,t):new i.Buffer(e,t)},alloc:function(e,t,n){if("number"!=typeof e)throw new Error("size passed to alloc must be a number.");if("function"==typeof i.Buffer.alloc)return i.Buffer.alloc(e,t,n);var r=new i.Buffer(e);return void 0!==t&&"function"==typeof r.fill&&r.fill(t,void 0,void 0,n),r},toStream:function(e){i.Buffer.isBuffer(e)||(e=i.buffer.toBuffer(e));var t=new i.stream.Readable,n=0;return t._read=function(r){if(n>=e.length)return t.push(null);var o=n+r;o>e.length&&(o=e.length),t.push(e.slice(n,o)),n=o},t},concat:function(e){var t,n,r=0,o=0;for(n=0;n>>8^t[255&(n^e.readUInt8(r))];return(-1^n)>>>0},hmac:function(e,t,n,r){return n||(n="binary"),"buffer"===n&&(n=void 0),r||(r="sha256"),"string"==typeof t&&(t=i.buffer.toBuffer(t)),i.crypto.lib.createHmac(r,e).update(t).digest(n)},md5:function(e,t,n){return i.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return i.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,r){var o=i.crypto.createHash(e);n||(n="binary"),"buffer"===n&&(n=void 0),"string"==typeof t&&(t=i.buffer.toBuffer(t));var s=i.arraySliceFn(t),a=i.Buffer.isBuffer(t);if(i.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(a=!0),r&&"object"==typeof t&&"function"==typeof t.on&&!a)t.on("data",(function(e){o.update(e)})),t.on("error",(function(e){r(e)})),t.on("end",(function(){r(null,o.digest(n))}));else{if(!r||!s||a||"undefined"==typeof FileReader){i.isBrowser()&&"object"==typeof t&&!a&&(t=new i.Buffer(new Uint8Array(t)));var c=o.update(t).digest(n);return r&&r(null,c),c}var u=0,l=new FileReader;l.onerror=function(){r(new Error("Failed to read data."))},l.onload=function(){var e=new i.Buffer(new Uint8Array(l.result));o.update(e),u+=e.length,l._continueReading()},l._continueReading=function(){if(u>=t.size)r(null,o.digest(n));else{var e=u+524288;e>t.size&&(e=t.size),l.readAsArrayBuffer(s.call(t,u,e))}},l._continueReading()}},toHex:function(e){for(var t=[],n=0;n=3e5,!1),o.config.isClockSkewed},applyClockOffset:function(e){e&&(o.config.systemClockOffset=e-(new Date).getTime())},extractRequestId:function(e){var t=e.httpResponse.headers["x-amz-request-id"]||e.httpResponse.headers["x-amzn-requestid"];!t&&e.data&&e.data.ResponseMetadata&&(t=e.data.ResponseMetadata.RequestId),t&&(e.requestId=t),e.error&&(e.error.requestId=t)},addPromises:function(e,t){var n=!1;void 0===t&&o&&o.config&&(t=o.config.getPromisesDependency()),void 0===t&&"undefined"!=typeof Promise&&(t=Promise),"function"!=typeof t&&(n=!0),Array.isArray(e)||(e=[e]);for(var r=0;r=0)return a++,void setTimeout(u,o+(e.retryAfter||0))}n(e)},u=function(){var t="";r.handleRequest(e,s,(function(e){e.on("data",(function(e){t+=e.toString()})),e.on("end",(function(){var r=e.statusCode;if(r<300)n(null,t);else{var o=1e3*parseInt(e.headers["retry-after"],10)||0,s=i.error(new Error,{statusCode:r,retryable:r>=500||429===r});o&&s.retryable&&(s.retryAfter=o),c(s)}}))}),c)};o.util.defer(u)},uuid:{v4:function(){return e("uuid").v4()}},convertPayloadToString:function(e){var t=e.request,n=t.operation,r=t.service.api.operations[n].output||{};r.payload&&e.data[r.payload]&&(e.data[r.payload]=e.data[r.payload].toString())},defer:function(e){"object"==typeof n&&"function"==typeof n.nextTick?n.nextTick(e):"function"==typeof r?r(e):setTimeout(e,0)},getRequestPayloadShape:function(e){var t=e.service.api.operations;if(t){var n=(t||{})[e.operation];if(n&&n.input&&n.input.payload)return n.input.members[n.input.payload]}},getProfilesFromSharedConfig:function(e,t){var r={},o={};n.env[i.configOptInEnv]&&(o=e.loadFrom({isConfig:!0,filename:n.env[i.sharedConfigFileEnv]}));var s={};try{s=e.loadFrom({filename:t||n.env[i.configOptInEnv]&&n.env[i.sharedCredentialsFileEnv]})}catch(e){if(!n.env[i.configOptInEnv])throw e}for(var a=0,c=Object.keys(o);a=6},parse:function(e){var t=e.split(":");return{partition:t[1],service:t[2],region:t[3],accountId:t[4],resource:t.slice(5).join(":")}},build:function(e){if(void 0===e.service||void 0===e.region||void 0===e.accountId||void 0===e.resource)throw i.error(new Error("Input ARN object is invalid"));return"arn:"+(e.partition||"aws")+":"+e.service+":"+e.region+":"+e.accountId+":"+e.resource}},defaultProfile:"default",configOptInEnv:"AWS_SDK_LOAD_CONFIG",sharedCredentialsFileEnv:"AWS_SHARED_CREDENTIALS_FILE",sharedConfigFileEnv:"AWS_CONFIG_FILE",imdsDisabledEnv:"AWS_EC2_METADATA_DISABLED"};t.exports=i}).call(this)}).call(this,e("_process"),e("timers").setImmediate)},{"../apis/metadata.json":4,"./core":19,_process:90,fs:80,timers:97,uuid:100}],73:[function(e,t,n){var r=e("../util"),o=e("../model/shape");function i(){}function s(e,t){for(var n=e.getElementsByTagName(t),r=0,o=n.length;r0||r?i.toString():""},t.exports=s},{"../util":72,"./xml-node":77,"./xml-text":78}],75:[function(e,t,n){t.exports={escapeAttribute:function(e){return e.replace(/&/g,"&").replace(/'/g,"'").replace(//g,">").replace(/"/g,""")}}},{}],76:[function(e,t,n){t.exports={escapeElement:function(e){return e.replace(/&/g,"&").replace(//g,">").replace(/\r/g," ").replace(/\n/g," ").replace(/\u0085/g,"…").replace(/\u2028/,"
")}}},{}],77:[function(e,t,n){var r=e("./escape-attribute").escapeAttribute;function o(e,t){void 0===t&&(t=[]),this.name=e,this.children=t,this.attributes={}}o.prototype.addAttribute=function(e,t){return this.attributes[e]=t,this},o.prototype.addChildNode=function(e){return this.children.push(e),this},o.prototype.removeAttribute=function(e){return delete this.attributes[e],this},o.prototype.toString=function(){for(var e=Boolean(this.children.length),t="<"+this.name,n=this.attributes,o=0,i=Object.keys(n);o"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},t.exports={XmlNode:o}},{"./escape-attribute":75}],78:[function(e,t,n){var r=e("./escape-element").escapeElement;function o(e){this.value=e}o.prototype.toString=function(){return r(""+this.value)},t.exports={XmlText:o}},{"./escape-element":76}],79:[function(e,t,n){"use strict";n.byteLength=function(e){var t=u(e),n=t[0],r=t[1];return 3*(n+r)/4-r},n.toByteArray=function(e){var t,n,r=u(e),s=r[0],a=r[1],c=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),l=0,p=a>0?s-4:s;for(n=0;n>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===a&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[l++]=255&t),1===a&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},n.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],s=16383,a=0,c=n-o;ac?c:a+s));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var o,i,s=[],a=t;a>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],80:[function(e,t,n){},{}],81:[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}},{}],82:[function(e,t,o){(function(e){(function(){!function(i){"object"==typeof o&&o&&o.nodeType,"object"==typeof t&&t&&t.nodeType;var s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self;var a,c=2147483647,u=36,l=/^xn--/,p=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,h={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function m(e){throw RangeError(h[e])}function v(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function y(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+v((e=e.replace(d,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=g((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=g(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function C(e,t,n){var r=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;r+=u)e=f(e/35);return f(r+36*e/(e+38))}function T(e){var t,n,r,o,i,s,a,l,p,d,h,g=[],v=e.length,y=0,E=128,b=72;for((n=e.lastIndexOf("-"))<0&&(n=0),r=0;r=128&&m("not-basic"),g.push(e.charCodeAt(r));for(o=n>0?n+1:0;o=v&&m("invalid-input"),((l=(h=e.charCodeAt(o++))-48<10?h-22:h-65<26?h-65:h-97<26?h-97:u)>=u||l>f((c-y)/s))&&m("overflow"),y+=l*s,!(l<(p=a<=b?1:a>=b+26?26:a-b));a+=u)s>f(c/(d=u-p))&&m("overflow"),s*=d;b=C(y-i,t=g.length+1,0==i),f(y/t)>c-E&&m("overflow"),E+=f(y/t),y%=t,g.splice(y++,0,E)}return S(g)}function I(e){var t,n,r,o,i,s,a,l,p,d,h,v,y,S,T,I=[];for(v=(e=E(e)).length,t=128,n=0,i=72,s=0;s=t&&hf((c-n)/(y=r+1))&&m("overflow"),n+=(a-t)*y,t=a,s=0;sc&&m("overflow"),h==t){for(l=n,p=u;!(l<(d=p<=i?1:p>=i+26?26:p-i));p+=u)T=l-d,S=u-d,I.push(g(b(d+T%S,0))),l=f(T/S);I.push(g(b(l,0))),i=C(n,y,r==o),n=0,++r}++n,++t}return I.join("")}a={version:"1.3.2",ucs2:{decode:E,encode:S},decode:T,encode:I,toASCII:function(e){return y(e,(function(e){return p.test(e)?"xn--"+I(e):e}))},toUnicode:function(e){return y(e,(function(e){return l.test(e)?T(e.slice(4).toLowerCase()):e}))}},void 0===(r=function(){return a}.call(o,n,o,t))||(t.exports=r)}()}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],83:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],84:[function(e,t,r){(function(t,n){(function(){var o=/%[sdj%]/g;r.format=function(e){if(!v(e)){for(var t=[],n=0;n=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}})),c=r[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),f(t)?n.showHidden=t:t&&r._extend(n,t),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),l(n,e,n.depth)}function c(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function u(e,t){return e}function l(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var o=t.inspect(n,e);return v(o)||(o=l(e,o,n)),o}var i=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(v(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return m(t)?e.stylize(""+t,"number"):f(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,t);if(i)return i;var s=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),C(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return p(t);if(0===s.length){if(T(t)){var c=t.name?": "+t.name:"";return e.stylize("[Function"+c+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(b(t))return e.stylize(Date.prototype.toString.call(t),"date");if(C(t))return p(t)}var u,S="",I=!1,_=["{","}"];return h(t)&&(I=!0,_=["[","]"]),T(t)&&(S=" [Function"+(t.name?": "+t.name:"")+"]"),E(t)&&(S=" "+RegExp.prototype.toString.call(t)),b(t)&&(S=" "+Date.prototype.toUTCString.call(t)),C(t)&&(S=" "+p(t)),0!==s.length||I&&0!=t.length?n<0?E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=I?function(e,t,n,r,o){for(var i=[],s=0,a=t.length;s60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(u,S,_)):_[0]+S+_[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,r,o,i){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),R(r,o)||(s="["+o+"]"),a||(e.seen.indexOf(c.value)<0?(a=g(n)?l(e,c.value,null):l(e,c.value,n-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),y(s)){if(i&&o.match(/^\d+$/))return a;(s=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function h(e){return Array.isArray(e)}function f(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function v(e){return"string"==typeof e}function y(e){return void 0===e}function E(e){return S(e)&&"[object RegExp]"===I(e)}function S(e){return"object"==typeof e&&null!==e}function b(e){return S(e)&&"[object Date]"===I(e)}function C(e){return S(e)&&("[object Error]"===I(e)||e instanceof Error)}function T(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function _(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(y(i)&&(i=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!s[e])if(new RegExp("\\b"+e+"\\b","i").test(i)){var n=t.pid;s[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else s[e]=function(){};return s[e]},r.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=h,r.isBoolean=f,r.isNull=g,r.isNullOrUndefined=function(e){return null==e},r.isNumber=m,r.isString=v,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=y,r.isRegExp=E,r.isObject=S,r.isDate=b,r.isError=C,r.isFunction=T,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function w(){var e=new Date,t=[_(e.getHours()),_(e.getMinutes()),_(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){console.log("%s - %s",w(),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!S(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this)}).call(this,e("_process"),void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":83,_process:90,inherits:81}],85:[function(e,t,r){(function(t,n){(function(){"use strict";var n=e("base64-js"),o=e("ieee754"),i=e("isarray");function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function f(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return 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(r)return j(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function v(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=n;ia&&(n=a-c),i=n;i>=0;i--){for(var p=!0,d=0;do&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:u>223?3:u>191?2:1;if(o+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,p=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),o+=p}return function(e){var t=e.length;if(t<=w)return String.fromCharCode.apply(String,e);for(var n="",r=0;r0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,r,o){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),a=Math.min(i,s),u=this.slice(r,o),l=e.slice(t,n),p=0;po)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return C(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var w=4096;function R(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;oo)&&(n=o);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function P(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function x(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function M(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||M(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,i){return i||M(e,0,n,8),o.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},c.prototype.readUInt8=function(e,t){return t||L(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||L(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||L(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||L(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||L(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||L(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||L(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||L(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||L(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||D(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function B(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"base64-js":79,buffer:85,ieee754:87,isarray:88}],86:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function o(e){return"function"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,a,c,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(s(n=this._events[e]))return!1;if(o(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(i(n))for(a=Array.prototype.slice.call(arguments,1),r=(u=n.slice()).length,c=0;c0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){if(!o(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var n,r,s,a;if(!o(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(n=this._events[e]).length,r=-1,n===t||o(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){r=a;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(o(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?o(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(o(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],87:[function(e,t,n){n.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<>1,l=-7,p=n?o-1:0,d=n?-1:1,h=e[t+p];for(p+=d,i=h&(1<<-l)-1,h>>=-l,l+=a;l>0;i=256*i+e[t+p],p+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+p],p+=d,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),i-=u}return(h?-1:1)*s*Math.pow(2,i-r)},n.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+p>=1?d/c:d*Math.pow(2,1-p))*c>=2&&(s++,c/=2),s+p>=l?(a=0,s=l):s+p>=1?(a=(t*c-1)*Math.pow(2,o),s+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;e[n+h]=255&a,h+=f,a/=256,o-=8);for(s=s<0;e[n+h]=255&s,h+=f,s/=256,u-=8);e[n+h-f]|=128*g}},{}],88:[function(e,t,n){var r={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},{}],89:[function(e,t,n){!function(e){"use strict";function t(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e,o){if(e===o)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(o))return!1;if(!0===t(e)){if(e.length!==o.length)return!1;for(var i=0;i",9:"Array"},u="EOF",l="UnquotedIdentifier",p="QuotedIdentifier",d="Rbracket",h="Rparen",f="Comma",g="Colon",m="Rbrace",v="Number",y="Current",E="Expref",S="Pipe",b="Or",C="And",T="EQ",I="GT",_="LT",A="GTE",w="LTE",R="NE",k="Flatten",N="Star",O="Filter",L="Dot",D="Not",P="Lbrace",x="Lbracket",M="Lparen",U="Literal",F={".":L,"*":N,",":f,":":g,"{":P,"}":m,"]":d,"(":M,")":h,"@":y},q={"<":!0,">":!0,"=":!0,"!":!0},j={" ":!0,"\t":!0,"\n":!0};function B(e){return e>="0"&&e<="9"||"-"===e}function V(){}V.prototype={tokenize:function(e){var t,n,r,o,i=[];for(this._current=0;this._current="a"&&o<="z"||o>="A"&&o<="Z"||"_"===o)t=this._current,n=this._consumeUnquotedIdentifier(e),i.push({type:l,value:n,start:t});else if(void 0!==F[e[this._current]])i.push({type:F[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(B(e[this._current]))r=this._consumeNumber(e),i.push(r);else if("["===e[this._current])r=this._consumeLBracket(e),i.push(r);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),i.push({type:p,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),i.push({type:U,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);i.push({type:U,value:s,start:t})}else if(void 0!==q[e[this._current]])i.push(this._consumeOperator(e));else if(void 0!==j[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,i.push({type:C,value:"&&",start:t})):i.push({type:E,value:"&",start:t});else{if("|"!==e[this._current]){var a=new Error("Unknown character:"+e[this._current]);throw a.name="LexerError",a}t=this._current,this._current++,"|"===e[this._current]?(this._current++,i.push({type:b,value:"||",start:t})):i.push({type:S,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:A,value:">=",start:t}):{type:I,value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:T,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,n=this._current,r=e.length;"`"!==e[this._current]&&this._current=0)return!0;if(["true","false","null"].indexOf(e)>=0)return!0;if(!("-0123456789".indexOf(e[0])>=0))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var W={};function H(){}function z(e){this.runtime=e}function G(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[s]}]},avg:{_func:this._functionAvg,_signature:[{types:[8]}]},ceil:{_func:this._functionCeil,_signature:[{types:[s]}]},contains:{_func:this._functionContains,_signature:[{types:[a,3]},{types:[1]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[a]},{types:[a]}]},floor:{_func:this._functionFloor,_signature:[{types:[s]}]},length:{_func:this._functionLength,_signature:[{types:[a,3,4]}]},map:{_func:this._functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this._functionMax,_signature:[{types:[8,9]}]},merge:{_func:this._functionMerge,_signature:[{types:[4],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[3]},{types:[6]}]},sum:{_func:this._functionSum,_signature:[{types:[8]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[a]},{types:[a]}]},min:{_func:this._functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[3]},{types:[6]}]},type:{_func:this._functionType,_signature:[{types:[1]}]},keys:{_func:this._functionKeys,_signature:[{types:[4]}]},values:{_func:this._functionValues,_signature:[{types:[4]}]},sort:{_func:this._functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[3]},{types:[6]}]},join:{_func:this._functionJoin,_signature:[{types:[a]},{types:[9]}]},reverse:{_func:this._functionReverse,_signature:[{types:[a,3]}]},to_array:{_func:this._functionToArray,_signature:[{types:[1]}]},to_string:{_func:this._functionToString,_signature:[{types:[1]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[1]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[1],variadic:!0}]}}}W.EOF=0,W.UnquotedIdentifier=0,W.QuotedIdentifier=0,W.Rbracket=0,W.Rparen=0,W.Comma=0,W.Rbrace=0,W.Number=0,W.Current=0,W.Expref=0,W.Pipe=1,W.Or=2,W.And=3,W.EQ=5,W.GT=5,W.LT=5,W.GTE=5,W.LTE=5,W.NE=5,W.Flatten=9,W.Star=20,W.Filter=21,W.Dot=40,W.Not=45,W.Lbrace=50,W.Lbracket=55,W.Lparen=60,H.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)!==u){var n=this._lookaheadToken(0),r=new Error("Unexpected token type: "+n.type+", value: "+n.value);throw r.name="ParserError",r}return t},_loadTokens:function(e){var t=(new V).tokenize(e);t.push({type:u,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),r=this._lookahead(0);e=0?this.expression(e):t===x?(this._match(x),this._parseMultiselectList()):t===P?(this._match(P),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(W[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===x)t=this.expression(e);else if(this._lookahead(0)===O)t=this.expression(e);else{if(this._lookahead(0)!==L){var n=this._lookaheadToken(0),r=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw r.name="ParserError",r}this._match(L),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==d;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===f&&(this._match(f),this._lookahead(0)===d))throw new Error("Unexpected token Rbracket")}return this._match(d),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,n,r=[],o=[l,p];;){if(e=this._lookaheadToken(0),o.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(g),n={type:"KeyValuePair",name:t,value:this.expression(0)},r.push(n),this._lookahead(0)===f)this._match(f);else if(this._lookahead(0)===m){this._match(m);break}}return{type:"MultiSelectHash",children:r}}},z.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,i){var s,a,c,u,l,p,d,h,f;switch(e.type){case"Field":return null!==i&&n(i)?void 0===(p=i[e.name])?null:p:null;case"Subexpression":for(c=this.visit(e.children[0],i),f=1;f0)for(f=b;fC;f+=N)c.push(i[f]);return c;case"Projection":var O=this.visit(e.children[0],i);if(!t(O))return null;for(h=[],f=0;fl;break;case A:c=u>=l;break;case _:c=u=e&&(t=n<0?e-1:e),t}},G.prototype={callFunction:function(e,t){var n=this.functionTable[e];if(void 0===n)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,n._signature),n._func.call(this,t)},_validateArgs:function(e,t,n){var r,o,i,s;if(n[n.length-1].variadic){if(t.length=0;r--)n+=t[r];return n}var o=e[0].slice(0);return o.reverse(),o},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,n=e[0],r=0;r=0},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return n(e[0])?Object.keys(e[0]).length:e[0].length},_functionMap:function(e){for(var t=[],n=this._interpreter,r=e[0],o=e[1],i=0;i0){if(this._getTypeName(e[0][0])===s)return Math.max.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;r0){if(this._getTypeName(e[0][0])===s)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;ra?1:sc&&(c=n,t=o[u]);return t},_functionMinBy:function(e){for(var t,n,r=e[1],o=e[0],i=this.createKeyFunction(r,[s,a]),c=1/0,u=0;u1)for(var n=1;n0&&u>c&&(u=c);for(var l=0;l=0?(p=g.substr(0,m),d=g.substr(m+1)):(p=g,d=""),h=decodeURIComponent(p),f=decodeURIComponent(d),r(s,h)?o(s[h])?s[h].push(f):s[h]=[s[h],f]:s[h]=f}return s};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],92:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?i(s(e),(function(s){var a=encodeURIComponent(r(s))+n;return o(e[s])?i(e[s],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[s]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r0&&c>a&&(c=a);for(var u=0;u=0?(l=f.substr(0,g),p=f.substr(g+1)):(l=f,p=""),d=decodeURIComponent(l),h=decodeURIComponent(p),r(i,d)?Array.isArray(i[d])?i[d].push(h):i[d]=[i[d],h]:i[d]=h}return i}},{}],95:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,o){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map((function(o){var i=encodeURIComponent(r(o))+n;return Array.isArray(e[o])?e[o].map((function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):o?encodeURIComponent(r(o))+n+encodeURIComponent(r(e)):""}},{}],96:[function(e,t,n){arguments[4][93][0].apply(n,arguments)},{"./decode":94,"./encode":95,dup:93}],97:[function(e,t,n){(function(t,r){(function(){var o=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,a={},c=0;function u(e,t){this._id=e,this._clearFn=t}n.setTimeout=function(){return new u(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new u(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(e){e.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},n.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},n._unrefActive=n.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n.setImmediate="function"==typeof t?t:function(e){var t=c++,r=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,o((function(){a[t]&&(r?e.apply(null,r):e.call(null),n.clearImmediate(t))})),t},n.clearImmediate="function"==typeof r?r:function(e){delete a[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":90,timers:97}],98:[function(e,t,n){var r=e("punycode");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=v,n.resolve=function(e,t){return v(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},n.format=function(e){return y(e)&&(e=v(e)),e instanceof o?e.format():o.prototype.format.call(e)},n.Url=o;var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,a=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(a),u=["%","/","?",";","#"].concat(c),l=["/","?","#"],p=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,h={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},m=e("querystring");function v(e,t,n){if(e&&E(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function y(e){return"string"==typeof e}function E(e){return"object"==typeof e&&null!==e}function S(e){return null===e}o.prototype.parse=function(e,t,n){if(!y(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e;o=o.trim();var s=i.exec(o);if(s){var a=(s=s[0]).toLowerCase();this.protocol=a,o=o.substr(s.length)}if(n||s||o.match(/^\/\/[^@\/]+@[^@\/]+/)){var v="//"===o.substr(0,2);!v||s&&f[s]||(o=o.substr(2),this.slashes=!0)}if(!f[s]&&(v||s&&!g[s])){for(var E,S,b=-1,C=0;C127?R+="x":R+=w[k];if(!R.match(p)){var O=_.slice(0,C),L=_.slice(C+1),D=w.match(d);D&&(O.push(D[1]),L.unshift(D[2])),L.length&&(o="/"+L.join(".")+o),this.hostname=O.join(".");break}}}if(this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),!I){var P=this.hostname.split("."),x=[];for(C=0;C0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),n.search=e.search,n.query=e.query,S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!p.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var h=p.slice(-1)[0],m=(n.host||e.host)&&("."===h||".."===h)||""===h,v=0,E=p.length;E>=0;E--)"."==(h=p[E])?p.splice(E,1):".."===h?(p.splice(E,1),v++):v&&(p.splice(E,1),v--);if(!u&&!l)for(;v--;v)p.unshift("..");!u||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),m&&"/"!==p.join("/").substr(-1)&&p.push("");var b,C=""===p[0]||p[0]&&"/"===p[0].charAt(0);return d&&(n.hostname=n.host=C?"":p.length?p.shift():"",(b=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),(u=u||n.host&&p.length)&&!C&&p.unshift(""),p.length?n.pathname=p.join("/"):(n.pathname=null,n.path=null),S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{punycode:82,querystring:93}],99:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;for(var r=[],o=0;o<256;++o)r[o]=(o+256).toString(16).substr(1);var i=function(e,t){var n=t||0,o=r;return[o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]]].join("")};n.default=i},{}],100:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"v1",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(n,"v3",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(n,"v4",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(n,"v5",{enumerable:!0,get:function(){return s.default}});var r=a(e("./v1.js")),o=a(e("./v3.js")),i=a(e("./v4.js")),s=a(e("./v5.js"));function a(e){return e&&e.__esModule?e:{default:e}}},{"./v1.js":104,"./v3.js":105,"./v4.js":107,"./v5.js":108}],101:[function(e,t,n){"use strict";function r(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,t,n,o,i,s){return r((a=r(r(t,e),r(o,s)))<<(c=i)|a>>>32-c,n);var a,c}function i(e,t,n,r,i,s,a){return o(t&n|~t&r,e,t,i,s,a)}function s(e,t,n,r,i,s,a){return o(t&r|n&~r,e,t,i,s,a)}function a(e,t,n,r,i,s,a){return o(t^n^r,e,t,i,s,a)}function c(e,t,n,r,i,s,a){return o(n^(t|~r),e,t,i,s,a)}Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var u=function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Array(t.length);for(var n=0;n>5]>>>t%32&255,r=parseInt(s.charAt(n>>>4&15)+s.charAt(15&n),16),o.push(r);return o}(function(e,t){var n,o,u,l,p;e[t>>5]|=128<>>9<<4)]=t;var d=1732584193,h=-271733879,f=-1732584194,g=271733878;for(n=0;n>2)-1]=void 0,t=0;t>5]|=(255&e[t/8])<>>32-t}Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var i=unescape(encodeURIComponent(e));e=new Array(i.length);for(var s=0;s>>0;v=m,m=g,g=o(f,30)>>>0,f=h,h=E}n[0]=n[0]+h>>>0,n[1]=n[1]+f>>>0,n[2]=n[2]+g>>>0,n[3]=n[3]+m>>>0,n[4]=n[4]+v>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]};n.default=i},{}],104:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r,o,i=a(e("./rng.js")),s=a(e("./bytesToUuid.js"));function a(e){return e&&e.__esModule?e:{default:e}}var c=0,u=0,l=function(e,t,n){var a=t&&n||0,l=t||[],p=(e=e||{}).node||r,d=void 0!==e.clockseq?e.clockseq:o;if(null==p||null==d){var h=e.random||(e.rng||i.default)();null==p&&(p=r=[1|h[0],h[1],h[2],h[3],h[4],h[5]]),null==d&&(d=o=16383&(h[6]<<8|h[7]))}var f=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:u+1,m=f-c+(g-u)/1e4;if(m<0&&void 0===e.clockseq&&(d=d+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,u=g,o=d;var v=(1e4*(268435455&(f+=122192928e5))+g)%4294967296;l[a++]=v>>>24&255,l[a++]=v>>>16&255,l[a++]=v>>>8&255,l[a++]=255&v;var y=f/4294967296*1e4&268435455;l[a++]=y>>>8&255,l[a++]=255&y,l[a++]=y>>>24&15|16,l[a++]=y>>>16&255,l[a++]=d>>>8|128,l[a++]=255&d;for(var E=0;E<6;++E)l[a+E]=p[E];return t||(0,s.default)(l)};n.default=l},{"./bytesToUuid.js":99,"./rng.js":102}],105:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r=i(e("./v35.js")),o=i(e("./md5.js"));function i(e){return e&&e.__esModule?e:{default:e}}var s=(0,r.default)("v3",48,o.default);n.default=s},{"./md5.js":101,"./v35.js":106}],106:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=function(e,t,n){var r=function(e,r,i,s){var a=i&&s||0;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=new Array(e.length),n=0;n=0;i--)o[i].Expire{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,t.ClientMethods=t.makeEnum(["getAgentSnapshot","putAgentState","getAgentStates","getDialableCountryCodes","getRoutingProfileQueues","getAgentPermissions","getAgentConfiguration","updateAgentConfiguration","acceptContact","createOutboundContact","createTaskContact","clearContact","completeContact","destroyContact","rejectContact","notifyContactIssue","updateContactAttributes","createAdditionalConnection","destroyConnection","holdConnection","resumeConnection","toggleActiveConnections","conferenceConnections","sendClientLogs","sendDigits","sendSoftphoneCallReport","sendSoftphoneCallMetrics","getEndpoints","getNewAuthToken","createTransport","muteParticipant","unmuteParticipant"]),t.AgentAppClientMethods={GET_CONTACT:"AgentAppService.Lcms.getContact",DELETE_SPEAKER:"AgentAppService.VoiceId.deleteSpeaker",ENROLL_BY_SESSION:"AgentAppService.VoiceId.enrollBySession",EVALUATE_SESSION:"AgentAppService.VoiceId.evaluateSession",DESCRIBE_SPEAKER:"AgentAppService.VoiceId.describeSpeaker",OPT_OUT_SPEAKER:"AgentAppService.VoiceId.optOutSpeaker",UPDATE_VOICE_ID_DATA:"AgentAppService.Lcms.updateVoiceIdData",DESCRIBE_SESSION:"AgentAppService.VoiceId.describeSession",UPDATE_SESSION:"AgentAppService.VoiceId.updateSession",START_VOICE_ID_SESSION:"AgentAppService.Nasa.startVoiceIdSession",LIST_INTEGRATION_ASSOCIATIONS:"AgentAppService.Acs.listIntegrationAssociations"},t.MasterMethods=t.makeEnum(["becomeMaster","checkMaster"]),t.TaskTemplatesClientMethods=t.makeEnum(["listTaskTemplates","getTaskTemplate","createTemplatedTask","updateContact"]);var n=function(){};n.EMPTY_CALLBACKS={success:function(){},failure:function(){}},n.prototype.call=function(e,r,o){t.assertNotNull(e,"method");var i=r||{},s=o||n.EMPTY_CALLBACKS;this._callImpl(e,i,s)},n.prototype._callImpl=function(e,n,r){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){if(r&&r.failure){var o=t.sprintf("No such method exists on NULL client: %s",e);r.failure(new t.ValueError(o),{message:o})}};var o=function(e,r,o){n.call(this),this.conduit=e,this.requestEvent=r,this.responseEvent=o,this._requestIdCallbacksMap={},this.conduit.onUpstream(o,t.hitch(this,this._handleResponse))};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._callImpl=function(e,n,r){var o=t.EventFactory.createRequest(this.requestEvent,e,n);this._requestIdCallbacksMap[o.requestId]=r,this.conduit.sendUpstream(o.event,o)},o.prototype._getCallbacksForRequest=function(e){var t=this._requestIdCallbacksMap[e]||null;return null!=t&&delete this._requestIdCallbacksMap[e],t},o.prototype._handleResponse=function(e){var t=this._getCallbacksForRequest(e.requestId);null!=t&&(e.err&&t.failure?t.failure(e.err,e.data):t.success&&t.success(e.data))};var i=function(e){o.call(this,e,t.EventType.API_REQUEST,t.EventType.API_RESPONSE)};(i.prototype=Object.create(o.prototype)).constructor=i;var s=function(e){o.call(this,e,t.EventType.MASTER_REQUEST,t.EventType.MASTER_RESPONSE)};(s.prototype=Object.create(o.prototype)).constructor=s;var a=function(e,r,o){t.assertNotNull(e,"authCookieName"),t.assertNotNull(r,"authToken"),t.assertNotNull(o,"endpoint"),n.call(this),this.endpointUrl=t.getUrlWithProtocol(o),this.authToken=r,this.authCookieName=e};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype._callImpl=function(e,n,r){var o=this,i={};i[o.authCookieName]=o.authToken;var s={method:"post",body:JSON.stringify(n||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(i)}};t.fetch(o.endpointUrl,s).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))};var c=function(e,r,o){t.assertNotNull(e,"authToken"),t.assertNotNull(r,"region"),n.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=r,this.authToken=e;var i=t.getBaseUrl(),s=o||(i.includes(".awsapps.com")?i+"/connect/api":i+"/api"),a=new AWS.Endpoint(s);this.client=new AWS.Connect({endpoint:a})};(c.prototype=Object.create(n.prototype)).constructor=c,c.prototype._callImpl=function(e,n,r){var o=this,i=t.getLog();if(t.contains(this.client,e))n=this._translateParams(e,n),i.trace("AWSClient: --\x3e Calling operation '%s'",e).sendInternalLogToServer(),this.client[e](n).on("build",(function(e){e.httpRequest.headers["X-Amz-Bearer"]=o.authToken})).send((function(n,o){try{if(n){if(n.code===t.CTIExceptions.UNAUTHORIZED_EXCEPTION)r.authFailure();else if(!r.accessDenied||n.code!==t.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==n.statusCode){var s={};if(s.type=n.code,s.message=n.message,s.stack=[],n.stack)try{Array.isArray(n.stack)?s.stack=n.stack:"object"==typeof n.stack?s.stack=[JSON.stringify(n.stack)]:"string"==typeof n.stack&&(s.stack=n.stack.split("\n"))}catch{}r.failure(s,o)}else r.accessDenied();i.trace("AWSClient: <-- Operation '%s' failed: %s",e,JSON.stringify(n)).sendInternalLogToServer()}else i.trace("AWSClient: <-- Operation '%s' succeeded.",e).withObject(o).sendInternalLogToServer(),r.success(o)}catch(n){t.getLog().error("Failed to handle AWS API request for method %s",e).withException(n).sendInternalLogToServer()}}));else{var s=t.sprintf("No such method exists on AWS client: %s",e);r.failure(new t.ValueError(s),{message:s})}},c.prototype._requiresAuthenticationParam=function(e){return e!==t.ClientMethods.COMPLETE_CONTACT&&e!==t.ClientMethods.CLEAR_CONTACT&&e!==t.ClientMethods.REJECT_CONTACT&&e!==t.ClientMethods.CREATE_TASK_CONTACT},c.prototype._translateParams=function(e,n){switch(e){case t.ClientMethods.UPDATE_AGENT_CONFIGURATION:n.configuration=this._translateAgentConfiguration(n.configuration);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:n.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(n.softphoneStreamStatistics);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:n.report=this._translateSoftphoneCallReport(n.report)}return this._requiresAuthenticationParam(e)&&(n.authentication={authToken:this.authToken}),n},c.prototype._translateAgentConfiguration=function(e){return{name:e.name,softphoneEnabled:e.softphoneEnabled,softphoneAutoAccept:e.softphoneAutoAccept,extension:e.extension,routingProfile:this._translateRoutingProfile(e.routingProfile),agentPreferences:e.agentPreferences}},c.prototype._translateRoutingProfile=function(e){return{name:e.name,routingProfileARN:e.routingProfileARN,defaultOutboundQueue:this._translateQueue(e.defaultOutboundQueue)}},c.prototype._translateQueue=function(e){return{queueARN:e.queueARN,name:e.name}},c.prototype._translateSoftphoneStreamStatistics=function(e){return e.forEach((function(e){"packetsCount"in e&&(e.packetCount=e.packetsCount,delete e.packetsCount)})),e},c.prototype._translateSoftphoneCallReport=function(e){return"handshakingTimeMillis"in e&&(e.handshakeTimeMillis=e.handshakingTimeMillis,delete e.handshakingTimeMillis),"preTalkingTimeMillis"in e&&(e.preTalkTimeMillis=e.preTalkingTimeMillis,delete e.preTalkingTimeMillis),"handshakingFailure"in e&&(e.handshakeFailure=e.handshakingFailure,delete e.handshakingFailure),"talkingTimeMillis"in e&&(e.talkTimeMillis=e.talkingTimeMillis,delete e.talkingTimeMillis),e.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(e.softphoneStreamStatistics),e};var u=function(e){if(t.assertNotNull(e,"endpoint"),n.call(this),e.includes("/task-templates"))this.endpointUrl=t.getUrlWithProtocol(e);else{var r=new AWS.Endpoint(e),o=e.includes(".awsapps.com")?"/connect":"";this.endpointUrl=t.getUrlWithProtocol(`${r.host}${o}/task-templates/api/ccp`)}};(u.prototype=Object.create(n.prototype)).constructor=u,u.prototype._callImpl=function(e,n,r){t.assertNotNull(e,"method"),t.assertNotNull(n,"params");var o={credentials:"include",method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","x-csrf-token":"csrf"}},i=n.instanceId,s=this.endpointUrl,a=t.TaskTemplatesClientMethods;switch(e){case a.LIST_TASK_TEMPLATES:if(s+=`/proxy/instance/${i}/task/template`,n.queryParams){const e=new URLSearchParams(n.queryParams).toString();e&&(s+=`?${e}`)}break;case a.GET_TASK_TEMPLATE:t.assertNotNull(n.templateParams,"params.templateParams");const r=t.assertNotNull(n.templateParams.id,"params.templateParams.id"),c=n.templateParams.version;s+=`/proxy/instance/${i}/task/template/${r}`,c&&(s+=`?snapshotVersion=${c}`);break;case a.CREATE_TEMPLATED_TASK:s+=`/${e}`,o.body=JSON.stringify(n),o.method="PUT";break;case a.UPDATE_CONTACT:s+=`/${e}`,o.body=JSON.stringify(n),o.method="POST"}t.fetch(s,o).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))},t.ClientBase=n,t.NullClient=r,t.UpstreamConduitClient=i,t.UpstreamConduitMasterClient=s,t.AWSClient=c,t.AgentAppClient=a,t.TaskTemplatesClient=u}()},895:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,t.core={},t.core.initialized=!1,t.version="2.3.0",t.DEFAULT_BATCH_SIZE=500;var n="Amazon Connect CCP",r="https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}",o="06919f4fd8ed324e",i="/auth/authorize",s="/connect/auth/authorize",a="IframeRefreshAttempts",c="IframeInitializationSuccess";function u(e){var t=e.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/gi);return t.length?t[0]:""}t.numberOfConnectedCCPs=0,t.numberOfConnectedCCPsInThisTab=0,t.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION=3,t.core.MAX_CTI_AUTH_RETRY_COUNT=10,t.core.ctiAuthRetryCount=0,t.core.authorizeTimeoutId=null,t.core.ctiTimeoutId=null,t.SessionStorageKeys=t.makeEnum(["tab_id","authorize_retry_count"]),t.core.checkNotInitialized=function(){t.core.initialized&&t.getLog().warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer()},t.core.init=function(e){t.core.eventBus=new t.EventBus,t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.initClient(e),t.core.initAgentAppClient(e),t.core.initTaskTemplatesClient(e),t.core.initialized=!0},t.core.initClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.region,"params.region"),o=e.endpoint||null;t.core.client=new t.AWSClient(n,r,o)},t.core.initAgentAppClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.authCookieName,"params.authCookieName"),o=t.assertNotNull(e.agentAppEndpoint,"params.agentAppEndpoint");t.core.agentAppClient=new t.AgentAppClient(r,n,o)},t.core.initTaskTemplatesClient=function(e){t.assertNotNull(e,"params");var n=e.taskTemplatesEndpoint||e.endpoint;t.assertNotNull(n,"taskTemplatesEndpoint"),t.core.taskTemplatesClient=new t.TaskTemplatesClient(n)},t.core.terminate=function(){t.core.client=new t.NullClient,t.core.agentAppClient=new t.NullClient,t.core.taskTemplatesClient=new t.NullClient,t.core.masterClient=new t.NullClient;var e=t.core.getEventBus();e&&e.unsubscribeAll(),t.core.bus=new t.EventBus,t.core.agentDataProvider=null,t.core.softphoneManager=null,t.core.upstream=null,t.core.keepaliveManager=null,t.agent.initialized=!1,t.core.initialized=!1},t.core.softphoneUserMediaStream=null,t.core.getSoftphoneUserMediaStream=function(){return t.core.softphoneUserMediaStream},t.core.setSoftphoneUserMediaStream=function(e){t.core.softphoneUserMediaStream=e},t.core.initRingtoneEngines=function(e){t.assertNotNull(e,"params");var n=function(e){t.assertNotNull(e,"ringtoneSettings"),t.assertNotNull(e.voice,"ringtoneSettings.voice"),t.assertTrue(e.voice.ringtoneUrl||e.voice.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"),t.assertNotNull(e.queue_callback,"ringtoneSettings.queue_callback"),t.assertTrue(e.queue_callback.ringtoneUrl||e.queue_callback.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"),t.core.ringtoneEngines={},t.agent((function(n){n.onRefresh((function(){t.ifMaster(t.MasterTopics.RINGTONE,(function(){e.voice.disabled||t.core.ringtoneEngines.voice||(t.core.ringtoneEngines.voice=new t.VoiceRingtoneEngine(e.voice),t.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer()),e.chat.disabled||t.core.ringtoneEngines.chat||(t.core.ringtoneEngines.chat=new t.ChatRingtoneEngine(e.chat),t.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer()),e.task.disabled||t.core.ringtoneEngines.task||(t.core.ringtoneEngines.task=new t.TaskRingtoneEngine(e.task),t.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer()),e.queue_callback.disabled||t.core.ringtoneEngines.queue_callback||(t.core.ringtoneEngines.queue_callback=new t.QueueCallbackRingtoneEngine(e.queue_callback),t.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer())}))}))})),l()},r=function(e,n){e.ringtone=e.ringtone||{},e.ringtone.voice=e.ringtone.voice||{},e.ringtone.queue_callback=e.ringtone.queue_callback||{},e.ringtone.chat=e.ringtone.chat||{disabled:!0},e.ringtone.task=e.ringtone.task||{disabled:!0},n.softphone&&(n.softphone.disableRingtone&&(e.ringtone.voice.disabled=!0,e.ringtone.queue_callback.disabled=!0),n.softphone.ringtoneUrl&&(e.ringtone.voice.ringtoneUrl=n.softphone.ringtoneUrl,e.ringtone.queue_callback.ringtoneUrl=n.softphone.ringtoneUrl)),n.chat&&(n.chat.disableRingtone&&(e.ringtone.chat.disabled=!0),n.chat.ringtoneUrl&&(e.ringtone.chat.ringtoneUrl=n.chat.ringtoneUrl)),n.ringtone&&(e.ringtone.voice=t.merge(e.ringtone.voice,n.ringtone.voice||{}),e.ringtone.queue_callback=t.merge(e.ringtone.queue_callback,n.ringtone.voice||{}),e.ringtone.chat=t.merge(e.ringtone.chat,n.ringtone.chat||{}))};r(e,e),t.isFramed()?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(t){this.unsubscribe(),r(e,t),n(e.ringtone)})):n(e.ringtone)};var l=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_RINGER_DEVICE,p)},p=function(e){if(0!==t.keys(t.core.ringtoneEngines).length&&e&&e.deviceId){var n=e.deviceId;for(var r in t.core.ringtoneEngines)t.core.ringtoneEngines[r].setOutputDevice(n);t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.RINGER_DEVICE_CHANGED,data:{deviceId:n}})}};t.core.initSoftphoneManager=function(e){t.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer();var n=e||{},r=function(e){var r=t.merge(n.softphone||{},e);t.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(),t.agent((function(e){e.getChannelConcurrency(t.ChannelType.VOICE)&&e.onRefresh((function(){var n=this;t.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(),t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(),!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),n.unsubscribe())}))}))}))};function o(e){var r=t.merge(n.softphone||{},e);t.core.softphoneParams=r,t.isFirefoxBrowser()&&(t.core.getUpstream().onUpstream(t.EventType.MASTER_RESPONSE,(function(e){if(e.data&&e.data.topic===t.MasterTopics.SOFTPHONE&&e.data.takeOver&&e.data.masterId!==t.core.portStreamId){t.core.softphoneManager&&(t.core.softphoneManager.onInitContactSub.unsubscribe(),delete t.core.softphoneManager);var n=t.core.getSoftphoneUserMediaStream();n&&(n.getTracks().forEach((function(e){e.stop()})),t.core.setSoftphoneUserMediaStream(null))}})),t.core.getEventBus().subscribe(t.ConnectionEvents.READY_TO_START_SESSION,(function(){t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.core.softphoneManager&&t.core.softphoneManager.startSession()}),(function(){t.becomeMaster(t.MasterTopics.SOFTPHONE,(function(){t.agent((function(e){!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),t.core.softphoneManager.startSession())}))}))}))})),t.contact((function(e){t.agent((function(n){e.onRefresh((function(e){if(t.hasOtherConnectedCCPs()&&"visible"===document.visibilityState&&(e.getStatus().type===t.ContactStatusType.CONNECTING||e.getStatus().type===t.ContactStatusType.INCOMING)){var r=e.isSoftphoneCall()&&!e.isInbound(),o=e.isSoftphoneCall()&&n.getConfiguration().softphoneAutoAccept,i=e.getType()===t.ContactType.QUEUE_CALLBACK;(r||o||i)&&t.core.triggerReadyToStartSessionEvent()}}))}))})))}t.isFramed()&&!n.allowFramedSoftphone?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(e){t.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(),e.softphone&&e.softphone.allowFramedSoftphone&&(this.unsubscribe(),r(e.softphone)),o(e.softphone)})):(r(n),o(n)),t.agent((function(e){e.isSoftphoneEnabled()&&e.getChannelConcurrency(t.ChannelType.VOICE)&&t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE})}))},t.core.triggerReadyToStartSessionEvent=function(){var e=t.core.softphoneParams&&t.core.softphoneParams.allowFramedSoftphone;t.isCCP()?e?t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):t.isFramed()?t.core.getUpstream().sendDownstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):e?t.core.getUpstream().sendUpstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION)},t.core.initPageOptions=function(e){if(t.assertNotNull(e,"params"),t.isFramed()){var n=t.core.getEventBus();n.subscribe(t.EventType.CONFIGURE,(function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.CONFIGURE,data:e})})),n.subscribe(t.EventType.MEDIA_DEVICE_REQUEST,(function(){function e(e){t.core.getUpstream().sendDownstream(t.EventType.MEDIA_DEVICE_RESPONSE,e)}navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})).catch((function(t){e({error:t.message})})):e({error:"No navigator or navigator.mediaDevices object found"})}))}},t.core.getFrameMediaDevices=function(e){var n=null,r=e||1e3,o=new Promise((function(e,t){setTimeout((function(){t(new Error("Timeout exceeded"))}),r)})),i=new Promise((function(e,r){if(t.isFramed()||t.isCCP())navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})):r(new Error("No navigator or navigator.mediaDevices object found"));else{var o=t.core.getEventBus();n=o.subscribe(t.EventType.MEDIA_DEVICE_RESPONSE,(function(t){t.error?r(new Error(t.error)):e(t)})),t.core.getUpstream().sendUpstream(t.EventType.MEDIA_DEVICE_REQUEST)}}));return Promise.race([i,o]).finally((function(){n&&n.unsubscribe()}))},t.core.authorize=function(e){var n=e;return n||(n=t.core.isLegacyDomain()?s:i),t.fetch(n,{credentials:"include"},2e3,5)},t.core.verifyDomainAccess=function(e,n){if(t.getLog().warn("This API will be deprecated in the next major version release"),!t.isFramed())return Promise.resolve();var r={headers:{"X-Amz-Bearer":e}},o=null;return o=n||(t.core.isLegacyDomain()?"/connect/whitelisted-origins":"/whitelisted-origins"),t.fetch(o,r,2e3,5).then((function(e){var t=u(window.document.referrer);return e.whitelistedOrigins.some((function(e){return t===u(e)}))?Promise.resolve():Promise.reject()}))},t.core.isLegacyDomain=function(e){return(e=e||window.location.href).includes(".awsapps.com")},t.core.initSharedWorker=function(n){if(t.core.checkNotInitialized(),!t.core.initialized){t.assertNotNull(n,"params");var r=t.assertNotNull(n.sharedWorkerUrl,"params.sharedWorkerUrl"),o=t.assertNotNull(n.authToken,"params.authToken"),a=t.assertNotNull(n.refreshToken,"params.refreshToken"),c=t.assertNotNull(n.authTokenExpiration,"params.authTokenExpiration"),u=t.assertNotNull(n.region,"params.region"),l=n.endpoint||null,p=n.authorizeEndpoint;p||(p=t.core.isLegacyDomain()?s:i);var d=n.agentAppEndpoint||null,g=n.taskTemplatesEndpoint||null,m=n.authCookieName||null;try{t.core.eventBus=new t.EventBus({logEvents:!0}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(n);var v=new SharedWorker(r,"ConnectSharedWorker"),y=new t.Conduit("ConnectSharedWorkerConduit",new t.PortStream(v.port),new t.WindowIOStream(window,parent));t.core.upstream=y,t.core.webSocketProvider=new h,e.onunload=function(){y.sendUpstream(t.EventType.CLOSE),v.port.close()},t.getLog().scheduleUpstreamLogPush(y),t.getLog().scheduleDownstreamClientSideLogsPush(),y.onAllUpstream(t.core.getEventBus().bridge()),y.onAllUpstream(y.passDownstream()),t.isFramed()&&(y.onAllDownstream(t.core.getEventBus().bridge()),y.onAllDownstream(y.passUpstream())),y.sendUpstream(t.EventType.CONFIGURE,{authToken:o,authTokenExpiration:c,endpoint:l,refreshToken:a,region:u,authorizeEndpoint:p,agentAppEndpoint:d,taskTemplatesEndpoint:g,authCookieName:m,longPollingOptions:n.longPollingOptions||void 0}),y.onUpstream(t.EventType.ACKNOWLEDGE,(function(e){t.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(),t.core.initialized=!0,t.core._setTabId(),t.core.portStreamId=e.id,this.unsubscribe()})),y.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),y.onUpstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))})),y.onDownstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.isFramed()&&Array.isArray(e)&&e.forEach((function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))}))})),y.onDownstream(t.EventType.LOG,(function(e){t.isFramed()&&e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.onAuthFail(t.hitch(t.core,t.core._handleAuthFail,n.loginEndpoint||null,p)),t.core.onAuthorizeSuccess(t.hitch(t.core,t.core._handleAuthorizeSuccess)),t.getLog().info("User Agent: "+navigator.userAgent).sendInternalLogToServer(),t.getLog().info("isCCPv2: "+!0).sendInternalLogToServer(),t.getLog().info("isFramed: "+t.isFramed()).sendInternalLogToServer(),t.core.upstream.onDownstream(t.EventType.OUTER_CONTEXT_INFO,(function(e){var n=e.streamsVersion;t.getLog().info("StreamsJS Version: "+n).sendInternalLogToServer()})),y.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.getLog().info("Number of connected CCPs updated: "+e.length).sendInternalLogToServer(),t.numberOfConnectedCCPs=e.length,e[t.core.tabId]&&!isNaN(e[t.core.tabId].length)&&t.numberOfConnectedCCPsInThisTab!==e[t.core.tabId].length&&(t.numberOfConnectedCCPsInThisTab=e[t.core.tabId].length,t.numberOfConnectedCCPsInThisTab>1&&t.getLog().warn("There are "+t.numberOfConnectedCCPsInThisTab+" connected CCPs in this tab. Please adjust your implementation to avoid complications. If you are embedding CCP, please do so exclusively with initCCP. InitCCP will not let you embed more than one CCP.").sendInternalLogToServer(),t.publishMetric({name:"ConnectedCCPSingleTabCount",data:{count:t.numberOfConnectedCCPsInThisTab}})),e.tabId&&e.streamsTabsAcrossBrowser&&t.ifMaster(t.MasterTopics.METRICS,(()=>t.agent((()=>t.publishMetric({name:"CCPTabsAcrossBrowserCount",data:{tabId:e.tabId,count:e.streamsTabsAcrossBrowser}})))))})),t.core.client=new t.UpstreamConduitClient(y),t.core.masterClient=new t.UpstreamConduitMasterClient(y),t.core.getEventBus().subscribe(t.EventType.TERMINATE,y.passUpstream()),t.core.getEventBus().subscribe(t.EventType.TERMINATED,(function(){window.location.reload(!0)})),v.port.start(),y.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.agent((function(){(new t.VoiceId).getDomainId().then((function(e){t.getLog().info("voiceId domainId successfully fetched at agent initialization: "+e).sendInternalLogToServer()})).catch((function(e){t.getLog().info("voiceId domainId not fetched at agent initialization").withObject({err:e}).sendInternalLogToServer()}))})),t.core.getNotificationManager().requestPermission()}catch(e){t.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer()}}},t.core._setTabId=function(){try{t.core.tabId=window.sessionStorage.getItem(t.SessionStorageKeys.TAB_ID),t.core.tabId||(t.core.tabId=t.randomId(),window.sessionStorage.setItem(t.SessionStorageKeys.TAB_ID,t.core.tabId)),t.core.upstream.sendUpstream(t.EventType.TAB_ID,{tabId:t.core.tabId})}catch(e){t.getLog().error("[Tab Id] There was an issue setting the tab Id").withException(e).sendInternalLogToServer()}},t.core.initCCP=function(n,i){if(t.core.checkNotInitialized(),!t.core.initialized){t.getLog().info("Iframe initialization started").sendInternalLogToServer();var s=Date.now();try{if(t.core._getCCPIframe())return void t.getLog().error("Attempted to call initCCP when an iframe generated by initCCP already exists").sendInternalLogToServer()}catch(e){t.getLog().error("Error while checking if initCCP has already been called").withException(e).sendInternalLogToServer()}var u={};"string"==typeof i?u.ccpUrl=i:u=i,t.assertNotNull(n,"containerDiv"),t.assertNotNull(u.ccpUrl,"params.ccpUrl");var l=t.core._createCCPIframe(n,u);t.core.eventBus=new t.EventBus({logEvents:!1}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(u);var p=new t.IFrameConduit(u.ccpUrl,window,l);t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(l,p),t.core.upstream=p,t.core.webSocketProvider=new h,p.onAllUpstream(t.core.getEventBus().bridge()),t.core.keepaliveManager=new d(p,t.core.getEventBus(),u.ccpSynTimeout||1e3,u.ccpAckTimeout||3e3),t.core.iframeRefreshTimeout=null,t.core.ccpLoadTimeoutInstance=e.setTimeout((function(){t.core.ccpLoadTimeoutInstance=null,t.core.getEventBus().trigger(t.EventType.ACK_TIMEOUT)}),u.ccpLoadTimeout||5e3),t.getLog().scheduleUpstreamOuterContextCCPLogsPush(p),t.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(p),p.onUpstream(t.EventType.ACKNOWLEDGE,(function(n){if(t.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(),t.core.client=new t.UpstreamConduitClient(p),t.core.masterClient=new t.UpstreamConduitMasterClient(p),t.core.portStreamId=n.id,(u.softphone||u.chat||u.pageOptions||u.shouldAddNamespaceToLogs)&&p.sendUpstream(t.EventType.CONFIGURE,{softphone:u.softphone,chat:u.chat,pageOptions:u.pageOptions,shouldAddNamespaceToLogs:u.shouldAddNamespaceToLogs}),t.core.ccpLoadTimeoutInstance&&(e.clearTimeout(t.core.ccpLoadTimeoutInstance),t.core.ccpLoadTimeoutInstance=null),p.sendUpstream(t.EventType.OUTER_CONTEXT_INFO,{streamsVersion:t.version}),t.core.keepaliveManager.start(),this.unsubscribe(),t.core.initialized=!0,t.core.getEventBus().trigger(t.EventType.INIT),s){var r=Date.now()-s,o=t.core.iframeRefreshAttempt||0;t.getLog().info("Iframe initialization succeeded").sendInternalLogToServer(),t.getLog().info(`Iframe initialization time ${r}`).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${o}`).sendInternalLogToServer(),setTimeout((()=>{t.publishMetric({name:a,data:{count:o}}),t.publishMetric({name:c,data:{count:1}}),t.publishMetric({name:"IframeInitializationTime",data:{count:r}}),s=null}),1e3)}})),p.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.getEventBus().subscribe(t.EventType.ACK_TIMEOUT,(function(){if(!1!==u.loginPopup)try{var i=function(n){var i="https://lily.us-east-1.amazonaws.com/taw/auth/code";return t.assertNotNull(i),n.loginUrl?n.loginUrl:n.alias?(log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."),r.replace("{alias}",n.alias).replace("{client_id}",o).replace("{redirect}",e.encodeURIComponent(i))):n.ccpUrl}(u);t.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(),u.loginUrl&&t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),t.core.loginWindow=t.core.getPopupManager().open(i,t.MasterTopics.LOGIN_POPUP,u.loginOptions)}catch(e){t.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer()}if(null==t.core.iframeRefreshTimeout)try{p.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=null,t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),(u.loginPopupAutoClose||u.loginOptions&&u.loginOptions.autoClose)&&t.core.loginWindow&&(t.core.loginWindow.close(),t.core.loginWindow=null)})),t.core._refreshIframeOnTimeout(u,n)}catch(e){t.getLog().error("Error occurred while refreshing iframe").withException(e).sendInternalLogToServer()}})),u.onViewContact&&t.core.onViewContact(u.onViewContact),p.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.numberOfConnectedCCPs=e.length})),p.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,(function(){if(s){var e=t.core.iframeRefreshAttempt-1;t.getLog().info("Iframe initialization failed").sendInternalLogToServer(),t.getLog().info("Time after iframe initialization started "+(Date.now()-s)).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${e}`).sendInternalLogToServer(),t.publishMetric({name:a,data:{count:e}}),t.publishMetric({name:c,data:{count:0}}),s=null}})),t.core.softphoneParams=u.softphone}},t.core.onIframeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,e)},t.core._refreshIframeOnTimeout=function(n,r){t.assertNotNull(n,"initCCPParams"),t.assertNotNull(r,"containerDiv");var o=(n.disasterRecoveryOn?1e4:5e3)+AWS.util.calculateRetryDelay(t.core.iframeRefreshAttempt||0,{base:2e3});e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=e.setTimeout((function(){if(t.core.iframeRefreshAttempt=(t.core.iframeRefreshAttempt||0)+1,t.core.iframeRefreshAttempt<=6){try{var o=t.core._getCCPIframe();o&&o.parentNode.removeChild(o);var i=t.core._createCCPIframe(r,n);t.core.upstream.upstream.output=i.contentWindow,t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(i,t.core.upstream)}catch(e){t.getLog().error("Error while checking for, and recreating, the CCP IFrame").withException(e).sendInternalLogToServer()}t.core._refreshIframeOnTimeout(n,r)}else t.core.getEventBus().trigger(t.EventType.IFRAME_RETRIES_EXHAUSTED),e.clearTimeout(t.core.iframeRefreshTimeout)}),o)},t.core._getCCPIframe=function(){for(var e of window.document.getElementsByTagName("iframe"))if(e.name===n)return e;return null},t.core._createCCPIframe=function(e,r){t.assertNotNull(r,"initCCPParams"),t.assertNotNull(e,"containerDiv");var o=document.createElement("iframe");return o.src=r.ccpUrl,o.allow="microphone; autoplay",o.style=r.style||"width: 100%; height: 100%",o.title=r.iframeTitle||n,o.name=n,e.appendChild(o),o},t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime=function(e,n){t.assertNotNull(e,"iframe"),t.assertNotNull(n,"conduit"),setTimeout((function(){var r={display:window.getComputedStyle(e,null).display,offsetWidth:e.offsetWidth,offsetHeight:e.offsetHeight,clientRectsLength:e.getClientRects().length};n.sendUpstream(t.EventType.IFRAME_STYLE,r)}),1e4)};var d=function(e,t,n,r){this.conduit=e,this.eventBus=t,this.synTimeout=n,this.ackTimeout=r,this.ackTimer=null,this.synTimer=null,this.ackSub=null};d.prototype.start=function(){var n=this;this.conduit.sendUpstream(t.EventType.SYNCHRONIZE),this.ackSub=this.conduit.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(n.ackTimer),n._deferStart()})),this.ackTimer=e.setTimeout((function(){n.ackSub.unsubscribe(),n.eventBus.trigger(t.EventType.ACK_TIMEOUT),n._deferStart()}),this.ackTimeout)},d.prototype._deferStart=function(){this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout)},d.prototype.deferStart=function(){null==this.synTimer&&(this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout))};var h=function(){var e={initFailure:new Set,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},n=function(e,t){e.forEach((function(e){e(t)}))};t.core.getUpstream().onUpstream(t.WebSocketEvents.INIT_FAILURE,(function(){n(e.initFailure)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_OPEN,(function(t){n(e.connectionOpen,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_CLOSE,(function(t){n(e.connectionClose,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_GAIN,(function(){n(e.connectionGain)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_LOST,(function(t){n(e.connectionLost,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,(function(t){n(e.subscriptionUpdate,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,(function(t){n(e.subscriptionFailure,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.ALL_MESSAGE,(function(t){n(e.allMessage,t),e.topic.has(t.topic)&&n(e.topic.get(t.topic),t)})),this.sendMessage=function(e){t.core.getUpstream().sendUpstream(t.WebSocketEvents.SEND,e)},this.onInitFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.initFailure.add(n),function(){return e.initFailure.delete(n)}},this.onConnectionOpen=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionOpen.add(n),function(){return e.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionClose.add(n),function(){return e.connectionClose.delete(n)}},this.onConnectionGain=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionGain.add(n),function(){return e.connectionGain.delete(n)}},this.onConnectionLost=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionLost.add(n),function(){return e.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionUpdate.add(n),function(){return e.subscriptionUpdate.delete(n)}},this.onSubscriptionFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionFailure.add(n),function(){return e.subscriptionFailure.delete(n)}},this.subscribeTopics=function(e){t.assertNotNull(e,"topics"),t.assertTrue(t.isArray(e),"topics must be a array"),t.core.getUpstream().sendUpstream(t.WebSocketEvents.SUBSCRIBE,e)},this.onMessage=function(n,r){return t.assertNotNull(n,"topicName"),t.assertTrue(t.isFunction(r),"method must be a function"),e.topic.has(n)?e.topic.get(n).add(r):e.topic.set(n,new Set([r])),function(){return e.topic.get(n).delete(r)}},this.onAllMessage=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.allMessage.add(n),function(){return e.allMessage.delete(n)}}},f=function(e){this.bus=e,this.bus.subscribe(t.AgentEvents.UPDATE,t.hitch(this,this.updateAgentData))};f.prototype.updateAgentData=function(e){var n=this.agentData;this.agentData=e,null==n&&(t.agent.initialized=!0,this.bus.trigger(t.AgentEvents.INIT,new t.Agent)),this.bus.trigger(t.AgentEvents.REFRESH,new t.Agent),this._fireAgentUpdateEvents(n)},f.prototype.getAgentData=function(){if(null==this.agentData)throw new t.StateError("No agent data is available yet!");return this.agentData},f.prototype.getContactData=function(e){var n=this.getAgentData(),r=t.find(n.snapshot.contacts,(function(t){return t.contactId===e}));if(null==r)throw new t.StateError("Contact %s no longer exists.",e);return r},f.prototype.getConnectionData=function(e,n){var r=this.getContactData(e),o=t.find(r.connections,(function(e){return e.connectionId===n}));if(null==o)throw new t.StateError("Connection %s for contact %s no longer exists.",n,e);return o},f.prototype.getInstanceId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]},f.prototype.getAWSAccountId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]},f.prototype._diffContacts=function(e){var n={added:{},removed:{},common:{},oldMap:t.index(null==e?[]:e.snapshot.contacts,(function(e){return e.contactId})),newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))};return t.keys(n.oldMap).forEach((function(e){t.contains(n.newMap,e)?n.common[e]=n.newMap[e]:n.removed[e]=n.oldMap[e]})),t.keys(n.newMap).forEach((function(e){t.contains(n.oldMap,e)||(n.added[e]=n.newMap[e])})),n},f.prototype._fireAgentUpdateEvents=function(e){var n=this,r=null,o=null==e?t.AgentAvailStates.INIT:e.snapshot.state.name,i=this.agentData.snapshot.state.name,s=null==e?t.AgentStateType.INIT:e.snapshot.state.type,a=this.agentData.snapshot.state.type;s!==a&&t.core.getAgentRoutingEventGraph().getAssociations(this,s,a).forEach((function(e){n.bus.trigger(e,new t.Agent)})),o!==i&&(this.bus.trigger(t.AgentEvents.STATE_CHANGE,{agent:new t.Agent,oldState:o,newState:i}),t.core.getAgentStateEventGraph().getAssociations(this,o,i).forEach((function(e){n.bus.trigger(e,new t.Agent)})));var c=e&&e.snapshot.nextState?e.snapshot.nextState.name:null,u=this.agentData.snapshot.nextState?this.agentData.snapshot.nextState.name:null;c!==u&&u&&n.bus.trigger(t.AgentEvents.ENQUEUED_NEXT_STATE,new t.Agent),r=null!==e?this._diffContacts(e):{added:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId})),removed:{},common:{},oldMap:{},newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))},t.values(r.added).forEach((function(e){n.bus.trigger(t.ContactEvents.INIT,new t.Contact(e.contactId)),n._fireContactUpdateEvents(e.contactId,t.ContactStateType.INIT,e.state.type)})),t.values(r.removed).forEach((function(e){n.bus.trigger(t.ContactEvents.DESTROYED,new t.ContactSnapshot(e)),n.bus.trigger(t.core.getContactEventName(t.ContactEvents.DESTROYED,e.contactId),new t.ContactSnapshot(e)),n._unsubAllContactEventsForContact(e.contactId)})),t.keys(r.common).forEach((function(e){n._fireContactUpdateEvents(e,r.oldMap[e].state.type,r.newMap[e].state.type)}))},f.prototype._fireContactUpdateEvents=function(e,n,r){var o=this;n!==r&&t.core.getContactEventGraph().getAssociations(this,n,r).forEach((function(n){o.bus.trigger(n,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(n,e),new t.Contact(e))})),o.bus.trigger(t.ContactEvents.REFRESH,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(t.ContactEvents.REFRESH,e),new t.Contact(e))},f.prototype._unsubAllContactEventsForContact=function(e){var n=this;t.values(t.ContactEvents).forEach((function(r){n.bus.getSubscriptions(t.core.getContactEventName(r,e)).map((function(e){e.unsubscribe()}))}))},t.core.onViewContact=function(e){t.core.getUpstream().onUpstream(t.ContactEvents.VIEW,e)},t.core.viewContact=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.VIEW,data:{contactId:e}})},t.core.onActivateChannelWithViewType=function(e){t.core.getUpstream().onUpstream(t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,e)},t.core.activateChannelWithViewType=function(e,n,r,o){const i={viewType:e,mediaType:n};r&&(i.source=r),o&&(i.caseId=o),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,data:i})},t.core.triggerTaskCreated=function(e){t.core.getUpstream().upstreamBus.trigger(t.TaskEvents.CREATED,e)},t.core.onAccessDenied=function(e){t.core.getUpstream().onUpstream(t.EventType.ACCESS_DENIED,e)},t.core.onAuthFail=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTH_FAIL,e)},t.core.onAuthorizeSuccess=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTHORIZE_SUCCESS,e)},t.core._handleAuthorizeSuccess=function(){window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,0)},t.core._handleAuthFail=function(e,n,r){r&&r.authorize?t.core._handleAuthorizeFail(e):t.core._handleCTIAuthFail(n)},t.core._handleAuthorizeFail=function(e){let n=t.core._getAuthRetryCount();if(!t.core.authorizeTimeoutId)if(n{t.core._redirectToLogin(e)}),r)}else t.getLog().warn("We have exhausted our authorization retries due to 401s from the authorize api. No more retries will be attempted in this session until the authorize api returns 200.").sendInternalLogToServer(),t.core.getEventBus().trigger(t.EventType.AUTHORIZE_RETRIES_EXHAUSTED)},t.core._redirectToLogin=function(e){"string"==typeof e?location.assign(e):location.reload()},t.core._handleCTIAuthFail=function(e){if(!t.core.ctiTimeoutId)if(t.core.ctiAuthRetryCount{t.core.authorize(e).then(t.core._triggerAuthorizeSuccess.bind(t.core)).catch(t.core._triggerAuthFail.bind(t.core,{authorize:!0})),t.core.ctiTimeoutId=null}),n)}else t.getLog().warn("We have exhausted our authorization retries due to 401s from the CTI service. No more retries will be attempted until the page is refreshed.").sendInternalLogToServer(),t.core.getEventBus().trigger(t.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED)},t.core._triggerAuthorizeSuccess=function(){t.core.getUpstream().upstreamBus.trigger(t.EventType.AUTHORIZE_SUCCESS)},t.core._triggerAuthFail=function(e){t.core.getUpstream().upstreamBus.trigger(t.EventType.AUTH_FAIL,e)},t.core._getAuthRetryCount=function(){let e=window.sessionStorage.getItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT);if(null!==e){if(isNaN(parseInt(e)))throw new t.StateError("The session storage value for auth retry count was NaN");return parseInt(e)}return window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,0),0},t.core._incrementAuthRetryCount=function(){window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,(t.core._getAuthRetryCount()+1).toString())},t.core.onAuthorizeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.AUTHORIZE_RETRIES_EXHAUSTED,e)},t.core.onCTIAuthorizeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED,e)},t.core.onSoftphoneSessionInit=function(e){t.core.getUpstream().onUpstream(t.ConnectionEvents.SESSION_INIT,e)},t.core.onConfigure=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.CONFIGURE,e)},t.core.onInitialized=function(e){t.core.getEventBus().subscribe(t.EventType.INIT,e)},t.core.getContactEventName=function(e,n){if(t.assertNotNull(e,"eventName"),t.assertNotNull(n,"contactId"),!t.contains(t.values(t.ContactEvents),e))throw new t.ValueError("%s is not a valid contact event.",e);return t.sprintf("%s::%s",e,n)},t.core.getEventBus=function(){return t.core.eventBus},t.core.getWebSocketManager=function(){return t.core.webSocketProvider},t.core.getAgentDataProvider=function(){return t.core.agentDataProvider},t.core.getLocalTimestamp=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp},t.core.getSkew=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.skew},t.core.getAgentRoutingEventGraph=function(){return t.core.agentRoutingEventGraph},t.core.agentRoutingEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.AgentStateType.ROUTABLE,t.AgentEvents.ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.NOT_ROUTABLE,t.AgentEvents.NOT_ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.OFFLINE,t.AgentEvents.OFFLINE),t.core.getAgentStateEventGraph=function(){return t.core.agentStateEventGraph},t.core.agentStateEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.values(t.AgentErrorStates),t.AgentEvents.ERROR).assoc(t.EventGraph.ANY,t.AgentAvailStates.AFTER_CALL_WORK,t.AgentEvents.ACW),t.core.getContactEventGraph=function(){return t.core.contactEventGraph},t.core.contactEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.ContactStateType.INCOMING,t.ContactEvents.INCOMING).assoc(t.EventGraph.ANY,t.ContactStateType.PENDING,t.ContactEvents.PENDING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTING,t.ContactEvents.CONNECTING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTED,t.ContactEvents.CONNECTED).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.ContactStateType.INCOMING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.EventGraph.ANY,t.ContactStateType.ENDED,t.ContactEvents.ACW).assoc(t.values(t.CONTACT_ACTIVE_STATES),t.values(t.relativeComplement(t.CONTACT_ACTIVE_STATES,t.ContactStateType)),t.ContactEvents.ENDED).assoc(t.EventGraph.ANY,t.ContactStateType.ERROR,t.ContactEvents.ERROR).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.MISSED,t.ContactEvents.MISSED),t.core.getClient=function(){if(!t.core.client)throw new t.StateError("The connect core has not been initialized!");return t.core.client},t.core.client=null,t.core.getAgentAppClient=function(){if(!t.core.agentAppClient)throw new t.StateError("The connect AgentApp Client has not been initialized!");return t.core.agentAppClient},t.core.agentAppClient=null,t.core.getTaskTemplatesClient=function(){if(!t.core.taskTemplatesClient)throw new t.StateError("The connect TaskTemplates Client has not been initialized!");return t.core.taskTemplatesClient},t.core.taskTemplatesClient=null,t.core.getMasterClient=function(){if(!t.core.masterClient)throw new t.StateError("The connect master client has not been initialized!");return t.core.masterClient},t.core.masterClient=null,t.core.getSoftphoneManager=function(){return t.core.softphoneManager},t.core.softphoneManager=null,t.core.getNotificationManager=function(){return t.core.notificationManager||(t.core.notificationManager=new t.NotificationManager),t.core.notificationManager},t.core.notificationManager=null,t.core.getPopupManager=function(){return t.core.popupManager},t.core.popupManager=new t.PopupManager,t.core.getUpstream=function(){if(!t.core.upstream)throw new t.StateError("There is no upstream conduit!");return t.core.upstream},t.core.upstream=null,t.core.AgentDataProvider=f}()},592:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t;var n="<>",r=t.makeEnum(["acknowledge","ack_timeout","init","api_request","api_response","auth_fail","access_denied","close","configure","log","master_request","master_response","synchronize","terminate","terminated","send_logs","reload_agent_configuration","broadcast","api_metric","client_metric","softphone_stats","softphone_report","client_side_logs","server_bound_internal_log","mute","iframe_style","iframe_retries_exhausted","update_connected_ccps","outer_context_info","media_device_request","media_device_response","tab_id","authorize_success","authorize_retries_exhausted","cti_authorize_retries_exhausted","click_stream_data"]),o=t.makeNamespacedEnum("connect",["loginPopup","sendLogs","softphone","ringtone","metrics"]),i=t.makeNamespacedEnum("agent",["init","update","refresh","routable","not_routable","pending","contact_pending","offline","error","softphone_error","websocket_connection_lost","websocket_connection_gained","state_change","acw","mute_toggle","local_media_stream_created","enqueued_next_state"]),s=t.makeNamespacedEnum("webSocket",["init_failure","connection_open","connection_close","connection_error","connection_gain","connection_lost","subscription_update","subscription_failure","all_message","send","subscribe"]),a=t.makeNamespacedEnum("contact",["init","refresh","destroyed","incoming","pending","connecting","connected","missed","acw","view","ended","error","accepted"]),c=t.makeNamespacedEnum("taskList",["activate_channel_with_view_type"]),u=t.makeNamespacedEnum("task",["created"]),l=t.makeNamespacedEnum("connection",["session_init","ready_to_start_session"]),p=t.makeNamespacedEnum("configuration",["configure","set_speaker_device","set_microphone_device","set_ringer_device","speaker_device_changed","microphone_device_changed","ringer_device_changed"]),d=t.makeNamespacedEnum("voiceId",["update_domain_id"]),h=function(){};h.createRequest=function(e,n,r){return{event:e,requestId:t.randomId(),method:n,params:r}},h.createResponse=function(e,t,n,r){return{event:e,requestId:t.requestId,data:n,err:r||null}};var f=function(e,n,r){this.subMap=e,this.id=t.randomId(),this.eventName=n,this.f=r};f.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var g=function(){this.subIdMap={},this.subEventNameMap={}};g.prototype.subscribe=function(e,t){var n=new f(this,e,t);this.subIdMap[n.id]=n;var r=this.subEventNameMap[e]||[];return r.push(n),this.subEventNameMap[e]=r,n},g.prototype.unsubscribe=function(e,n){t.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==n})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),t.contains(this.subIdMap,n)&&delete this.subIdMap[n]},g.prototype.getAllSubscriptions=function(){return t.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},g.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var m=function(e){var t=e||{};this.subMap=new g,this.logEvents=t.logEvents||!1};m.prototype.subscribe=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.subMap.subscribe(e,n)},m.prototype.subscribeAll=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.subMap.subscribe(n,e)},m.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},m.prototype.trigger=function(e,r){t.assertNotNull(e,"eventName");var o=this,i=this.subMap.getSubscriptions(n),s=this.subMap.getSubscriptions(e);this.logEvents&&e!==t.EventType.LOG&&e!==t.EventType.MASTER_RESPONSE&&e!==t.EventType.API_METRIC&&e!==t.EventType.SERVER_BOUND_INTERNAL_LOG&&t.getLog().trace("Publishing event: %s",e).sendInternalLogToServer(),e.startsWith(t.ContactEvents.ACCEPTED)&&r&&r.contactId&&!(r instanceof t.Contact)&&(r=new t.Contact(r.contactId)),i.concat(s).forEach((function(n){try{n.f(r||null,e,o)}catch(n){t.getLog().error("'%s' event handler failed.",e).withException(n).sendInternalLogToServer()}}))},m.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},m.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))},t.EventBus=m,t.EventFactory=h,t.EventType=r,t.AgentEvents=i,t.ConfigurationEvents=p,t.ConnectionEvents=l,t.ConnnectionEvents=l,t.ContactEvents=a,t.ChannelViewEvents=c,t.TaskEvents=u,t.VoiceIdEvents=d,t.WebSocketEvents=s,t.MasterTopics=o}()},286:()=>{!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";var r=n(1),o="DEBUG",i="AMZ_WEB_SOCKET_MANAGER:",s="Network offline",a="Network online, connecting to WebSocket server",c="Network offline, ignoring this getWebSocketConnConfig request",u="Heartbeat response not received",l="Failed to send heartbeat since WebSocket is not open",p="WebSocket connection established!",d="WebSocket connection is closed",h="WebSocketManager Error, error_event: ",f="Scheduling WebSocket reinitialization, after delay ",g="WebSocket URL cannot be used to establish connection",m="WebSocket Initialization failed - Terminating and cleaning subscriptions",v="Fetching new WebSocket connection configuration",y="Successfully fetched webSocket connection configuration",E="Failed to fetch webSocket connection configuration",S="Retrying fetching new WebSocket connection configuration",b="Initializing Websocket Manager",C="WebSocketManager Message Error",T="Message received for topic ",I="Invalid incoming message",_="aws/subscribe",A="aws/heartbeat",w="disconnected";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})(e)}var k={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return k.assertTrue(null!==e&&void 0!==R(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"!==R(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},N=new RegExp("^(wss://)\\w*");k.validWSUrl=function(e){return N.test(e)},k.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},k.assertIsObject=function(e,t){if(!k.isObject(e))throw new Error(t+" is not an object!")},k.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)},k.isNetworkOnline=function(){return navigator.onLine},k.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var O=k;function L(e){return(L=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function D(e,t){return(D=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function P(e){return(P="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 x(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var n=0;n=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var t=e.prefix||q;return this._logsDestination===o?this.consoleLoggerWrapper:new W(t)}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||j.INFO,this._advancedLogWriter="warn",t.advancedLogWriter&&(this._advancedLogWriter=t.advancedLogWriter),t.customizedLogger&&"object"===P(t.customizedLogger)&&(this.useClientLogger=!0),this._clientLogger=t.logger||this.selectLogger(t),this._logsDestination="NULL",t.debug&&(this._logsDestination=o),t.logger&&(this._logsDestination="CLIENT_LOGGER")}},{key:"selectLogger",value:function(e){return e.customizedLogger&&"object"===P(e.customizedLogger)?e.customizedLogger:e.useDefaultLogger?(this.consoleLoggerWrapper=H(),this.consoleLoggerWrapper):null}}]),e}(),V=function(){function e(){x(this,e)}return U(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}},{key:"advancedLog",value:function(){}}]),e}(),W=function(e){function t(e){var n;return x(this,t),(n=function(e,t){return!t||"object"!==P(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,L(t).call(this))).prefix=e||q,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&&D(e,t)}(t,V),U(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}},{key:"getIsConnected",value:function(){return!this.numAttempts}}])&&G(t.prototype,n),e}();n.d(t,"a",(function(){return Y}));var X=function(){var e=z.getLogger({prefix:i}),t=O.isNetworkOnline(),n={primary:null,secondary:null},r={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},o={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},R={pendingResponse:!1,intervalHandle:null},k={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},N={connConfig:null,promiseHandle:null,promiseCompleted:!0},L={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},D={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},P=new K((function(){se()})),x=new Set([_,"aws/unsubscribe",A]),M=setInterval((function(){if(t!==O.isNetworkOnline()){if(!(t=O.isNetworkOnline()))return e.advancedLog(s),void ue(e.info(s));var n=W();t&&(!n||j(n,WebSocket.CLOSING)||j(n,WebSocket.CLOSED))&&(e.advancedLog(a),ue(e.info(a)),se())}}),250),U=function(t,n){t.forEach((function(t){try{t(n)}catch(t){ue(e.error("Error executing callback",t))}}))},F=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"}},q=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";ue(e.debug("["+t+"] Primary WebSocket: "+F(n.primary)+" | Secondary WebSocket: "+F(n.secondary)))},j=function(e,t){return e&&e.readyState===t},B=function(e){return j(e,WebSocket.OPEN)},V=function(e){return null===e||void 0===e.readyState||j(e,WebSocket.CLOSED)},W=function(){return null!==n.secondary?n.secondary:n.primary},H=function(){return B(W())},G=function(){if(R.pendingResponse)return e.advancedLog(u),ue(e.warn(u)),clearInterval(R.intervalHandle),R.pendingResponse=!1,void se();H()?(ue(e.debug("Sending heartbeat")),W().send(oe(A)),R.pendingResponse=!0):(e.advancedLog(l),ue(e.warn(l)),q("sendHeartBeat"),se())},X=function(){e.advancedLog("Reset Websocket state"),r.exponentialBackOffTime=1e3,R.pendingResponse=!1,r.reconnectWebSocket=!0,clearTimeout(r.lifeTimeTimeoutHandle),clearInterval(R.intervalHandle),clearTimeout(r.exponentialTimeoutHandle),clearTimeout(r.webSocketInitCheckerTimeoutId)},Y=function(){D.consecutiveFailedSubscribeAttempts=0,D.consecutiveNoResponseRequest=0,clearInterval(D.responseCheckIntervalId),clearInterval(D.reSubscribeIntervalId)},J=function(){o.connectWebSocketRetryCount=0,o.connectionAttemptStartTime=null,o.noOpenConnectionsTimestamp=null},Q=function(){P.connected();try{e.advancedLog(p),ue(e.info(p)),q("webSocketOnOpen"),null!==r.connState&&r.connState!==w||U(k.connectionGain),r.connState="connected";var t=Date.now();U(k.connectionOpen,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,noOpenConnectionsTimestamp:o.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-o.connectionAttemptStartTime,timeWithoutConnection:o.noOpenConnectionsTimestamp?t-o.noOpenConnectionsTimestamp:null}),J(),X(),W().openTimestamp=Date.now(),0===L.subscribed.size&&B(n.secondary)&&te(n.primary,"[Primary WebSocket] Closing WebSocket"),(L.subscribed.size>0||L.pending.size>0)&&(B(n.secondary)&&ue(e.info("Subscribing secondary websocket to topics of primary websocket")),L.subscribed.forEach((function(e){L.subscriptionHistory.add(e),L.pending.add(e)})),L.subscribed.clear(),ee()),G(),R.intervalHandle=setInterval(G,1e4);var i=1e3*N.connConfig.webSocketTransport.transportLifeTimeInSeconds;ue(e.debug("Scheduling WebSocket manager reconnection, after delay "+i+" ms")),r.lifeTimeTimeoutHandle=setTimeout((function(){ue(e.debug("Starting scheduled WebSocket manager reconnection")),se()}),i)}catch(t){ue(e.error("Error after establishing WebSocket connection",t))}},Z=function(t){q("webSocketOnError"),e.advancedLog(h,JSON.stringify(t)),ue(e.error(h,JSON.stringify(t))),P.getIsConnected()?se():P.retry()},$=function(t){var r=JSON.parse(t.data);switch(r.topic){case _:if(ue(e.debug("Subscription Message received from webSocket server",t.data)),D.requestCompleted=!0,D.consecutiveNoResponseRequest=0,"success"===r.content.status)D.consecutiveFailedSubscribeAttempts=0,r.content.topics.forEach((function(e){L.subscriptionHistory.delete(e),L.pending.delete(e),L.subscribed.add(e)})),0===L.subscriptionHistory.size?B(n.secondary)&&(ue(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),te(n.primary,"[Primary WebSocket] Closing WebSocket")):ee(),U(k.subscriptionUpdate,r);else{if(clearInterval(D.reSubscribeIntervalId),++D.consecutiveFailedSubscribeAttempts,5===D.consecutiveFailedSubscribeAttempts)return U(k.subscriptionFailure,r),void(D.consecutiveFailedSubscribeAttempts=0);D.reSubscribeIntervalId=setInterval((function(){ee()}),500)}break;case A:ue(e.debug("Heartbeat response received")),R.pendingResponse=!1;break;default:if(r.topic){if(e.advancedLog(T,r.topic),ue(e.debug(T+r.topic)),B(n.primary)&&B(n.secondary)&&0===L.subscriptionHistory.size&&this===n.primary)return void ue(e.warn("Ignoring Message for Topic "+r.topic+", to avoid duplicates"));if(0===k.allMessage.size&&0===k.topic.size)return void ue(e.warn("No registered callback listener for Topic",r.topic));e.advancedLog("WebsocketManager invoke callbacks for topic success ",r.topic),U(k.allMessage,r),k.topic.has(r.topic)&&U(k.topic.get(r.topic),r)}else r.message?(e.advancedLog(C,r),ue(e.warn(C,r))):(e.advancedLog(I,r),ue(e.warn(I,r)))}},ee=function t(){if(D.consecutiveNoResponseRequest>3)return ue(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void U(k.subscriptionFailure,O.getSubscriptionResponse(_,!1,Array.from(L.pending)));H()?0!==Array.from(L.pending).length&&(clearInterval(D.responseCheckIntervalId),W().send(oe(_,{topics:Array.from(L.pending)})),D.requestCompleted=!1,D.responseCheckIntervalId=setInterval((function(){D.requestCompleted||(++D.consecutiveNoResponseRequest,t())}),1e3)):ue(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},te=function(t,n){j(t,WebSocket.CONNECTING)||j(t,WebSocket.OPEN)?t.close(1e3,n):ue(e.warn("Ignoring WebSocket Close request, WebSocket State: "+F(t)))},ne=function(e){te(n.primary,"[Primary] WebSocket "+e),te(n.secondary,"[Secondary] WebSocket "+e)},re=function(t){X(),Y(),e.advancedLog(m,t),ue(e.error(m)),r.websocketInitFailed=!0,ne("Terminating WebSocket Manager"),clearInterval(M),U(k.initFailure,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,reason:t}),J()},oe=function(e,t){return JSON.stringify({topic:e,content:t})},ie=function(t){return!!(O.isObject(t)&&O.isObject(t.webSocketTransport)&&O.isNonEmptyString(t.webSocketTransport.url)&&O.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(ue(e.error("Invalid WebSocket Connection Configuration",t)),!1)},se=function(){if(!O.isNetworkOnline())return e.advancedLog(c),void ue(e.info(c));if(r.websocketInitFailed)ue(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(N.promiseCompleted)return X(),e.advancedLog(v),ue(e.info(v)),o.connectionAttemptStartTime=o.connectionAttemptStartTime||Date.now(),N.promiseCompleted=!1,N.promiseHandle=k.getWebSocketTransport(),N.promiseHandle.then((function(t){return N.promiseCompleted=!0,e.advancedLog(y),ue(e.debug(y,t)),ie(t)?(N.connConfig=t,N.connConfig.urlConnValidTime=Date.now()+85e3,ae()):(re("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return N.promiseCompleted=!0,e.advancedLog(E),ue(e.error(E,t)),O.isNetworkFailure(t)?(e.advancedLog(S+JSON.stringify(t)),ue(e.info(S+JSON.stringify(t))),P.retry()):re("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));ue(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}},ae=function(){if(r.websocketInitFailed)return ue(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!O.isNetworkOnline())return ue(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};e.advancedLog(b),ue(e.info(b)),q("initWebSocket");try{if(ie(N.connConfig)){var t=null;return B(n.primary)?(ue(e.debug("Primary Socket connection is already open")),j(n.secondary,WebSocket.CONNECTING)||(ue(e.debug("Establishing a secondary web-socket connection")),P.numAttempts=0,n.secondary=ce()),t=n.secondary):(j(n.primary,WebSocket.CONNECTING)||(ue(e.debug("Establishing a primary web-socket connection")),n.primary=ce()),t=n.primary),r.webSocketInitCheckerTimeoutId=setTimeout((function(){B(t)||function(){o.connectWebSocketRetryCount++;var t=O.addJitter(r.exponentialBackOffTime,.3);Date.now()+t<=N.connConfig.urlConnValidTime?(e.advancedLog(f),ue(e.debug(f+t+" ms")),r.exponentialTimeoutHandle=setTimeout((function(){return ae()}),t),r.exponentialBackOffTime*=2):(e.advancedLog(g),ue(e.warn(g)),se())}()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return ue(e.error("Error Initializing web-socket-manager",t)),re("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},ce=function(){var t=new WebSocket(N.connConfig.webSocketTransport.url);return t.addEventListener("open",Q),t.addEventListener("message",$),t.addEventListener("error",Z),t.addEventListener("close",(function(i){return function(t,i){e.advancedLog(d,JSON.stringify(t)),ue(e.info(d,JSON.stringify(t))),q("webSocketOnClose before-cleanup"),U(k.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),V(n.primary)&&(n.primary=null),V(n.secondary)&&(n.secondary=null),r.reconnectWebSocket&&(B(n.primary)||B(n.secondary)?V(n.primary)&&B(n.secondary)&&(ue(e.info("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(ue(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),r.connState===w?ue(e.info("Ignoring connectionLost callback invocation")):(U(k.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),o.noOpenConnectionsTimestamp=Date.now()),r.connState=w,se()),q("webSocketOnClose after-cleanup"))}(i,t)})),t},ue=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(O.assertTrue(O.isFunction(t),"transportHandle must be a function"),null===k.getWebSocketTransport)return k.getWebSocketTransport=t,se();ue(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(t){return e.advancedLog("Initializing Websocket Manager Failed!"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.initFailure.add(t),r.websocketInitFailed&&t(),function(){return k.initFailure.delete(t)}},this.onConnectionOpen=function(t){return e.advancedLog("Websocket connection open"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.connectionOpen.add(t),function(){return k.connectionOpen.delete(t)}},this.onConnectionClose=function(t){return e.advancedLog("Websocket connection close"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.connectionClose.add(t),function(){return k.connectionClose.delete(t)}},this.onConnectionGain=function(t){return e.advancedLog("Websocket connection gain"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.connectionGain.add(t),H()&&t(),function(){return k.connectionGain.delete(t)}},this.onConnectionLost=function(t){return e.advancedLog("Websocket connection lost"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.connectionLost.add(t),r.connState===w&&t(),function(){return k.connectionLost.delete(t)}},this.onSubscriptionUpdate=function(e){return O.assertTrue(O.isFunction(e),"cb must be a function"),k.subscriptionUpdate.add(e),function(){return k.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(t){return e.advancedLog("Websocket subscription failure"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.subscriptionFailure.add(t),function(){return k.subscriptionFailure.delete(t)}},this.onMessage=function(e,t){return O.assertNotNull(e,"topicName"),O.assertTrue(O.isFunction(t),"cb must be a function"),k.topic.has(e)?k.topic.get(e).add(t):k.topic.set(e,new Set([t])),function(){return k.topic.get(e).delete(t)}},this.onAllMessage=function(e){return O.assertTrue(O.isFunction(e),"cb must be a function"),k.allMessage.add(e),function(){return k.allMessage.delete(e)}},this.subscribeTopics=function(e){O.assertNotNull(e,"topics"),O.assertIsList(e),e.forEach((function(e){L.subscribed.has(e)||L.pending.add(e)})),D.consecutiveNoResponseRequest=0,ee()},this.sendMessage=function(t){if(O.assertIsObject(t,"payload"),void 0===t.topic||x.has(t.topic))ue(e.warn("Cannot send message, Invalid topic",t));else{try{t=JSON.stringify(t)}catch(n){return void ue(e.warn("Error stringify message",t))}H()?W().send(t):ue(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){X(),Y(),r.reconnectWebSocket=!1,clearInterval(M),ne("User request to close WebSocket")},this.terminateWebSocketManager=re},Y={create:function(){return new X},setGlobalConfig:function(e){var t=e&&e.loggerConfig;z.updateLoggerConfig(t)},LogLevel:j,Logger:F}},function(e,t,n){var r;!function(){"use strict";var o={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,t){var n,r,s,a,c,u,l,p,d,h=1,f=e.length,g="";for(r=0;r=0),a.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}o.json.test(a.type)?g+=n:(!o.number.test(a.type)||p&&!a.sign?d="":(d=p?"+":"-",n=n.toString().replace(o.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(d+n).length,c=a.width&&l>0?u.repeat(l):"",g+=a.align?d+n+c:"0"===u?d+c+n:c+d+n)}return g}(function(e){if(a[e])return a[e];for(var t,n=e,r=[],i=0;n;){if(null!==(t=o.text.exec(n)))r.push(t[0]);else if(null!==(t=o.modulo.exec(n)))r.push("%");else{if(null===(t=o.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){i|=1;var s=[],c=t[2],u=[];if(null===(u=o.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=o.key_access.exec(c)))s.push(u[1]);else{if(null===(u=o.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}t[2]=s}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");r.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return a[e]=r}(e),arguments)}function s(e,t){return i.apply(null,[e].concat(t||[]))}var a=Object.create(null);t.sprintf=i,t.vsprintf=s,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=s,void 0===(r=function(){return{sprintf:i,vsprintf:s}}.call(t,n,t,e))||(e.exports=r))}()},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"WebSocketManager",(function(){return o}));var r=n(0);e.connect=e.connect||{},connect.WebSocketManager=r.a;var o=r.a}.call(this,n(3))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n}])},151:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t;var n={TEST:"TEST",TRACE:"TRACE",DEBUG:"DEBUG",INFO:"INFO",LOG:"LOG",WARN:"WARN",ERROR:"ERROR",CRITICAL:"CRITICAL"},r={CCP:"ccp",SOFTPHONE:"softphone",CHAT:"chat",TASK:"task"},o={TEST:0,TRACE:10,DEBUG:20,INFO:30,LOG:40,WARN:50,ERROR:100,CRITICAL:200},i={TRACE:function(e){console.info(e)},DEBUG:function(e){console.info(e)},INFO:function(e){console.info(e)},LOG:function(e){console.log(e)},TEST:function(e){console.log(e)},WARN:function(e){console.warn(e)},ERROR:function(e){console.error(e)},CRITICAL:function(e){console.error(e)}},s=function(e){var t,n,o=Array.prototype.slice.call(e,0),i=o.shift();return function(e){return-1!==Object.values(r).indexOf(e)}(i)?(n=i,t=o.shift()):(t=i,n=r.CCP),{format:t,component:n,args:o}},a=function(e,n,r,o){this.component=e,this.level=n,this.text=r,this.time=new Date,this.exception=null,this.objects=[],this.line=0,this.agentResourceId=null;try{t.agent.initialized&&(this.agentResourceId=(new t.Agent)._getResourceId())}catch(e){console.log("Issue finding agentResourceId: ",e)}this.loggerId=o};a.fromObject=function(e){var t=new a(r.CCP,e.level,e.text,e.loggerId);return"[object Date]"===Object.prototype.toString.call(e.time)?t.time=new Date(e.time.getTime()):"number"==typeof e.time?t.time=new Date(e.time):"string"==typeof e.time?t.time=Date.parse(e.time):t.time=new Date,t.exception=e.exception,t.objects=e.objects,t};var c=function(e){var t=/AuthToken.*\=/g;e&&"object"==typeof e&&Object.keys(e).forEach((function(n){"object"==typeof e[n]?c(e[n]):"string"==typeof e[n]&&("url"===n||"text"===n?e[n]=e[n].replace(t,"[redacted]"):"quickConnectName"===n&&(e[n]="[redacted]"))}))},u=function(e){if(this.type=e instanceof Error?e.name:e.code||Object.prototype.toString.call(e),this.message=e.message,this.stack=[],e.stack)try{Array.isArray(e.stack)?this.stack=e.stack:"object"==typeof e.stack?this.stack=[JSON.stringify(e.stack)]:"string"==typeof e.stack&&(this.stack=e.stack.split("\n"))}catch{}};a.prototype.toString=function(){return t.sprintf("[%s] [%s] [%s]: %s",this.getTime()&&this.getTime().toISOString?this.getTime().toISOString():"???",this.getLevel(),this.getAgentResourceId(),this.getText())},a.prototype.getTime=function(){return this.time},a.prototype.getAgentResourceId=function(){return this.agentResourceId},a.prototype.getLevel=function(){return this.level},a.prototype.getText=function(){return this.text},a.prototype.getComponent=function(){return this.component},a.prototype.withException=function(e){return this.exception=new u(e),this},a.prototype.withObject=function(e){var n=t.deepcopy(e);return c(n),this.objects.push(n),this},a.prototype.withCrossOriginEventObject=function(e){var n=t.deepcopyCrossOriginEvent(e);return c(n),this.objects.push(n),this},a.prototype.sendInternalLogToServer=function(){return t.getLog()._serverBoundInternalLogs.push(this),this};var l=function(){this._logs=[],this._rolledLogs=[],this._logsToPush=[],this._serverBoundInternalLogs=[],this._echoLevel=o.INFO,this._logLevel=o.INFO,this._lineCount=0,this._logRollInterval=0,this._logRollTimer=null,this._loggerId=(new Date).getTime()+"-"+Math.random().toString(36).slice(2),this.setLogRollInterval(18e5),this._startLogIndexToPush=0};l.prototype.setLogRollInterval=function(t){var n=this;this._logRollTimer&&t===this._logRollInterval?this.warn("Logger is already set to the given interval: %d",this._logRollInterval):(this._logRollTimer&&e.clearInterval(this._logRollTimer),this._logRollInterval=t,this._logRollTimer=e.setInterval((function(){n._rolledLogs=n._logs,n._logs=[],n._startLogIndexToPush=0,n.info("Log roll interval occurred.")}),this._logRollInterval))},l.prototype.setLogLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._logLevel=o[e]},l.prototype.setEchoLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._echoLevel=o[e]},l.prototype.write=function(e,t,n){var r=new a(e,t,n,this.getLoggerId());return c(r),this.addLogEntry(r),r},l.prototype.addLogEntry=function(e){c(e),this._logs.push(e),r.SOFTPHONE===e.component&&this._logsToPush.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.sendInternalLogEntryToServer=function(e){this._serverBoundInternalLogs.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=i._logLevel})));var a=new e.Blob([JSON.stringify(s,void 0,4)],["text/plain"]),c=document.createElement("a");n=n||"agent-log",c.href=e.URL.createObjectURL(a),c.download=n+".txt",document.body.appendChild(c),c.click(),document.body.removeChild(c)},l.prototype.scheduleUpstreamLogPush=function(n){t.upstreamLogPushScheduled||(t.upstreamLogPushScheduled=!0,e.setInterval(t.hitch(this,this.reportMasterLogsUpStream,n),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var n=this._logsToPush.slice();this._logsToPush=[],t.ifMaster(t.MasterTopics.SEND_LOGS,(function(){n.length>0&&e.sendUpstream(t.EventType.SEND_LOGS,n)}))},l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPserverBoundLogsUpstream,n),1e3)},l.prototype.scheduleUpstreamOuterContextCCPLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPLogsUpstream,n),1e3)},l.prototype.pushOuterContextCCPserverBoundLogsUpstream=function(e){if(this._serverBoundInternalLogs.length>0){for(var n=0;n500?e=this._serverBoundInternalLogs.splice(0,500):(e=this._serverBoundInternalLogs,this._serverBoundInternalLogs=[]),t.publishClientSideLogs(e))};var p=function(n){l.call(this),this.conduit=n,e.setInterval(t.hitch(this,this._pushLogsDownstream),p.LOG_PUSH_INTERVAL),e.clearInterval(this._logRollTimer),this._logRollTimer=null};p.LOG_PUSH_INTERVAL=1e3,p.prototype=Object.create(l.prototype),p.prototype.constructor=p,p.prototype.pushLogsDownstream=function(e){var n=this;e.forEach((function(e){n.conduit.sendDownstream(t.EventType.LOG,e)}))},p.prototype._pushLogsDownstream=function(){var e=this;this._logs.forEach((function(n){e.conduit.sendDownstream(t.EventType.LOG,n)})),this._logs=[];for(var n=0;n{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,t.ChatMediaController=function(e,n){var r=t.getLog(),o=t.LogComponent.CHAT,i=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},s=function(e){e.onConnectionBroken((function(e){r.error(o,"Chat Session connection broken").withException(e).sendInternalLogToServer(),i("Chat Session connection broken",e)})),e.onConnectionEstablished((function(e){r.info(o,"Chat Session connection established").withObject(e).sendInternalLogToServer(),i("Chat Session connection established",e)}))};return{get:function(){return function(){i("Chat media controller init",e.contactId),r.info(o,"Chat media controller init").withObject(e).sendInternalLogToServer(),t.ChatSession.setGlobalConfig({loggerConfig:{logger:r},region:n.region});var a=t.ChatSession.create({chatDetails:e,type:"AGENT",websocketManager:t.core.getWebSocketManager()});return s(a),a.connect().then((function(t){return r.info(o,"Chat Session Successfully established for contactId %s",e.contactId).sendInternalLogToServer(),i("Chat Session Successfully established",e.contactId),a})).catch((function(t){throw r.error(o,"Chat Session establishement failed for contact %s",e.contactId).withException(t).sendInternalLogToServer(),i("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},279:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,t.MediaFactory=function(e){var n={},r=new Set,o=t.getLog(),i=t.LogComponent.CHAT,s=t.merge({},e)||{};s.region=s.region||"us-west-2";var a=function(e){n[e]&&!r.has(e)&&(o.info(i,"Destroying mediaController for %s",e),r.add(e),n[e].then((function(){"function"==typeof controller.cleanUp&&controller.cleanUp(),delete n[e],r.delete(e)})).catch((function(){delete n[e],r.delete(e)})))};return{get:function(e){return function(e){return e.isActive()}(e)?function(e){var r=e.getConnectionId();if(!e.getMediaInfo())return o.error(i,"Media info does not exist for a media type %s",e.getMediaType()).withObject(e).sendInternalLogToServer(),Promise.reject("Media info does not exist for this connection");if(n[r])return n[r];switch(o.info(i,"media controller of type %s init",e.getMediaType()).withObject(e).sendInternalLogToServer(),e.getMediaType()){case t.MediaType.CHAT:return n[r]=new t.ChatMediaController(e.getMediaInfo(),s).get();case t.MediaType.SOFTPHONE:return n[r]=new t.SoftphoneMediaController(e.getMediaInfo()).get();case t.MediaType.TASK:return n[r]=new t.TaskMediaController(e.getMediaInfo()).get();default:return o.error(i,"Unrecognized media type %s ",e.getMediaType()).sendInternalLogToServer(),Promise.reject()}}(e):(a(e.getConnectionId()),Promise.reject("Media Controller is no longer available for this connection"))},destroy:a}}}()},418:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,t.SoftphoneMediaController=function(e){return{get:function(){return Promise.resolve(e)}}}}()},187:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,t.TaskMediaController=function(e){var n=t.getLog(),r=t.LogComponent.TASK,o=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},i=function(e){e.onConnectionBroken((function(e){n.error(r,"Task Session connection broken").withException(e),o("Task Session connection broken",e)})),e.onConnectionEstablished((function(e){n.info(r,"Task Session connection established").withObject(e),o("Task Session connection established",e)}))};return{get:function(){return function(){o("Task media controller init",e.contactId),n.info(r,"Task media controller init").withObject(e);var s=t.TaskSession.create({contactId:e.contactId,initialContactId:e.initialContactId,websocketManager:t.core.getWebSocketManager()});return i(s),s.connect().then((function(){return n.info(r,"Task Session Successfully established for contactId %s",e.contactId),o("Task Session Successfully established",e.contactId),s})).catch((function(t){throw n.error(r,"Task Session establishement failed for contact %s",e.contactId).withException(t),o("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},743:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t;var n=function(n){var r=this;if(this._prevContactId=null,t.assertNotNull(n,"ringtoneConfig"),!n.ringtoneUrl)throw new Error("ringtoneUrl is required!");e.Audio&&void 0!==e.Promise?this._playableAudioPromise=new Promise((function(e,t){r._audio=new Audio(n.ringtoneUrl),r._audio.loop=!0,r._audio.addEventListener("canplay",(function(){r._audioPlayable=!0,e(r._audio)}))})):(this._audio=null,t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()),r._driveRingtone()};n.prototype._driveRingtone=function(){throw new Error("Not implemented.")},n.prototype._startRingtone=function(e){var n=this;this._audio&&(this._audio.play().catch((function(r){n._publishTelemetryEvent("Ringtone Playback Failure",e),t.getLog().error("Ringtone Playback Failure").withException(r).withObject({currentSrc:n._audio.currentSrc,sinkId:n._audio.sinkId,volume:n._audio.volume}).sendInternalLogToServer()})),n._publishTelemetryEvent("Ringtone Start",e),t.getLog().info("Ringtone Start").sendInternalLogToServer())},n.prototype._stopRingtone=function(e){this._audio&&(this._audio.pause(),this._audio.currentTime=0,this._publishTelemetryEvent("Ringtone Stop",e),t.getLog().info("Ringtone Stop").sendInternalLogToServer())},n.prototype.stopRingtone=function(){this._stopRingtone()},n.prototype._ringtoneSetup=function(e){var n=this;t.ifMaster(t.MasterTopics.RINGTONE,(function(){n._startRingtone(e),n._prevContactId=e.getContactId(),e.onConnected(lily.hitch(n,n._stopRingtone)),e.onAccepted(lily.hitch(n,n._stopRingtone)),e.onEnded(lily.hitch(n,n._stopRingtone)),e.onRefresh((function(e){e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING&&n._stopRingtone()}))}))},n.prototype._publishTelemetryEvent=function(e,n){n&&n.getContactId()&&t.publishMetric({name:e,contactId:n.getContactId()})},n.prototype.setOutputDevice=function(t){return this._playableAudioPromise?Promise.race([this._playableAudioPromise,new Promise((function(t,n){e.setTimeout((function(){n("Timed out waiting for playable audio")}),3e3)}))]).then((function(e){return e?e.setSinkId?Promise.resolve(e.setSinkId(t)):Promise.reject("Not supported"):Promise.reject("No audio found")})):e.Promise?Promise.reject("Not eligible ringtone owner"):void 0};var r=function(e){n.call(this,e)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.VOICE&&n.isSoftphoneCall()&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Ringtone Connecting",n),t.getLog().info("Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)})),(new t.Agent).getContacts().forEach((function(e){e.getStatus().type===t.ContactStatusType.CONNECTING&&n(e)}))};var o=function(e){n.call(this,e)};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.CHAT&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Chat Ringtone Connecting",n),t.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var i=function(e){n.call(this,e)};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.TASK&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Task Ringtone Connecting",n),t.getLog().info("Task Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var s=function(e){n.call(this,e)};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype._driveRingtone=function(){var e=this;t.contact((function(n){n.onIncoming((function(){n.getType()===lily.ContactType.QUEUE_CALLBACK&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Callback Ringtone Connecting",n),t.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer())}))}))},t.VoiceRingtoneEngine=r,t.ChatRingtoneEngine=o,t.TaskRingtoneEngine=i,t.QueueCallbackRingtoneEngine=s}()},642:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,e.ccpVersion="V2";var n={};n[t.SoftphoneCallType.AUDIO_ONLY]="Audio",n[t.SoftphoneCallType.VIDEO_ONLY]="Video",n[t.SoftphoneCallType.AUDIO_VIDEO]="AudioVideo",n[t.SoftphoneCallType.NONE]="None";var r="audio_input",o="audio_output";({})[t.ContactType.VOICE]="Voice";var i=[],s={},a={},c=null,u=null,l=null,p=t.SoftphoneErrorTypes,d={},h=t.randomId(),f=function(e){return new Promise((function(n,r){t.core.getClient().call(t.ClientMethods.CREATE_TRANSPORT,e,{success:function(e){n(e.softphoneTransport.softphoneMediaConnections)},failure:function(e){e.message&&e.message.includes("SoftphoneConnectionLimitBreachedException")&&w("multiple_softphone_active_sessions","Number of active sessions are more then allowed limit.",""),r(Error("requestIceAccess failed"))},authFailure:function(){r(Error("Authentication failed while requestIceAccess"))},accessDenied:function(){r(Error("Access Denied while requestIceAccess"))}})}))},g=function(e){var n=t.core.getUpstream(),r=e.getAgentConnection();if(r){var o=r.getSoftphoneMediaInfo();o?!0===o.autoAccept?(l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(),n.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(e.contactId)}),n.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,e.contactId),data:new t.Contact(e.contactId)})):l.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer():l.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer()}else l.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer()},m=function(){t.core.getEventBus().subscribe(t.EventType.MUTE,b)},v=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_SPEAKER_DEVICE,C)},y=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_MICROPHONE_DEVICE,T)},E=function(){try{t.isChromeBrowser()&&t.getChromeBrowserVersion()>43&&navigator.permissions.query({name:"microphone"}).then((function(e){e.onchange=function(){l.info("Microphone Permission: "+e.state),k("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:e.state}),"denied"===e.state&&w(p.MICROPHONE_NOT_SHARED,"Your microphone is not enabled in your browser. ","")}}))}catch(e){l.error("Failed in detecting microphone permission status: "+e)}},S=function(e){delete d[e],t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:!1}})},b=function(e){var n;if(0!==t.keys(d).length){for(var r in e&&void 0!==e.mute&&(n=e.mute),d)if(d.hasOwnProperty(r)){var o=d[r].stream;if(o){var i=o.getAudioTracks()[0];void 0!==n?(i.enabled=!n,d[r].muted=n,n?l.info("Agent has muted the contact, connectionId - "+r).sendInternalLogToServer():l.info("Agent has unmuted the contact, connectionId - "+r).sendInternalLogToServer()):n=d[r].muted||!1}}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:n}})}},C=function(e){if(0!==t.keys(d).length&&e&&e.deviceId){var n=e.deviceId,r=document.getElementById("remote-audio");try{l.info("Trying to set speaker to device "+n),r&&"function"==typeof r.setSinkId&&r.setSinkId(n)}catch(e){l.error("Failed to set speaker to device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,data:{deviceId:n}})}},T=function(e){if(0!==t.keys(d).length&&e&&e.deviceId){var n=e.deviceId,r=t.core.getSoftphoneManager();try{navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:n}}}).then((function(e){var t=e.getAudioTracks()[0];for(var n in d)d.hasOwnProperty(n)&&(d[n].stream,r.getSession(n)._pc.getSenders()[0].replaceTrack(t).then((function(){r.replaceLocalMediaTrack(n,t)})))}))}catch(e){l.error("Failed to set microphone device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,data:{deviceId:n}})}},I=function(e,n){if(n===t.RTCErrors.ICE_COLLECTION_TIMEOUT){for(var r="\n",o=0;o0?t.success(e):t.failure(p.MICROPHONE_NOT_SHARED)}),(function(e){t.failure(p.MICROPHONE_NOT_SHARED)})),r}t.failure(p.UNSUPPORTED_BROWSER)},w=function(e,n,r){l.error("Softphone error occurred : ",e,n||"").sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.SOFTPHONE_ERROR,data:new t.SoftphoneError(e,n,r)})},R=function(e,t){k("Softphone Session Failed",e,{failedReason:t})},k=function(e,n,r){t.publishMetric({name:e,contactId:n,data:r})},N=function(e,t,n){k(e,t,[{name:"AgentConnectionId",value:n}]),l.info("Publish multiple session error metrics",e,"contactId "+t,"agent connectionId "+n).sendInternalLogToServer()},O=function(){return!!(t.isOperaBrowser()&&t.getOperaBrowserVersion()>17)||!!(t.isChromeBrowser()&&t.getChromeBrowserVersion()>22)||!!(t.isFirefoxBrowser()&&t.getFirefoxBrowserVersion()>21)},L=function(e){var t=i.slice();i=[],t.length>0&&e.sendSoftphoneMetrics(t,{success:function(){l.info("sendSoftphoneMetrics success"+JSON.stringify(t)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneMetrics failed.").withObject(e).sendInternalLogToServer()}})},D=function(e){c=window.setInterval((function(){e.getUserAudioStats().then((function(e){var t=s;s=e,i.push(M(s,t,r))}),(function(e){l.debug("Failed to get user audio stats.",e).sendInternalLogToServer()})),e.getRemoteAudioStats().then((function(e){var t=a;a=e,i.push(M(a,t,o))}),(function(e){l.debug("Failed to get remote audio stats.",e).sendInternalLogToServer()}))}),1e3)},P=function(e){u=window.setInterval((function(){L(e)}),3e4)},x=function(){s=null,a=null,i=[],c=null,u=null},M=function(e,t,n){if(t&&e){var r=e.packetsLost>t.packetsLost?e.packetsLost-t.packetsLost:0,o=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new q(e.timestamp,r,o,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new q(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},U=function(e){return null!==e&&window.clearInterval(e),null},F=function(e,t){c=U(c),u=U(u),function(e,t,n,i){t.streamStats=[j(n,r),j(i,o)];var s={callStartTime:t.sessionStartTime,callEndTime:t.sessionEndTime,gumTimeMillis:t.gumTimeMillis,initializationTimeMillis:t.initializationTimeMillis,iceCollectionTimeMillis:t.iceCollectionTimeMillis,signallingConnectTimeMillis:t.signallingConnectTimeMillis,handshakingTimeMillis:t.handshakingTimeMillis,preTalkingTimeMillis:t.preTalkingTimeMillis,talkingTimeMillis:t.talkingTimeMillis,cleanupTimeMillis:t.cleanupTimeMillis,iceCollectionFailure:t.iceCollectionFailure,signallingConnectionFailure:t.signallingConnectionFailure,handshakingFailure:t.handshakingFailure,gumOtherFailure:t.gumOtherFailure,gumTimeoutFailure:t.gumTimeoutFailure,createOfferFailure:t.createOfferFailure,setLocalDescriptionFailure:t.setLocalDescriptionFailure,userBusyFailure:t.userBusyFailure,invalidRemoteSDPFailure:t.invalidRemoteSDPFailure,noRemoteIceCandidateFailure:t.noRemoteIceCandidateFailure,setRemoteDescriptionFailure:t.setRemoteDescriptionFailure,softphoneStreamStatistics:t.streamStats};e.sendSoftphoneReport(s,{success:function(){l.info("sendSoftphoneReport success"+JSON.stringify(s)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneReport failed.").withObject(e).sendInternalLogToServer()}})}(e,t,j(s,r),j(a,o)),L(e)},q=function(e,t,n,r,o,i,s){this.softphoneStreamType=r,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=o,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},j=function(e,t){return new q((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},B=function(e){this._originalLogger=e;var n=this;this._tee=function(e,r){return function(){var e=Array.prototype.slice.call(arguments[0]),o="";return e.forEach((function(){o+=" %s"})),r.apply(n._originalLogger,[t.LogComponent.SOFTPHONE,o].concat(e))}}};B.prototype.debug=function(){return this._tee(1,this._originalLogger.debug)(arguments)},B.prototype.info=function(){return this._tee(2,this._originalLogger.info)(arguments)},B.prototype.log=function(){return this._tee(3,this._originalLogger.log)(arguments)},B.prototype.warn=function(){return this._tee(4,this._originalLogger.warn)(arguments)},B.prototype.error=function(){return this._tee(5,this._originalLogger.error)(arguments)},t.SoftphoneManager=function(e){var n,r=this;(l=new B(t.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),t.RtcPeerConnectionFactory&&(n=new t.RtcPeerConnectionFactory(l,t.core.getWebSocketManager(),h,t.hitch(r,f,{transportType:"softphone",softphoneClientId:h}),t.hitch(r,w))),O()||w(p.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ",""),A({success:function(e){k("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"granted"})},failure:function(e){w(e,"Your microphone is not enabled in your browser. ",""),k("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"denied"})}}),m(),v(),y(),E(),this.ringtoneEngine=null;var o={},i={};this.onInitContactSub={},this.onInitContactSub.unsubscribe=function(){};var s=!1,a=null,c=null,u=function(){s=!1,a=null,c=null};this.getSession=function(e){return o[e]},this.replaceLocalMediaTrack=function(e,t){var n=d[e].stream;if(n){var r=n.getAudioTracks()[0];t.enabled=r.enabled,r.enabled=!1,n.removeTrack(r),n.addTrack(t)}};var b=function(e){if(o.hasOwnProperty(e)){var t=o[e];new Promise((function(n,r){delete o[e],delete i[e],t.hangup()})).catch((function(t){lily.getLog().warn("Clean up the session locally "+e,t.message).sendInternalLogToServer()}))}};this.startSession=function(e,r){var p=s?a:e,h=s?c:r;if(p&&h){u(),i[h]=!0,l.info("Softphone call detected:","contactId "+p.getContactId(),"agent connectionId "+h).sendInternalLogToServer(),function(e){if(Object.keys(e).length>0){for(var t in e)e.hasOwnProperty(t)&&(N("MultiSessionHangUp",e[t].callId,t),b(t));throw new Error("duplicate session detected, refusing to setup new connection")}}(o),p.getStatus().type===t.ContactStatusType.CONNECTING&&k("Softphone Connecting",p.getContactId()),x();var f,m=p.getAgentConnection().getSoftphoneMediaInfo(),v=_(m.callConfigJson);v.useWebSocketProvider&&(f=t.core.getWebSocketManager());var y=new t.RTCSession(v.signalingEndpoint,v.iceServers,m.callContextToken,l,p.getContactId(),h,f);o[h]=y,t.core.getSoftphoneUserMediaStream()&&(y.mediaStream=t.core.getSoftphoneUserMediaStream()),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConnectionEvents.SESSION_INIT,data:{connectionId:h}}),y.onSessionFailed=function(e,t){delete o[h],delete i[h],I(e,t),R(p.getContactId(),t),F(p,e.sessionReport)},y.onSessionConnected=function(e){k("Softphone Session Connected",p.getContactId()),t.becomeMaster(t.MasterTopics.SEND_LOGS),D(e),P(p),g(p)},y.onSessionCompleted=function(e){k("Softphone Session Completed",p.getContactId()),delete o[h],delete i[h],F(p,e.sessionReport),S(h)},y.onLocalStreamAdded=function(e,n){d[h]={stream:n},t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,data:{connectionId:h}})},y.remoteAudioElement=document.getElementById("remote-audio"),n?y.connect(n.get(v.iceServers)):y.connect()}};var C=function(e,n){o[n]&&function(e){return e.getStatus().type===t.ContactStatusType.ENDED||e.getStatus().type===t.ContactStatusType.ERROR||e.getStatus().type===t.ContactStatusType.MISSED}(e)&&(b(n),u()),!e.isSoftphoneCall()||i[n]||e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING||(t.isFirefoxBrowser()&&t.hasOtherConnectedCCPs()?function(e,t){s=!0,a=e,c=t}(e,n):r.startSession(e,n))},T=function(e){var t=e.getAgentConnection().connectionId;l.info("Contact detected:","contactId "+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),i[t]||e.onRefresh((function(){C(e,t)}))};r.onInitContactSub=t.contact(T),(new t.Agent).getContacts().forEach((function(e){var t=e.getAgentConnection().connectionId;l.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId"+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),T(e),C(e,t)}))}}()},944:()=>{!function(){var e=this||globalThis,t=function(){return t.cache.hasOwnProperty(arguments[0])||(t.cache[arguments[0]]=t.parse(arguments[0])),t.format.call(null,t.cache[arguments[0]],arguments)};function n(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function r(e,t){for(var n=[];t>0;n[--t]=e);return n.join("")}t.format=function(e,o){var i,s,a,c,u,l,p,d=1,h=e.length,f="",g=[];for(s=0;s>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}i=/[def]/.test(c[8])&&c[3]&&i>=0?"+"+i:i,l=c[4]?"0"==c[4]?"0":c[4].charAt(1):" ",p=c[6]-String(i).length,u=c[6]?r(l,p):"",g.push(c[5]?i+u:u+i)}return g.join("")},t.cache={},t.parse=function(e){for(var t=e,n=[],r=[],o=0;t;){if(null!==(n=/^[^\x25]+/.exec(t)))r.push(n[0]);else if(null!==(n=/^\x25{2}/.exec(t)))r.push("%");else{if(null===(n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t)))throw"[sprintf] huh?";if(n[2]){o|=1;var i=[],s=n[2],a=[];if(null===(a=/^([a-z_][a-z_\d]*)/i.exec(s)))throw"[sprintf] huh?";for(i.push(a[1]);""!==(s=s.substring(a[0].length));)if(null!==(a=/^\.([a-z_][a-z_\d]*)/i.exec(s)))i.push(a[1]);else{if(null===(a=/^\[(\d+)\]/.exec(s)))throw"[sprintf] huh?";i.push(a[1])}n[2]=i}else o|=2;if(3===o)throw"[sprintf] mixing positional and named placeholders is not (yet) supported";r.push(n)}t=t.substring(n[0].length)}return r},e.sprintf=t,e.vsprintf=function(e,n,r){return(r=n.slice(0)).splice(0,0,e),t.apply(null,r)}}()},82:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t;var n=function(){};n.prototype.send=function(e){throw new t.NotImplementedError},n.prototype.onMessage=function(e){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.onMessage=function(e){},r.prototype.send=function(e){};var o=function(e,t){n.call(this),this.window=e,this.domain=t||"*"};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.send=function(e){this.window.postMessage(e,this.domain)},o.prototype.onMessage=function(e){this.window.addEventListener("message",e)};var i=function(e,t,r){n.call(this),this.input=e,this.output=t,this.domain=r||"*"};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype.send=function(e){this.output.postMessage(e,this.domain)},i.prototype.onMessage=function(e){this.input.addEventListener("message",(t=>{t.source===this.output&&e(t)}))};var s=function(e){n.call(this),this.port=e,this.id=t.randomId()};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype.send=function(e){this.port.postMessage(e)},s.prototype.onMessage=function(e){this.port.addEventListener("message",e)},s.prototype.getId=function(){return this.id};var a=function(e){n.call(this),this.streamMap=e?t.index(e,(function(e){return e.getId()})):{},this.messageListeners=[]};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype.send=function(e){this.getStreams().forEach((function(t){try{t.send(e)}catch(e){}}))},a.prototype.onMessage=function(e){this.messageListeners.push(e),this.getStreams().forEach((function(t){t.onMessage(e)}))},a.prototype.addStream=function(e){this.streamMap[e.getId()]=e,this.messageListeners.forEach((function(t){e.onMessage(t)}))},a.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},a.prototype.getStreams=function(e){return t.values(this.streamMap)},a.prototype.getStreamForPort=function(e){return t.find(this.getStreams(),(function(t){return t.port===e}))};var c=function(e,n,o){this.name=e,this.upstream=n||new r,this.downstream=o||new r,this.downstreamBus=new t.EventBus,this.upstreamBus=new t.EventBus,this.upstream.onMessage(t.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(t.hitch(this,this._dispatchEvent,this.downstreamBus))};c.prototype.onUpstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.upstreamBus.subscribe(e,n)},c.prototype.onAllUpstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},c.prototype.onDownstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.downstreamBus.subscribe(e,n)},c.prototype.onAllDownstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},c.prototype.sendUpstream=function(e,n){t.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:n})},c.prototype.sendDownstream=function(e,n){t.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:n})},c.prototype._dispatchEvent=function(e,t){var n=t.data;n.event&&e.trigger(n.event,n.data)},c.prototype.passUpstream=function(){var e=this;return function(t,n){e.upstream.send({event:n,data:t})}},c.prototype.passDownstream=function(){var e=this;return function(t,n){e.downstream.send({event:n,data:t})}},c.prototype.shutdown=function(){this.upstreamBus.unsubscribeAll(),this.downstreamBus.unsubscribeAll()};var u=function(e,t,n,r){c.call(this,e,new i(t,n.contentWindow,r||"*"),null)};(u.prototype=Object.create(c.prototype)).constructor=u,t.Stream=n,t.NullStream=r,t.WindowStream=o,t.WindowIOStream=i,t.PortStream=s,t.StreamMultiplexer=a,t.Conduit=c,t.IFrameConduit=u}()},833:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t;var n=function(e,n){t.assertNotNull(e,"fromState"),t.assertNotNull(n,"toState"),this.fromState=e,this.toState=n};n.prototype.getAssociations=function(e){throw t.NotImplementedError()},n.prototype.getFromState=function(){return this.fromState},n.prototype.getToState=function(){return this.toState};var r=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"associations"),n.call(this,e,r),this.associations=o};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.getAssociations=function(e){return this.associations};var o=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"closure"),t.assertTrue(t.isFunction(o),"closure must be a function"),n.call(this,e,r),this.closure=o};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};var i=function(){this.fromMap={}};i.ANY="<>",i.prototype.assoc=function(e,t,n){var i=this;if(!e)throw new Error("fromStateObj is not defined.");if(!t)throw new Error("toStateObj is not defined.");if(!n)throw new Error("assocObj is not defined.");return e instanceof Array?e.forEach((function(e){i.assoc(e,t,n)})):t instanceof Array?t.forEach((function(t){i.assoc(e,t,n)})):"function"==typeof n?this._addAssociation(new o(e,t,n)):n instanceof Array?this._addAssociation(new r(e,t,n)):this._addAssociation(new r(e,t,[n])),this},i.prototype.getAssociations=function(e,n,r){t.assertNotNull(n,"fromState"),t.assertNotNull(r,"toState");var o=[],s=this.fromMap[i.ANY]||{},a=this.fromMap[n]||{};return o=(o=o.concat(this._getAssociationsFromMap(s,e,n,r))).concat(this._getAssociationsFromMap(a,e,n,r))},i.prototype._addAssociation=function(e){var t=this.fromMap[e.getFromState()];t||(t=this.fromMap[e.getFromState()]={});var n=t[e.getToState()];n||(n=t[e.getToState()]=[]),n.push(e)},i.prototype._getAssociationsFromMap=function(e,t,n,r){return(e[i.ANY]||[]).concat(e[r]||[]).reduce((function(e,n){return e.concat(n.getAssociations(t))}),[])},t.EventGraph=i}()},891:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t;var n=navigator.userAgent,r=["bubbles","cancelBubble","cancelable","composed","data","defaultPrevented","eventPhase","isTrusted","lastEventId","origin","returnValue","timeStamp","type"];t.sprintf=e.sprintf,t.vsprintf=e.vsprintf,delete e.sprintf,delete e.vsprintf,t.HTTP_STATUS_CODES={SUCCESS:200,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},t.TRANSPORT_TYPES={CHAT_TOKEN:"chat_token",WEB_SOCKET:"web_socket"},t.hitch=function(){var e=Array.prototype.slice.call(arguments),n=e.shift(),r=e.shift();return t.assertNotNull(n,"scope"),t.assertNotNull(r,"method"),t.assertTrue(t.isFunction(r),"method must be a function"),function(){var t=Array.prototype.slice.call(arguments);return r.apply(n,e.concat(t))}},t.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},t.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},t.keys=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(r);return n},t.values=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(e[r]);return n},t.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},t.merge=function(){var e=Array.prototype.slice.call(arguments,0),n={};return e.forEach((function(e){t.entries(e).forEach((function(e){n[e.key]=e.value}))})),n},t.now=function(){return(new Date).getTime()},t.find=function(e,t){for(var n=0;n{try{n[r]=e[r]}catch(e){t.getLog().info("deepcopyCrossOriginEvent failed on key: ",r).sendInternalLogToServer()}})),t.deepcopy(n)},t.getBaseUrl=function(){var n=e.location;return t.sprintf("%s//%s:%s",n.protocol,n.hostname,n.port)},t.getUrlWithProtocol=function(n){var r=e.location.protocol;return n.substr(0,r.length)!==r?t.sprintf("%s//%s",r,n):n},t.isFramed=function(){try{return window.self!==window.top}catch(e){return!0}},t.hasOtherConnectedCCPs=function(){return t.numberOfConnectedCCPs>1},t.fetch=function(e,n,r,o){return o=o||5,r=r||1e3,n=n||{},new Promise((function(i,s){!function o(a){fetch(e,n).then((function(e){e.status===t.HTTP_STATUS_CODES.SUCCESS?e.json().then((e=>i(e))).catch((()=>i({}))):1!==a&&(e.status>=t.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===t.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout((function(){o(--a)}),r):s(e)})).catch((function(e){s(e)}))}(o)}))},t.backoff=function(n,r,o,i){t.assertTrue(t.isFunction(n),"func must be a Function");var s=this;n({success:function(e){i&&i.success&&i.success(e)},failure:function(t,a){if(o>0){var c=2*r*Math.random();e.setTimeout((function(){s.backoff(n,2*c,--o,i)}),c)}else i&&i.failure&&i.failure(t,a)}})},t.publishMetric=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.CLIENT_METRIC,data:e})},t.publishSoftphoneStats=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_STATS,data:e})},t.publishSoftphoneReport=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_REPORT,data:e})},t.publishClickStreamData=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.CLICK_STREAM_DATA,data:e})},t.publishClientSideLogs=function(e){t.core.getEventBus().trigger(t.EventType.CLIENT_SIDE_LOGS,e)},t.addNamespaceToLogs=function(e){["log","error","warn","info","debug"].forEach((t=>{const n=window.console[t];window.console[t]=function(){const t=Array.from(arguments);t.unshift(`[${e}]`),n.apply(window.console,t)}}))},t.PopupManager=function(){},t.PopupManager.prototype.open=function(e,t,n){var r=this._getLastOpenedTimestamp(t),o=(new Date).getTime(),i=null;if(o-r>864e5){if(n){var s=n.height||578,a=n.width||433,c=n.top||0,u=n.left||0;(i=window.open("",t,"width="+a+", height="+s+", top="+c+", left="+u)).location!==e&&(i=window.open(e,t,"width="+a+", height="+s+", top="+c+", left="+u))}else(i=window.open("",t)).location!==e&&(i=window.open(e,t));this._setLastOpenedTimestamp(t,o)}return i},t.PopupManager.prototype.clear=function(t){var n=this._getLocalStorageKey(t);e.localStorage.removeItem(n)},t.PopupManager.prototype._getLastOpenedTimestamp=function(t){var n=this._getLocalStorageKey(t),r=e.localStorage.getItem(n);return r?parseInt(r,10):0},t.PopupManager.prototype._setLastOpenedTimestamp=function(t,n){var r=this._getLocalStorageKey(t);e.localStorage.setItem(r,""+n)},t.PopupManager.prototype._getLocalStorageKey=function(e){return"connectPopupManager::"+e};var o=t.makeEnum(["granted","denied","default"]);t.NotificationManager=function(){this.queue=[],this.permission=o.DEFAULT},t.NotificationManager.prototype.requestPermission=function(){var n=this;"Notification"in e?e.Notification.permission===o.DENIED?(t.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(),this.permission=o.DENIED):this.permission!==o.GRANTED&&e.Notification.requestPermission().then((function(e){n.permission=e,e===o.GRANTED?n._showQueued():n.queue=[]})):(t.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(),this.permission=o.DENIED)},t.NotificationManager.prototype.show=function(e,n){if(this.permission===o.GRANTED)return this._showImpl({title:e,options:n});if(this.permission===o.DENIED)t.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({title:e,options:n});else{var r={title:e,options:n};t.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(r).sendInternalLogToServer(),this.queue.push(r)}},t.NotificationManager.prototype._showQueued=function(){var e=this,t=this.queue.map((function(t){return e._showImpl(t)}));return this.queue=[],t},t.NotificationManager.prototype._showImpl=function(t){var n=new e.Notification(t.title,t.options);return t.options.clicked&&(n.onclick=function(){t.options.clicked.call(n)}),n},t.ValueError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift(),r=new Error(t.vsprintf(n,e));return Object.setPrototypeOf(r,t.ValueError.prototype),r},Object.setPrototypeOf(t.ValueError.prototype,Error.prototype),Object.setPrototypeOf(t.ValueError,Error),t.ValueError.prototype.name="ValueError",t.NotImplementedError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift(),r=new Error(t.vsprintf(n,e));return Object.setPrototypeOf(r,t.NotImplementedError.prototype),r},Object.setPrototypeOf(t.NotImplementedError.prototype,Error.prototype),Object.setPrototypeOf(t.NotImplementedError,Error),t.NotImplementedError.prototype.name="NotImplementedError",t.StateError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift(),r=new Error(t.vsprintf(n,e));return Object.setPrototypeOf(r,t.StateError.prototype),r},Object.setPrototypeOf(t.StateError.prototype,Error.prototype),Object.setPrototypeOf(t.StateError,Error),t.StateError.prototype.name="StateError",t.VoiceIdError=function(e,t,n){var r={};return r.type=e,r.message=t,r.stack=Error(t).stack,r.err=n,r},t.isCCP=function(){return"ConnectSharedWorkerConduit"===t.core.getUpstream().name}}()},736:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,t.worker={};var n=function(){this.topicMasterMap={}};n.prototype.getMaster=function(e){return t.assertNotNull(e,"topic"),this.topicMasterMap[e]||null},n.prototype.setMaster=function(e,n){t.assertNotNull(e,"topic"),t.assertNotNull(n,"id"),this.topicMasterMap[e]=n},n.prototype.removeMaster=function(e){t.assertNotNull(e,"id");var n=this;t.entries(this.topicMasterMap).filter((function(t){return t.value===e})).forEach((function(e){delete n.topicMasterMap[e.key]}))};var r=function(e){t.ClientBase.call(this),this.conduit=e};(r.prototype=Object.create(t.ClientBase.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){var o=this,i=(new Date).getTime();t.containsValue(t.AgentAppClientMethods,e)?t.core.getAgentAppClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.containsValue(t.TaskTemplatesClientMethods,e)?t.core.getTaskTemplatesClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.core.getClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t,n){o._recordAPILatency(e,i,t),r.failure(t,n)},authFailure:function(){o._recordAPILatency(e,i),r.authFailure()},accessDenied:function(){r.accessDenied&&r.accessDenied()}})},r.prototype._recordAPILatency=function(e,t,n){var r=(new Date).getTime()-t;this._sendAPIMetrics(e,r,n)},r.prototype._sendAPIMetrics=function(e,n,r){this.conduit.sendDownstream(t.EventType.API_METRIC,{name:e,time:n,dimensions:[{name:"Category",value:"API"}],error:r})};var o=function(){var o=this;this.multiplexer=new t.StreamMultiplexer,this.conduit=new t.Conduit("AmazonConnectSharedWorker",null,this.multiplexer),this.client=new r(this.conduit),this.timeout=null,this.agent=null,this.nextToken=null,this.initData={},this.portConduitMap={},this.streamMapByTabId={},this.masterCoord=new n,this.logsBuffer=[],this.suppress=!1,this.forceOffline=!1,this.longPollingOptions={allowLongPollingShadowMode:!1,allowLongPollingWebsocketOnlyMode:!1};var i=null;t.rootLogger=new t.DownstreamConduitLogger(this.conduit),this.conduit.onDownstream(t.EventType.SEND_LOGS,(function(e){t.getLog().pushLogsDownstream(e),o.logsBuffer=o.logsBuffer.concat(e),o.logsBuffer.length>400&&o.handleSendLogsRequest(o.logsBuffer)})),this.conduit.onDownstream(t.EventType.CONFIGURE,(function(n){n.authToken&&n.authToken!==o.initData.authToken&&(o.initData=n,t.core.init(n),n.longPollingOptions&&("boolean"==typeof n.longPollingOptions.allowLongPollingShadowMode&&(o.longPollingOptions.allowLongPollingShadowMode=n.longPollingOptions.allowLongPollingShadowMode),"boolean"==typeof n.longPollingOptions.allowLongPollingWebsocketOnlyMode&&(o.longPollingOptions.allowLongPollingWebsocketOnlyMode=n.longPollingOptions.allowLongPollingWebsocketOnlyMode)),i?t.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(t.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),t.WebSocketManager.setGlobalConfig({loggerConfig:{logger:t.getLog()}}),(i=t.WebSocketManager.create()).onInitFailure((function(){o.conduit.sendDownstream(t.WebSocketEvents.INIT_FAILURE)})),i.onConnectionOpen((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_OPEN,e)})),i.onConnectionClose((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_CLOSE,e)})),i.onConnectionGain((function(){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_GAIN)})),i.onConnectionLost((function(e){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_LOST,e)})),i.onSubscriptionUpdate((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,e)})),i.onSubscriptionFailure((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,e)})),i.onAllMessage((function(e){o.conduit.sendDownstream(t.WebSocketEvents.ALL_MESSAGE,e)})),o.conduit.onDownstream(t.WebSocketEvents.SEND,(function(e){i.sendMessage(e)})),o.conduit.onDownstream(t.WebSocketEvents.SUBSCRIBE,(function(e){i.subscribeTopics(e)})),i.init(t.hitch(o,o.getWebSocketUrl)).then((function(n){try{if(n&&!n.webSocketConnectionFailed)t.getLog().info("Kicking off agent polling").sendInternalLogToServer(),o.pollForAgent(),t.getLog().info("Kicking off config polling").sendInternalLogToServer(),o.pollForAgentConfiguration({repeatForever:!0}),t.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),e.setInterval(t.hitch(o,o.checkAuthToken),3e5);else if(!t.webSocketInitFailed){const e=t.WebSocketEvents.INIT_FAILURE;throw o.conduit.sendDownstream(e),t.webSocketInitFailed=!0,new Error(e)}}catch(e){t.getLog().error("WebSocket failed to initialize").withException(e).sendInternalLogToServer()}}))))})),this.conduit.onDownstream(t.EventType.TERMINATE,(function(){o.handleSendLogsRequest(o.logsBuffer),t.core.terminate(),o.conduit.sendDownstream(t.EventType.TERMINATED)})),this.conduit.onDownstream(t.EventType.SYNCHRONIZE,(function(){o.conduit.sendDownstream(t.EventType.ACKNOWLEDGE)})),this.conduit.onDownstream(t.EventType.BROADCAST,(function(e){o.conduit.sendDownstream(e.event,e.data)})),e.onconnect=function(e){var n=e.ports[0],r=new t.PortStream(n);o.multiplexer.addStream(r),n.start();var i=new t.Conduit(r.getId(),null,r);i.sendDownstream(t.EventType.ACKNOWLEDGE,{id:r.getId()}),o.portConduitMap[r.getId()]=i,o.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length}),null!==o.agent&&o.updateAgent(),i.onDownstream(t.EventType.API_REQUEST,t.hitch(o,o.handleAPIRequest,i)),i.onDownstream(t.EventType.MASTER_REQUEST,t.hitch(o,o.handleMasterRequest,i,r.getId())),i.onDownstream(t.EventType.RELOAD_AGENT_CONFIGURATION,t.hitch(o,o.pollForAgentConfiguration)),i.onDownstream(t.EventType.TAB_ID,t.hitch(o,o.handleTabIdEvent,r)),i.onDownstream(t.EventType.CLOSE,t.hitch(o,o.handleCloseEvent,r))}};o.prototype.pollForAgent=function(){var n=this,r=t.hitch(n,n.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:n.nextToken,timeout:3e4},{success:function(r){try{n.agent=n.agent||{},n.agent.snapshot=r.snapshot,n.agent.snapshot.localTimestamp=t.now(),n.agent.snapshot.skew=n.agent.snapshot.snapshotTimestamp-n.agent.snapshot.localTimestamp,n.nextToken=r.nextToken,t.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(r).sendInternalLogToServer(),n.updateAgent()}catch(e){t.getLog().error("Long poll failed to update agent.").withObject(r).withException(e).sendInternalLogToServer()}finally{e.setTimeout(t.hitch(n,n.pollForAgent),100)}},failure:function(r,o){try{t.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:r,data:o})}finally{e.setTimeout(t.hitch(n,n.pollForAgent),5e3)}},authFailure:function(){r()},accessDenied:t.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentConfiguration=function(n){var r=this,o=n||{},i=t.hitch(r,r.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(n){var i=n.configuration;r.pollForAgentPermissions(i),r.pollForAgentStates(i),r.pollForDialableCountryCodes(i),r.pollForRoutingProfileQueues(i),o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration,o),3e4)},failure:function(n,i){try{t.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:n,data:i})}finally{o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration),3e4,o)}},authFailure:function(){i()},accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentStates=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentStates(e,{states:(o.states||[]).concat(t.states),nextToken:t.nextToken,maxResults:o.maxResults}):(e.agentStates=(o.states||[]).concat(t.states),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentPermissions=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentPermissions(e,{permissions:(o.permissions||[]).concat(t.permissions),nextToken:t.nextToken,maxResults:o.maxResults}):(e.permissions=(o.permissions||[]).concat(t.permissions),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForDialableCountryCodes=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForDialableCountryCodes(e,{countryCodes:(o.countryCodes||[]).concat(t.countryCodes),nextToken:t.nextToken,maxResults:o.maxResults}):(e.dialableCountries=(o.countryCodes||[]).concat(t.countryCodes),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForRoutingProfileQueues=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:e.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForRoutingProfileQueues(e,{countryCodes:(o.queues||[]).concat(t.queues),nextToken:t.nextToken,maxResults:o.maxResults}):(e.routingProfile.queues=(o.queues||[]).concat(t.queues),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.handleAPIRequest=function(e,n){var r=this;this.client.call(n.method,n.params,{success:function(r){var o=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,r);e.sendDownstream(o.event,o)},failure:function(o,i){var s=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,i,JSON.stringify(o));e.sendDownstream(s.event,s),t.getLog().error("'%s' API request failed",n.method).withObject({request:r.filterAuthToken(n),response:s}).withException(o).sendInternalLogToServer()},authFailure:t.hitch(r,r.handleAuthFail,{authorize:!0})})},o.prototype.handleMasterRequest=function(e,n,r){var o=this.conduit,i=null;switch(r.method){case t.MasterMethods.BECOME_MASTER:var s=this.masterCoord.getMaster(r.params.topic),a=Boolean(s)&&s!==n;this.masterCoord.setMaster(r.params.topic,n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:n,takeOver:a,topic:r.params.topic}),a&&o.sendDownstream(i.event,i);break;case t.MasterMethods.CHECK_MASTER:(s=this.masterCoord.getMaster(r.params.topic))||r.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(r.params.topic,n),s=n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:s,isMaster:n===s,topic:r.params.topic});break;default:throw new Error("Unknown master method: "+r.method)}e.sendDownstream(i.event,i)},o.prototype.handleTabIdEvent=function(e,n){var r=this;try{let o=n.tabId,i=r.streamMapByTabId[o],s=e.getId(),a=Object.keys(r.streamMapByTabId).filter((e=>r.streamMapByTabId[e].length>0)).length;if(i&&i.length>0){if(!i.includes(s)){r.streamMapByTabId[o].push(s);let e={length:Object.keys(r.portConduitMap).length,tabId:o,streamsTabsAcrossBrowser:a};e[o]={length:i.length},r.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,e)}}else{r.streamMapByTabId[o]=[e.getId()];let n={length:Object.keys(r.portConduitMap).length,tabId:o,streamsTabsAcrossBrowser:a+1};n[o]={length:r.streamMapByTabId[o].length},r.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,n)}}catch(e){t.getLog().error("[Tab Ids] Issue updating connected CCPs within the same tab").withException(e).sendInternalLogToServer()}},o.prototype.handleCloseEvent=function(e){var n=this;n.multiplexer.removeStream(e),delete n.portConduitMap[e.getId()],n.masterCoord.removeMaster(e.getId());let r={length:Object.keys(n.portConduitMap).length},o=Object.keys(n.streamMapByTabId);try{let t=o.find((t=>n.streamMapByTabId[t].includes(e.getId())));if(t){let o=n.streamMapByTabId[t].findIndex((t=>e.getId()===t));n.streamMapByTabId[t].splice(o,1);let i=n.streamMapByTabId[t]?n.streamMapByTabId[t].length:0;r[t]={length:i},r.tabId=t}let i=o.filter((e=>n.streamMapByTabId[e].length>0)).length;r.streamsTabsAcrossBrowser=i}catch(e){t.getLog().error("[Tab Ids] Issue updating tabId-specific stream data").withException(e).sendInternalLogToServer()}n.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,r)},o.prototype.updateAgentConfiguration=function(e){e.permissions&&e.dialableCountries&&e.agentStates&&e.routingProfile.queues?(this.agent=this.agent||{},this.agent.configuration=e,this.updateAgent()):t.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer()},o.prototype.updateAgent=function(){this.agent?this.agent.snapshot?this.agent.configuration?(this.agent.snapshot.status=this.agent.state,this.agent.snapshot.contacts&&this.agent.snapshot.contacts.length>1&&this.agent.snapshot.contacts.sort((function(e,t){return e.state.timestamp.getTime()-t.state.timestamp.getTime()})),this.agent.snapshot.contacts.forEach((function(e){e.status=e.state,e.connections.forEach((function(e){e.address=e.endpoint}))})),this.agent.configuration.routingProfile.defaultOutboundQueue.queueId=this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN,this.agent.configuration.routingProfile.queues.forEach((function(e){e.queueId=e.queueARN})),this.agent.snapshot.contacts.forEach((function(e){void 0!==e.queue&&(e.queue.queueId=e.queue.queueARN)})),this.agent.configuration.routingProfile.routingProfileId=this.agent.configuration.routingProfile.routingProfileARN,this.conduit.sendDownstream(t.AgentEvents.UPDATE,this.agent)):t.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer()},o.prototype.getWebSocketUrl=function(){var e=this,n=t.core.getClient(),r=t.hitch(e,e.handleAuthFail),o=t.hitch(e,e.handleAccessDenied);return new Promise((function(e,i){n.call(t.ClientMethods.CREATE_TRANSPORT,{transportType:t.TRANSPORT_TYPES.WEB_SOCKET},{success:function(n){t.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(),e(n)},failure:function(e,n){t.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({err:e,data:n}),i({reason:"getWebSocketUrl failed",_debug:e})},authFailure:function(){t.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(),i(Error("Authentication failed while getting getWebSocketUrl")),r()},accessDenied:function(){t.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(),i(Error("Access Denied Failure while getting getWebSocketUrl")),o()}})}))},o.prototype.handleSendLogsRequest=function(){var e=this,n=[],r=e.logsBuffer.slice();e.logsBuffer=[],r.forEach((function(e){n.push({timestamp:e.time,component:e.component,message:e.text})})),this.client.call(t.ClientMethods.SEND_CLIENT_LOGS,{logEvents:n},{success:function(e){t.getLog().info("SendLogs request succeeded.").sendInternalLogToServer()},failure:function(e,n){t.getLog().error("SendLogs request failed.").withObject(n).withException(e).sendInternalLogToServer()},authFailure:t.hitch(e,e.handleAuthFail)})},o.prototype.handleAuthFail=function(e){e?this.conduit.sendDownstream(t.EventType.AUTH_FAIL,e):this.conduit.sendDownstream(t.EventType.AUTH_FAIL)},o.prototype.handleAccessDenied=function(){this.conduit.sendDownstream(t.EventType.ACCESS_DENIED)},o.prototype.checkAuthToken=function(){var e=this,n=new Date(e.initData.authTokenExpiration),r=(new Date).getTime();n.getTime() { (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -114,7 +114,7 @@ /***/ (() => { (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -197,7 +197,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -329,15 +329,6 @@ 'api', 'disconnect' ]); - - /*---------------------------------------------------------------- - * enum for ContactRecording Voice Track config - */ - connect.ContactRecordingVoiceTrackConfig = connect.makeEnum([ - 'ALL', - 'TO_AGENT', - 'FROM_AGENT' - ]); /*---------------------------------------------------------------- * enum ChannelType @@ -382,6 +373,15 @@ 'other' ]); + /*---------------------------------------------------------------- + * enum for ClickType + */ + connect.ClickType = connect.makeEnum([ + 'Accept', + 'Reject', + 'Hangup' + ]); + /*---------------------------------------------------------------- * enum for VoiceIdErrorTypes */ @@ -455,7 +455,7 @@ ]); /*---------------------------------------------------------------- - * enum for contact flow authentication decision + * enum for contact flow authentication decision */ connect.ContactFlowAuthenticationDecision = connect.makeEnum([ "Authenticated", @@ -479,7 +479,7 @@ ]); /*---------------------------------------------------------------- - * enum for VoiceId EnrollmentRequest Status + * enum for VoiceId EnrollmentRequest Status */ connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum([ "NOT_ENOUGH_SPEECH", @@ -511,8 +511,7 @@ */ connect.AgentPermissions = { OUTBOUND_CALL: 'outboundCall', - VOICE_ID: 'voiceId', - CONTACT_RECORDING: 'contactRecording' + VOICE_ID: 'voiceId' }; /*---------------------------------------------------------------- @@ -832,7 +831,7 @@ var queueArns = this.getAllQueueARNs(); for (let queueArn of queueArns) { const agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); - + if (agentIdMatch) { return agentIdMatch[1]; } @@ -1085,6 +1084,13 @@ var client = connect.core.getClient(); var self = this; var contactId = this.getContactId(); + + connect.publishClickStreamData({ + contactId: this.getContactId(), + clickType: connect.ClickType.ACCEPT, + clickTime: new Date().toISOString() + }); + client.call(connect.ClientMethods.ACCEPT_CONTACT, { contactId: contactId }, { @@ -1124,6 +1130,13 @@ Contact.prototype.reject = function (callbacks) { var client = connect.core.getClient(); + + connect.publishClickStreamData({ + contactId: this.getContactId(), + clickType: connect.ClickType.REJECT, + clickTime: new Date().toISOString() + }); + client.call(connect.ClientMethods.REJECT_CONTACT, { contactId: this.getContactId() }, callbacks); @@ -1331,6 +1344,12 @@ }; Connection.prototype.destroy = function (callbacks) { + connect.publishClickStreamData({ + contactId: this.getContactId(), + clickType: connect.ClickType.HANGUP, + clickTime: new Date().toISOString() + }); + var client = connect.core.getClient(); client.call(connect.ClientMethods.DESTROY_CONNECTION, { contactId: this.getContactId(), @@ -1373,157 +1392,29 @@ } } - // Method for checking whether this connection is an agent-side connection + // 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 + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; } /** - * Utility method for checking whether this connection is an agent-side connection + * 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 + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; } - - /*---------------------------------------------------------------- - * Contact recording - */ - - var ContactRecording = function (contactId) { - this.contactId = connect.core.getAgentDataProvider().getContactData(contactId) ? contactId : null; - } - - ContactRecording.prototype.startContactRecording = function(trackConfig) { - var self = this; - var client, contactData; - - client = connect.core.getClient(); - contactData = connect.core.getAgentDataProvider().getContactData(self.contactId); - var recordingTrack = (trackConfig && Object.values(connect.ContactRecordingVoiceTrackConfig).includes(trackConfig)) ? trackConfig : connect.ContactRecordingVoiceTrackConfig.ALL; - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.START_CONTACT_RECORDING, { - "initialContactId": contactData.initialContactId || self.contactId, - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId(), - "voiceRecordingConfiguration": { - "voiceRecordingTrack": recordingTrack - } - }, { - success: function (data) { - connect.getLog().info("startContactRecording succeeded") - .withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err, data) { - connect.getLog().error("startContactRecording failed").sendInternalLogToServer() - .withObject({ - err, - data - }); - reject(Error("startContactRecording failed", { cause: err })); - } - }) - }) - }; - - ContactRecording.prototype.stopContactRecording = function() { - var self = this; - var client, contactData; - - client = connect.core.getClient(); - contactData = connect.core.getAgentDataProvider().getContactData(self.contactId); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.STOP_CONTACT_RECORDING, { - "initialContactId": contactData.initialContactId || self.contactId, - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId() - }, { - success: function (data) { - connect.getLog().info("stopContactRecording succeeded") - .withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err, data) { - connect.getLog().error("stopContactRecording failed").sendInternalLogToServer() - .withObject({ - err, - data - }); - reject(Error("stopContactRecording failed", { cause: err })); - } - }) - }) - }; - - ContactRecording.prototype.suspendContactRecording = function() { - var self = this; - var client, contactData; - - client = connect.core.getClient(); - contactData = connect.core.getAgentDataProvider().getContactData(self.contactId); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.SUSPEND_CONTACT_RECORDING, { - "initialContactId": contactData.initialContactId || self.contactId, - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId() - }, { - success: function (data) { - connect.getLog().info("suspendContactRecording succeeded") - .withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err, data) { - connect.getLog().error("suspendContactRecording failed").sendInternalLogToServer() - .withObject({ - err, - data - }); - reject(Error("suspendContactRecording failed", { cause: err })); - } - }) - }) - }; - - ContactRecording.prototype.resumeContactRecording = function() { - var self = this; - var client, contactData; - - client = connect.core.getClient(); - contactData = connect.core.getAgentDataProvider().getContactData(self.contactId); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.RESUME_CONTACT_RECORDING, { - "initialContactId": contactData.initialContactId || self.contactId, - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId() - }, { - success: function (data) { - connect.getLog().info("resumeContactRecording succeeded") - .withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function (err, data) { - connect.getLog().error("resumeContactRecording failed").sendInternalLogToServer() - .withObject({ - err, - data - }); - reject(Error("resumeContactRecording failed"), { cause: err }); - } - }) - }) - }; /*---------------------------------------------------------------- * Voice authenticator VoiceId */ - + var VoiceId = function (contactId) { this.contactId = contactId; }; @@ -1549,7 +1440,7 @@ 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") @@ -1609,7 +1500,7 @@ }; // internal only - VoiceId.prototype._optOutSpeakerInLcms = function (speakerId) { + VoiceId.prototype._optOutSpeakerInLcms = function (speakerId, generatedSpeakerId) { var self = this; var client = connect.core.getClient(); return new Promise(function (resolve, reject) { @@ -1619,7 +1510,8 @@ "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), "VoiceIdResult": { - "SpeakerOptedOut": true + "SpeakerOptedOut": true, + "generatedSpeakerId": generatedSpeakerId } }, { success: function (data) { @@ -1651,7 +1543,7 @@ "DomainId" : domainId }, { success: function (data) { - self._optOutSpeakerInLcms(speakerId).catch(function(){}); + self._optOutSpeakerInLcms(speakerId, data.generatedSpeakerId).catch(function(){}); connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, @@ -1751,7 +1643,7 @@ self.checkConferenceCall(); var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var pollTimes = 0; + var pollTimes = 0; return new Promise(function (resolve, reject) { function evaluate() { self.getDomainId().then(function(domainId) { @@ -1775,7 +1667,7 @@ } // Resolve if both authentication and fraud detection are not enabled. - if(!self.isAuthEnabled(data.AuthenticationResult.Decision) && + if(!self.isAuthEnabled(data.AuthenticationResult.Decision) && !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); @@ -1798,7 +1690,7 @@ return; } - if(!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && + if(!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && self.isAuthEnabled(data.AuthenticationResult.Decision)) { switch (data.AuthenticationResult.Decision) { case connect.VoiceIdAuthenticationDecision.ACCEPT: @@ -1818,7 +1710,7 @@ } } - if(!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && + if(!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && self.isFraudEnabled(data.FraudDetectionResult.Decision)) { switch (data.FraudDetectionResult.Decision) { case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: @@ -1859,7 +1751,7 @@ break; default: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); - connect.getLog().error("evaluateSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); + connect.getLog().error("evaluateSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); } reject(error); } @@ -1868,7 +1760,7 @@ reject(err); }); } - + if(!startNew) { self.syncSpeakerId().then(function () { evaluate(); @@ -1877,7 +1769,7 @@ .withObject({err: err}).sendInternalLogToServer(); reject(err); }) - } else { + } else { self.startSession().then(function(data) { self.syncSpeakerId().then(function(data) { setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); @@ -2034,7 +1926,7 @@ }; // internal only - VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId) { + VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId, generatedSpeakerId) { var self = this; var client = connect.core.getClient(); return new Promise(function (resolve, reject) { @@ -2044,7 +1936,7 @@ "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), "VoiceIdResult": { - "generatedSpeakerId": speakerId + "generatedSpeakerId": generatedSpeakerId } }, { success: function (data) { @@ -2077,7 +1969,7 @@ }, { success: function (data) { connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); - self._updateSpeakerIdInLcms(speakerId) + self._updateSpeakerIdInLcms(speakerId, data.generatedSpeakerId) .then(function() { resolve(data); }) @@ -2096,7 +1988,7 @@ break; default: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); - connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: err }).sendInternalLogToServer(); + connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: err }).sendInternalLogToServer(); } reject(error); } @@ -2206,13 +2098,12 @@ /** * @class VoiceConnection - * @param {number} contactId - * @param {number} connectionId + * @param {number} contactId + * @param {number} connectionId * @description - Provides voice media specific operations */ var VoiceConnection = function (contactId, connectionId) { this._speakerAuthenticator = new VoiceId(contactId); - this._contactRecorder = new ContactRecording(contactId); Connection.call(this, contactId, connectionId); }; @@ -2221,7 +2112,7 @@ /** * @deprecated - * Please use getMediaInfo + * Please use getMediaInfo */ VoiceConnection.prototype.getSoftphoneMediaInfo = function () { return this._getData().softphoneMediaInfo; @@ -2248,7 +2139,7 @@ } VoiceConnection.prototype.optOutVoiceIdSpeaker = function() { - + return this._speakerAuthenticator.optOutSpeaker(); } @@ -2292,44 +2183,11 @@ }, callbacks); }; - VoiceConnection.prototype.startContactRecording = function() { - var self = this; - self.checkConferenceCall(); - return this._contactRecorder.startContactRecording(); - } - - VoiceConnection.prototype.stopContactRecording = function() { - var self = this; - self.checkConferenceCall(); - return this._contactRecorder.stopContactRecording(); - } - - VoiceConnection.prototype.suspendContactRecording = function() { - var self = this; - self.checkConferenceCall(); - return this._contactRecorder.suspendContactRecording(); - } - - VoiceConnection.prototype.resumeContactRecording = function() { - var self = this; - self.checkConferenceCall(); - return this._contactRecorder.resumeContactRecording(); - } - - VoiceConnection.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 and Contact Recording are not supported for conference calls"); - } - } /** * @class ChatConnection - * @param {*} contactId - * @param {*} connectionId + * @param {*} contactId + * @param {*} connectionId * @description adds the chat media specific functionality */ var ChatConnection = function (contactId, connectionId) { @@ -2370,7 +2228,7 @@ }; /** - * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. + * 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() @@ -2420,8 +2278,8 @@ /** * @class TaskConnection - * @param {*} contactId - * @param {*} connectionId + * @param {*} contactId + * @param {*} connectionId * @description adds the task media specific functionality */ var TaskConnection = function (contactId, connectionId) { @@ -2618,7 +2476,6 @@ connect.Address = Endpoint; connect.SoftphoneError = SoftphoneError; connect.VoiceId = VoiceId; - connect.ContactRecording = ContactRecording; })(); @@ -2628,7 +2485,7 @@ /***/ 827: /***/ ((module, exports, __webpack_require__) => { -var __WEBPACK_AMD_DEFINE_RESULT__;// AWS SDK for JavaScript v2.553.0 +var __WEBPACK_AMD_DEFINE_RESULT__;// AWS SDK for JavaScript v2.1189.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= 0) { + return configValue.toLowerCase(); + } else { + throw AWS.util.error(new Error(), errorOptions); + } +} + +/** + * Resolve the configuration value for regional endpoint from difference sources: client + * config, environmental variable, shared config file. Value can be case-insensitive + * 'legacy' or 'reginal'. + * @param originalConfig user-supplied config object to resolve + * @param options a map of config property names from individual configuration source + * - env: name of environmental variable that refers to the config + * - sharedConfig: name of shared configuration file property that refers to the config + * - clientConfig: name of client configuration property that refers to the config + * + * @api private + */ +function resolveRegionalEndpointsFlag(originalConfig, options) { + originalConfig = originalConfig || {}; + //validate config value + var resolved; + if (originalConfig[options.clientConfig]) { + resolved = validateRegionalEndpointsFlagValue(originalConfig[options.clientConfig], { + code: 'InvalidConfiguration', + message: 'invalid "' + options.clientConfig + '" configuration. Expect "legacy" ' + + ' or "regional". Got "' + originalConfig[options.clientConfig] + '".' + }); + if (resolved) return resolved; + } + if (!AWS.util.isNode()) return resolved; + //validate environmental variable + if (Object.prototype.hasOwnProperty.call(process.env, options.env)) { + var envFlag = process.env[options.env]; + resolved = validateRegionalEndpointsFlagValue(envFlag, { + code: 'InvalidEnvironmentalVariable', + message: 'invalid ' + options.env + ' environmental variable. Expect "legacy" ' + + ' or "regional". Got "' + process.env[options.env] + '".' + }); + if (resolved) return resolved; + } + //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, options.sharedConfig)) { + var fileFlag = profile[options.sharedConfig]; + resolved = validateRegionalEndpointsFlagValue(fileFlag, { + code: 'InvalidConfiguration', + message: 'invalid ' + options.sharedConfig + ' profile config. Expect "legacy" ' + + ' or "regional". Got "' + profile[options.sharedConfig] + '".' + }); + if (resolved) return resolved; + } + return resolved; +} + +module.exports = resolveRegionalEndpointsFlag; + +}).call(this)}).call(this,require('_process')) +},{"./core":19,"_process":90}],19:[function(require,module,exports){ /** * The main AWS namespace */ @@ -6962,7 +7470,7 @@ AWS.util.update(AWS, { /** * @constant */ - VERSION: '2.553.0', + VERSION: '2.1189.0', /** * @api private @@ -7050,7 +7558,7 @@ 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){ +},{"../vendor/endpoint-cache":109,"./api_loader":9,"./config":17,"./event_listeners":34,"./http":35,"./json/builder":37,"./json/parser":38,"./model/api":39,"./model/operation":41,"./model/paginator":42,"./model/resource_waiter":43,"./model/shape":44,"./param_validator":45,"./protocol/json":47,"./protocol/query":48,"./protocol/rest":49,"./protocol/rest_json":50,"./protocol/rest_xml":51,"./request":57,"./resource_waiter":58,"./response":59,"./sequential_executor":60,"./service":61,"./signers/request_signer":64,"./util":72,"./xml/builder":74}],20:[function(require,module,exports){ var AWS = require('./core'); /** @@ -7298,7 +7806,7 @@ AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() { AWS.util.addPromises(AWS.Credentials); -},{"./core":18}],20:[function(require,module,exports){ +},{"./core":19}],21:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -7500,7 +8008,7 @@ AWS.ChainableTemporaryCredentials = AWS.util.inherit(AWS.Credentials, { } }); -},{"../../clients/sts":8,"../core":18}],21:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],22:[function(require,module,exports){ var AWS = require('../core'); var CognitoIdentity = require('../../clients/cognitoidentity'); var STS = require('../../clients/sts'); @@ -7887,7 +8395,7 @@ AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, { })() }); -},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(require,module,exports){ +},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":19}],23:[function(require,module,exports){ var AWS = require('../core'); /** @@ -8042,6 +8550,7 @@ AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, { * AWS.CredentialProviderChain.defaultProviders = [ * function () { return new AWS.EnvironmentCredentials('AWS'); }, * function () { return new AWS.EnvironmentCredentials('AMAZON'); }, + * function () { return new AWS.SsoCredentials(); }, * function () { return new AWS.SharedIniFileCredentials(); }, * function () { return new AWS.ECSCredentials(); }, * function () { return new AWS.ProcessCredentials(); }, @@ -8068,7 +8577,7 @@ AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFro AWS.util.addPromises(AWS.CredentialProviderChain); -},{"../core":18}],23:[function(require,module,exports){ +},{"../core":19}],24:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -8164,7 +8673,7 @@ AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, { }); -},{"../../clients/sts":8,"../core":18}],24:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],25:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -8295,7 +8804,7 @@ AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, { }); -},{"../../clients/sts":8,"../core":18}],25:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],26:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -8412,7 +8921,7 @@ AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, { }); -},{"../../clients/sts":8,"../core":18}],26:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],27:[function(require,module,exports){ (function (process){(function (){ var AWS = require('./core'); var util = require('./util'); @@ -8583,19 +9092,14 @@ function requiredDiscoverEndpoint(request, done) { }]); 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); + request.response.error = util.error(err, { retryable: false }); 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.request.response.error = util.error(err, { retryable: false }); requestContext.callback(); }); delete requestQueue[cacheKeyStr]; @@ -8680,23 +9184,28 @@ function isFalsy(value) { } /** - * If endpoint discovery should perform for this request when endpoint discovery is optional. + * If endpoint discovery should perform for this request when no operation requires endpoint + * discovery for the given service. * 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. + * 1. If set in client configuration. + * 2. If set in env AWS_ENABLE_ENDPOINT_DISCOVERY. + * 3. If set in shared ini config file with key 'endpoint_discovery_enabled'. * @param [object] request request object. + * @returns [boolean|undefined] if endpoint discovery config is not set in any source, this + * function returns undefined * @api private */ -function isEndpointDiscoveryApplicable(request) { +function resolveEndpointDiscoveryConfig(request) { var service = request.service || {}; - if (service.config.endpointDiscoveryEnabled === true) return true; + if (service.config.endpointDiscoveryEnabled !== undefined) { + return service.config.endpointDiscoveryEnabled; + } //shared ini file is only available in Node //not to check env in browser - if (util.isBrowser()) return false; + if (util.isBrowser()) return undefined; + // If any of recognized endpoint discovery config env is set for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) { var env = endpointDiscoveryEnabledEnvs[i]; if (Object.prototype.hasOwnProperty.call(process.env, env)) { @@ -8706,7 +9215,7 @@ function isEndpointDiscoveryApplicable(request) { message: 'environmental variable ' + env + ' cannot be set to nothing' }); } - if (!isFalsy(process.env[env])) return true; + return !isFalsy(process.env[env]); } } @@ -8727,9 +9236,9 @@ function isEndpointDiscoveryApplicable(request) { message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing' }); } - if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true; + return !isFalsy(sharedFileConfig.endpoint_discovery_enabled); } - return false; + return undefined; } /** @@ -8741,20 +9250,38 @@ 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'; + var isEnabled = resolveEndpointDiscoveryConfig(request); + var hasRequiredEndpointDiscovery = service.api.hasRequiredEndpointDiscovery; + if (isEnabled || hasRequiredEndpointDiscovery) { + // Once a customer enables endpoint discovery, the SDK should start appending + // the string endpoint-discovery to the user-agent on all requests. + request.httpRequest.appendToUserAgent('endpoint-discovery'); + } switch (isEndpointDiscoveryRequired) { case 'OPTIONAL': - optionalDiscoverEndpoint(request); - request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); + if (isEnabled || hasRequiredEndpointDiscovery) { + // For a given service; if at least one operation requires endpoint discovery then the SDK must enable endpoint discovery + // by default for all operations of that service, including operations where endpoint discovery is optional. + optionalDiscoverEndpoint(request); + request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); + } done(); break; case 'REQUIRED': + if (isEnabled === false) { + // For a given operation; if endpoint discovery is required and it has been disabled on the SDK client, + // then the SDK must return a clear and actionable exception. + request.response.error = util.error(new Error(), { + code: 'ConfigurationException', + message: 'Endpoint Discovery is disabled but ' + service.api.className + '.' + request.operation + + '() requires it. Please check your configurations.' + }); + done(); + break; + } request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); requiredDiscoverEndpoint(request, done); break; @@ -8775,7 +9302,7 @@ module.exports = { }; }).call(this)}).call(this,require('_process')) -},{"./core":18,"./util":71,"_process":86}],27:[function(require,module,exports){ +},{"./core":19,"./util":72,"_process":90}],28:[function(require,module,exports){ var eventMessageChunker = require('../event-stream/event-message-chunker').eventMessageChunker; var parseEvent = require('./parse-event').parseEvent; @@ -8798,7 +9325,7 @@ module.exports = { createEventStream: createEventStream }; -},{"../event-stream/event-message-chunker":28,"./parse-event":30}],28:[function(require,module,exports){ +},{"../event-stream/event-message-chunker":29,"./parse-event":31}],29:[function(require,module,exports){ /** * Takes in a buffer of event messages and splits them into individual messages. * @param {Buffer} buffer @@ -8830,7 +9357,7 @@ module.exports = { eventMessageChunker: eventMessageChunker }; -},{}],29:[function(require,module,exports){ +},{}],30:[function(require,module,exports){ var util = require('../core').util; var toBuffer = util.buffer.toBuffer; @@ -8925,7 +9452,7 @@ module.exports = { Int64: Int64 }; -},{"../core":18}],30:[function(require,module,exports){ +},{"../core":19}],31:[function(require,module,exports){ var parseMessage = require('./parse-message').parseMessage; /** @@ -9000,7 +9527,7 @@ module.exports = { parseEvent: parseEvent }; -},{"./parse-message":31}],31:[function(require,module,exports){ +},{"./parse-message":32}],32:[function(require,module,exports){ var Int64 = require('./int64').Int64; var splitMessage = require('./split-message').splitMessage; @@ -9130,7 +9657,7 @@ module.exports = { parseMessage: parseMessage }; -},{"./int64":29,"./split-message":32}],32:[function(require,module,exports){ +},{"./int64":30,"./split-message":33}],33:[function(require,module,exports){ var util = require('../core').util; var toBuffer = util.buffer.toBuffer; @@ -9202,7 +9729,8 @@ module.exports = { splitMessage: splitMessage }; -},{"../core":18}],33:[function(require,module,exports){ +},{"../core":19}],34:[function(require,module,exports){ +(function (process){(function (){ var AWS = require('./core'); var SequentialExecutor = require('./sequential_executor'); var DISCOVER_ENDPOINT = require('./discover_endpoint').discoverEndpoint; @@ -9286,16 +9814,22 @@ AWS.EventListeners = { req.service.config.getCredentials(function(err) { if (err) { req.response.error = AWS.util.error(err, - {code: 'CredentialsError', message: 'Missing credentials in config'}); + {code: 'CredentialsError', message: 'Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1'}); } 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'}); + if (!req.service.isGlobalEndpoint) { + var dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!req.service.config.region) { + req.response.error = AWS.util.error(new Error(), + {code: 'ConfigError', message: 'Missing region in config'}); + } else if (!dnsHostRegex.test(req.service.config.region)) { + req.response.error = AWS.util.error(new Error(), + {code: 'ConfigError', message: 'Invalid region in config'}); + } } }); @@ -9331,6 +9865,28 @@ AWS.EventListeners = { new AWS.ParamValidator(validation).validate(rules, req.params); }); + add('COMPUTE_CHECKSUM', 'afterBuild', function COMPUTE_CHECKSUM(req) { + if (!req.service.api.operations) { + return; + } + var operation = req.service.api.operations[req.operation]; + if (!operation) { + return; + } + var body = req.httpRequest.body; + var isNonStreamingPayload = body && (AWS.util.Buffer.isBuffer(body) || typeof body === 'string'); + var headers = req.httpRequest.headers; + if ( + operation.httpChecksumRequired && + req.service.config.computeChecksums && + isNonStreamingPayload && + !headers['Content-MD5'] + ) { + var md5 = AWS.util.crypto.md5(body, 'base64'); + headers['Content-MD5'] = md5; + } + }); + addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) { req.haltHandlersOnError(); if (!req.service.api.operations) { @@ -9388,6 +9944,24 @@ AWS.EventListeners = { req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; }); + add('SET_TRACE_ID', 'afterBuild', function SET_TRACE_ID(req) { + var traceIdHeaderName = 'X-Amzn-Trace-Id'; + if (AWS.util.isNode() && !Object.hasOwnProperty.call(req.httpRequest.headers, traceIdHeaderName)) { + var ENV_LAMBDA_FUNCTION_NAME = 'AWS_LAMBDA_FUNCTION_NAME'; + var ENV_TRACE_ID = '_X_AMZN_TRACE_ID'; + var functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + var traceId = process.env[ENV_TRACE_ID]; + if ( + typeof functionName === 'string' && + functionName.length > 0 && + typeof traceId === 'string' && + traceId.length > 0 + ) { + req.httpRequest.headers[traceIdHeaderName] = traceId; + } + } + }); + add('RESTART', 'restart', function RESTART() { var err = this.response.error; if (!err || !err.retryable) return; @@ -9424,7 +9998,7 @@ AWS.EventListeners = { var date = service.getSkewCorrectedDate(); var SignerClass = service.getSignerClass(req); var signer = new SignerClass(req.httpRequest, - service.api.signingName || service.api.endpointPrefix, + service.getSigningName(req), { signatureCache: service.config.signatureCache, operation: operation, @@ -9458,7 +10032,17 @@ AWS.EventListeners = { } }); - addAsync('SEND', 'send', function SEND(resp, done) { + add('ERROR', 'error', function ERROR(err, resp) { + var errorCodeMapping = resp.request.service.api.errorCodeMapping; + if (errorCodeMapping && err && err.code) { + var mapping = errorCodeMapping[err.code]; + if (mapping) { + resp.error.code = mapping.code; + } + } + }, true); + + addAsync('SEND', 'send', function SEND(resp, done) { resp.httpResponse._abortCallback = done; resp.error = null; resp.data = null; @@ -9659,7 +10243,7 @@ AWS.EventListeners = { 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; + resp.error.retryDelay = this.service.retryDelays(resp.retryCount, resp.error) || 0; } } }); @@ -9678,7 +10262,8 @@ AWS.EventListeners = { } } - if (willRetry) { + // delay < 0 is a signal from customBackoff to skip retries + if (willRetry && delay >= 0) { resp.error = null; setTimeout(done, delay); } else { @@ -9692,8 +10277,14 @@ AWS.EventListeners = { 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 + + function isDNSError(err) { + return err.errno === 'ENOTFOUND' || + typeof err.errno === 'number' && + typeof AWS.util.getSystemErrorName === 'function' && + ['EAI_NONAME', 'EAI_NODATA'].indexOf(AWS.util.getSystemErrorName(err.errno) >= 0); + } + if (err.code === 'NetworkingError' && isDNSError(err)) { + var message = 'Inaccessible host: `' + err.hostname + '\' at port `' + err.port + '\'. This service may not be available in the `' + err.region + '\' region.'; this.response.error = AWS.util.error(new Error(message), { @@ -9716,6 +10307,9 @@ AWS.EventListeners = { if (!shape) { return shape; } + if (inputShape.isSensitive) { + return '***SensitiveInformation***'; + } switch (inputShape.type) { case 'structure': var struct = {}; @@ -9740,11 +10334,7 @@ AWS.EventListeners = { }); return map; default: - if (inputShape.isSensitive) { - return '***SensitiveInformation***'; - } else { - return shape; - } + return shape; } } @@ -9819,7 +10409,8 @@ AWS.EventListeners = { }) }; -},{"./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){ +}).call(this)}).call(this,require('_process')) +},{"./core":19,"./discover_endpoint":27,"./protocol/json":47,"./protocol/query":48,"./protocol/rest":49,"./protocol/rest_json":50,"./protocol/rest_xml":51,"./sequential_executor":60,"_process":90,"util":84}],35:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; @@ -9983,6 +10574,9 @@ AWS.HttpRequest = inherit({ var newEndpoint = new AWS.Endpoint(endpointStr); this.endpoint = newEndpoint; this.path = newEndpoint.path || '/'; + if (this.headers['Host']) { + this.headers['Host'] = newEndpoint.host; + } } }); @@ -10056,7 +10650,7 @@ AWS.HttpClient.getInstance = function getInstance() { return this.singleton; }; -},{"./core":18}],35:[function(require,module,exports){ +},{"./core":19}],36:[function(require,module,exports){ var AWS = require('../core'); var EventEmitter = require('events').EventEmitter; require('../http'); @@ -10194,7 +10788,7 @@ AWS.HttpClient.prototype = AWS.XHRClient.prototype; */ AWS.HttpClient.streamsApiVersion = 1; -},{"../core":18,"../http":34,"events":82}],36:[function(require,module,exports){ +},{"../core":19,"../http":35,"events":86}],37:[function(require,module,exports){ var util = require('../util'); function JsonBuilder() { } @@ -10215,6 +10809,9 @@ function translate(value, shape) { } function translateStructure(structure, shape) { + if (shape.isDocument) { + return structure; + } var struct = {}; util.each(structure, function(name, value) { var memberShape = shape.members[name]; @@ -10255,7 +10852,7 @@ function translateScalar(value, shape) { */ module.exports = JsonBuilder; -},{"../util":71}],37:[function(require,module,exports){ +},{"../util":72}],38:[function(require,module,exports){ var util = require('../util'); function JsonParser() { } @@ -10277,6 +10874,7 @@ function translate(value, shape) { function translateStructure(structure, shape) { if (structure == null) return undefined; + if (shape.isDocument) return structure; var struct = {}; var shapeMembers = shape.members; @@ -10324,12 +10922,13 @@ function translateScalar(value, shape) { */ module.exports = JsonParser; -},{"../util":71}],38:[function(require,module,exports){ +},{"../util":72}],39:[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 metadata = require('../../apis/metadata.json'); var util = require('../util'); var property = util.property; @@ -10343,6 +10942,9 @@ function Api(api, options) { api.metadata = api.metadata || {}; + var serviceIdentifier = options.serviceIdentifier; + delete options.serviceIdentifier; + property(this, 'isApi', true, false); property(this, 'apiVersion', api.metadata.apiVersion); property(this, 'endpointPrefix', api.metadata.endpointPrefix); @@ -10357,6 +10959,9 @@ function Api(api, options) { property(this, 'abbreviation', api.metadata.serviceAbbreviation); property(this, 'fullName', api.metadata.serviceFullName); property(this, 'serviceId', api.metadata.serviceId); + if (serviceIdentifier && metadata[serviceIdentifier]) { + property(this, 'xmlNoDefaultLists', metadata[serviceIdentifier].xmlNoDefaultLists, false); + } memoizedProperty(this, 'className', function() { var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName; @@ -10371,6 +10976,13 @@ function Api(api, options) { if (operation.endpointoperation === true) { property(self, 'endpointOperation', util.string.lowerFirst(name)); } + if (operation.endpointdiscovery && !self.hasRequiredEndpointDiscovery) { + property( + self, + 'hasRequiredEndpointDiscovery', + operation.endpointdiscovery.required === true + ); + } } property(this, 'operations', new Collection(api.operations, options, function(name, operation) { @@ -10393,6 +11005,7 @@ function Api(api, options) { property(this, 'documentation', api.documentation); property(this, 'documentationUrl', api.documentationUrl); } + property(this, 'errorCodeMapping', api.awsQueryCompatible); } /** @@ -10400,7 +11013,7 @@ function Api(api, options) { */ module.exports = Api; -},{"../util":71,"./collection":39,"./operation":40,"./paginator":41,"./resource_waiter":42,"./shape":43}],39:[function(require,module,exports){ +},{"../../apis/metadata.json":4,"../util":72,"./collection":40,"./operation":41,"./paginator":42,"./resource_waiter":43,"./shape":44}],40:[function(require,module,exports){ var memoizedProperty = require('../util').memoizedProperty; function memoize(name, value, factory, nameTr) { @@ -10426,7 +11039,7 @@ function Collection(iterable, options, factory, nameTr, callback) { */ module.exports = Collection; -},{"../util":71}],40:[function(require,module,exports){ +},{"../util":72}],41:[function(require,module,exports){ var Shape = require('./shape'); var util = require('../util'); @@ -10453,6 +11066,12 @@ function Operation(name, operation, options) { 'NULL' ); + // httpChecksum replaces usage of httpChecksumRequired, but some APIs + // (s3control) still uses old trait. + var httpChecksumRequired = operation.httpChecksumRequired + || (operation.httpChecksum && operation.httpChecksum.requestChecksumRequired); + property(this, 'httpChecksumRequired', httpChecksumRequired, false); + memoizedProperty(this, 'input', function() { if (!operation.input) { return new Shape.create({type: 'structure'}, options); @@ -10541,7 +11160,7 @@ function hasEventStream(topLevelShape) { */ module.exports = Operation; -},{"../util":71,"./shape":43}],41:[function(require,module,exports){ +},{"../util":72,"./shape":44}],42:[function(require,module,exports){ var property = require('../util').property; function Paginator(name, paginator) { @@ -10557,7 +11176,7 @@ function Paginator(name, paginator) { */ module.exports = Paginator; -},{"../util":71}],42:[function(require,module,exports){ +},{"../util":72}],43:[function(require,module,exports){ var util = require('../util'); var property = util.property; @@ -10592,7 +11211,7 @@ function ResourceWaiter(name, waiter, options) { */ module.exports = ResourceWaiter; -},{"../util":71}],43:[function(require,module,exports){ +},{"../util":72}],44:[function(require,module,exports){ var Collection = require('./collection'); var util = require('../util'); @@ -10761,6 +11380,7 @@ function StructureShape(shape, options) { property(this, 'memberNames', []); property(this, 'required', []); property(this, 'isRequired', function() { return false; }); + property(this, 'isDocument', Boolean(shape.document)); } if (shape.members) { @@ -11000,7 +11620,7 @@ Shape.shapes = { */ module.exports = Shape; -},{"../util":71,"./collection":39}],44:[function(require,module,exports){ +},{"../util":72,"./collection":40}],45:[function(require,module,exports){ var AWS = require('./core'); /** @@ -11054,8 +11674,9 @@ AWS.ParamValidator = AWS.util.inherit({ }, validateStructure: function validateStructure(shape, params, context) { - this.validateType(params, context, ['object'], 'structure'); + if (shape.isDocument) return true; + this.validateType(params, context, ['object'], 'structure'); var paramName; for (var i = 0; shape.required && i < shape.required.length; i++) { paramName = shape.required[i]; @@ -11076,7 +11697,7 @@ AWS.ParamValidator = AWS.util.inherit({ if (memberShape !== undefined) { var memberContext = [context, paramName].join('.'); this.validateMember(memberShape, paramValue, memberContext); - } else { + } else if (paramValue !== undefined && paramValue !== null) { this.fail('UnexpectedParameter', 'Unexpected key \'' + paramName + '\' found in ' + context); } @@ -11272,7 +11893,7 @@ AWS.ParamValidator = AWS.util.inherit({ } }); -},{"./core":18}],45:[function(require,module,exports){ +},{"./core":19}],46:[function(require,module,exports){ var util = require('../util'); var AWS = require('../core'); @@ -11363,7 +11984,7 @@ module.exports = { populateHostPrefix: populateHostPrefix }; -},{"../core":18,"../util":71}],46:[function(require,module,exports){ +},{"../core":19,"../util":72}],47:[function(require,module,exports){ var util = require('../util'); var JsonBuilder = require('../json/builder'); var JsonParser = require('../json/parser'); @@ -11397,8 +12018,9 @@ function extractError(resp) { 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(); + var code = e.__type || e.code || e.Code; + if (code) { + error.code = code.split('#').pop(); } if (error.code === 'RequestEntityTooLarge') { error.message = 'Request body must be less than 1 MB'; @@ -11438,7 +12060,7 @@ module.exports = { extractData: extractData }; -},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(require,module,exports){ +},{"../json/builder":37,"../json/parser":38,"../util":72,"./helpers":46}],48:[function(require,module,exports){ var AWS = require('../core'); var util = require('../util'); var QueryParamSerializer = require('../query/query_param_serializer'); @@ -11550,7 +12172,7 @@ module.exports = { extractData: extractData }; -},{"../core":18,"../model/shape":43,"../query/query_param_serializer":51,"../util":71,"./helpers":45}],48:[function(require,module,exports){ +},{"../core":19,"../model/shape":44,"../query/query_param_serializer":52,"../util":72,"./helpers":46}],49:[function(require,module,exports){ var util = require('../util'); var populateHostPrefix = require('./helpers').populateHostPrefix; @@ -11700,7 +12322,7 @@ module.exports = { generateURI: generateURI }; -},{"../util":71,"./helpers":45}],49:[function(require,module,exports){ +},{"../util":72,"./helpers":46}],50:[function(require,module,exports){ var util = require('../util'); var Rest = require('./rest'); var Json = require('./json'); @@ -11715,30 +12337,24 @@ function populateBody(req) { 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); + req.httpRequest.body = builder.build(params || {}, payloadShape); applyContentTypeHeader(req); - } else { // non-JSON payload + } else if (params !== undefined) { + // 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; - } + req.httpRequest.body = builder.build(req.params, input); 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; @@ -11748,8 +12364,8 @@ function applyContentTypeHeader(req, isBinary) { function buildRequest(req) { Rest.buildRequest(req); - // never send body payload on HEAD/DELETE - if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { + // never send body payload on GET/HEAD/DELETE + if (['GET', 'HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { populateBody(req); } } @@ -11801,7 +12417,7 @@ module.exports = { extractData: extractData }; -},{"../json/builder":36,"../json/parser":37,"../util":71,"./json":46,"./rest":48}],50:[function(require,module,exports){ +},{"../json/builder":37,"../json/parser":38,"../util":72,"./json":47,"./rest":49}],51:[function(require,module,exports){ var AWS = require('../core'); var util = require('../util'); var Rest = require('./rest'); @@ -11911,7 +12527,7 @@ module.exports = { extractData: extractData }; -},{"../core":18,"../util":71,"./rest":48}],51:[function(require,module,exports){ +},{"../core":19,"../util":72,"./rest":49}],52:[function(require,module,exports){ var util = require('../util'); function QueryParamSerializer() { @@ -11997,7 +12613,7 @@ function serializeMember(name, value, rules, fn) { */ module.exports = QueryParamSerializer; -},{"../util":71}],52:[function(require,module,exports){ +},{"../util":72}],53:[function(require,module,exports){ module.exports = { //provide realtime clock for performance measurement now: function now() { @@ -12008,13 +12624,35 @@ module.exports = { } }; -},{}],53:[function(require,module,exports){ +},{}],54:[function(require,module,exports){ +function isFipsRegion(region) { + return typeof region === 'string' && (region.startsWith('fips-') || region.endsWith('-fips')); +} + +function isGlobalRegion(region) { + return typeof region === 'string' && ['aws-global', 'aws-us-gov-global'].includes(region); +} + +function getRealRegion(region) { + return ['fips-aws-global', 'aws-fips', 'aws-global'].includes(region) + ? 'us-east-1' + : ['fips-aws-us-gov-global', 'aws-us-gov-global'].includes(region) + ? 'us-gov-west-1' + : region.replace(/fips-(dkr-|prod-)?|-fips/, ''); +} + +module.exports = { + isFipsRegion: isFipsRegion, + isGlobalRegion: isGlobalRegion, + getRealRegion: getRealRegion +}; + +},{}],55:[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('-') + '-*'; @@ -12048,24 +12686,31 @@ function applyConfig(service, config) { function configureEndpoint(service) { var keys = derivedKeys(service); + var useFipsEndpoint = service.config.useFipsEndpoint; + var useDualstackEndpoint = service.config.useDualstackEndpoint; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!key) continue; - if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) { - var config = regionConfig.rules[key]; + var rules = useFipsEndpoint + ? useDualstackEndpoint + ? regionConfig.dualstackFipsRules + : regionConfig.fipsRules + : useDualstackEndpoint + ? regionConfig.dualstackRules + : regionConfig.rules; + + if (Object.prototype.hasOwnProperty.call(rules, key)) { + var config = rules[key]; if (typeof config === 'string') { config = regionConfig.patterns[config]; } - // set dualstack endpoint - if (service.config.useDualstack && util.isDualstackAvailable(service)) { - config = util.copy(config); - config.endpoint = '{service}.dualstack.{region}.amazonaws.com'; - } - // set global endpoint service.isGlobalEndpoint = !!config.globalEndpoint; + if (config.signingRegion) { + service.signingRegion = config.signingRegion; + } // signature version if (!config.signatureVersion) config.signatureVersion = 'v4'; @@ -12077,12 +12722,33 @@ function configureEndpoint(service) { } } +function getEndpointSuffix(region) { + var regionRegexes = { + '^(us|eu|ap|sa|ca|me)\\-\\w+\\-\\d+$': 'amazonaws.com', + '^cn\\-\\w+\\-\\d+$': 'amazonaws.com.cn', + '^us\\-gov\\-\\w+\\-\\d+$': 'amazonaws.com', + '^us\\-iso\\-\\w+\\-\\d+$': 'c2s.ic.gov', + '^us\\-isob\\-\\w+\\-\\d+$': 'sc2s.sgov.gov' + }; + var defaultSuffix = 'amazonaws.com'; + var regexes = Object.keys(regionRegexes); + for (var i = 0; i < regexes.length; i++) { + var regionPattern = RegExp(regexes[i]); + var dnsSuffix = regionRegexes[regexes[i]]; + if (regionPattern.test(region)) return dnsSuffix; + } + return defaultSuffix; +} + /** * @api private */ -module.exports = configureEndpoint; +module.exports = { + configureEndpoint: configureEndpoint, + getEndpointSuffix: getEndpointSuffix, +}; -},{"./region_config_data.json":54,"./util":71}],54:[function(require,module,exports){ +},{"./region_config_data.json":56,"./util":72}],56:[function(require,module,exports){ module.exports={ "rules": { "*/*": { @@ -12091,22 +12757,45 @@ module.exports={ "cn-*/*": { "endpoint": "{service}.{region}.amazonaws.com.cn" }, + "us-iso-*/*": "usIso", + "us-isob-*/*": "usIsob", "*/budgets": "globalSSL", "*/cloudfront": "globalSSL", - "*/iam": "globalSSL", "*/sts": "globalSSL", "*/importexport": { "endpoint": "{service}.amazonaws.com", "signatureVersion": "v2", "globalEndpoint": true }, - "*/route53": { - "endpoint": "https://{service}.amazonaws.com", - "signatureVersion": "v3https", - "globalEndpoint": true + + "*/route53": "globalSSL", + "cn-*/route53": { + "endpoint": "{service}.amazonaws.com.cn", + "globalEndpoint": true, + "signingRegion": "cn-northwest-1" }, + "us-gov-*/route53": "globalGovCloud", + "us-iso-*/route53": { + "endpoint": "{service}.c2s.ic.gov", + "globalEndpoint": true, + "signingRegion": "us-iso-east-1" + }, + "us-isob-*/route53": { + "endpoint": "{service}.sc2s.sgov.gov", + "globalEndpoint": true, + "signingRegion": "us-isob-east-1" + }, + "*/waf": "globalSSL", + + "*/iam": "globalSSL", + "cn-*/iam": { + "endpoint": "{service}.cn-north-1.amazonaws.com.cn", + "globalEndpoint": true, + "signingRegion": "cn-north-1" + }, "us-gov-*/iam": "globalGovCloud", + "us-gov-*/sts": { "endpoint": "{service}.{region}.amazonaws.com" }, @@ -12132,22 +12821,164 @@ module.exports={ } }, + "fipsRules": { + "*/*": "fipsStandard", + "us-gov-*/*": "fipsStandard", + "us-iso-*/*": { + "endpoint": "{service}-fips.{region}.c2s.ic.gov" + }, + "us-iso-*/dms": "usIso", + "us-isob-*/*": { + "endpoint": "{service}-fips.{region}.sc2s.sgov.gov" + }, + "us-isob-*/dms": "usIsob", + "cn-*/*": { + "endpoint": "{service}-fips.{region}.amazonaws.com.cn" + }, + "*/api.ecr": "fips.api.ecr", + "*/api.sagemaker": "fips.api.sagemaker", + "*/batch": "fipsDotPrefix", + "*/eks": "fipsDotPrefix", + "*/models.lex": "fips.models.lex", + "*/runtime.lex": "fips.runtime.lex", + "*/runtime.sagemaker": { + "endpoint": "runtime-fips.sagemaker.{region}.amazonaws.com" + }, + "*/iam": "fipsWithoutRegion", + "*/route53": "fipsWithoutRegion", + "*/transcribe": "fipsDotPrefix", + "*/waf": "fipsWithoutRegion", + + "us-gov-*/transcribe": "fipsDotPrefix", + "us-gov-*/api.ecr": "fips.api.ecr", + "us-gov-*/api.sagemaker": "fips.api.sagemaker", + "us-gov-*/models.lex": "fips.models.lex", + "us-gov-*/runtime.lex": "fips.runtime.lex", + "us-gov-*/acm-pca": "fipsWithServiceOnly", + "us-gov-*/batch": "fipsWithServiceOnly", + "us-gov-*/config": "fipsWithServiceOnly", + "us-gov-*/eks": "fipsWithServiceOnly", + "us-gov-*/elasticmapreduce": "fipsWithServiceOnly", + "us-gov-*/identitystore": "fipsWithServiceOnly", + "us-gov-*/dynamodb": "fipsWithServiceOnly", + "us-gov-*/elasticloadbalancing": "fipsWithServiceOnly", + "us-gov-*/guardduty": "fipsWithServiceOnly", + "us-gov-*/monitoring": "fipsWithServiceOnly", + "us-gov-*/resource-groups": "fipsWithServiceOnly", + "us-gov-*/runtime.sagemaker": "fipsWithServiceOnly", + "us-gov-*/servicecatalog-appregistry": "fipsWithServiceOnly", + "us-gov-*/servicequotas": "fipsWithServiceOnly", + "us-gov-*/ssm": "fipsWithServiceOnly", + "us-gov-*/sts": "fipsWithServiceOnly", + "us-gov-*/support": "fipsWithServiceOnly", + "us-gov-west-1/states": "fipsWithServiceOnly", + "us-iso-east-1/elasticfilesystem": { + "endpoint": "elasticfilesystem-fips.{region}.c2s.ic.gov" + }, + "us-gov-west-1/organizations": "fipsWithServiceOnly", + "us-gov-west-1/route53": { + "endpoint": "route53.us-gov.amazonaws.com" + } + }, + + "dualstackRules": { + "*/*": { + "endpoint": "{service}.{region}.api.aws" + }, + "cn-*/*": { + "endpoint": "{service}.{region}.api.amazonwebservices.com.cn" + }, + + "*/s3": "dualstackLegacy", + "cn-*/s3": "dualstackLegacyCn", + "*/s3-control": "dualstackLegacy", + "cn-*/s3-control": "dualstackLegacyCn", + + "ap-south-1/ec2": "dualstackLegacyEc2", + "eu-west-1/ec2": "dualstackLegacyEc2", + "sa-east-1/ec2": "dualstackLegacyEc2", + "us-east-1/ec2": "dualstackLegacyEc2", + "us-east-2/ec2": "dualstackLegacyEc2", + "us-west-2/ec2": "dualstackLegacyEc2" + }, + + "dualstackFipsRules": { + "*/*": { + "endpoint": "{service}-fips.{region}.api.aws" + }, + "cn-*/*": { + "endpoint": "{service}-fips.{region}.api.amazonwebservices.com.cn" + }, + "*/s3": "dualstackFipsLegacy", + "cn-*/s3": "dualstackFipsLegacyCn", + "*/s3-control": "dualstackFipsLegacy", + "cn-*/s3-control": "dualstackFipsLegacyCn" + }, + "patterns": { "globalSSL": { "endpoint": "https://{service}.amazonaws.com", - "globalEndpoint": true + "globalEndpoint": true, + "signingRegion": "us-east-1" }, "globalGovCloud": { - "endpoint": "{service}.us-gov.amazonaws.com" + "endpoint": "{service}.us-gov.amazonaws.com", + "globalEndpoint": true, + "signingRegion": "us-gov-west-1" }, "s3signature": { "endpoint": "{service}.{region}.amazonaws.com", "signatureVersion": "s3" + }, + "usIso": { + "endpoint": "{service}.{region}.c2s.ic.gov" + }, + "usIsob": { + "endpoint": "{service}.{region}.sc2s.sgov.gov" + }, + "fipsStandard": { + "endpoint": "{service}-fips.{region}.amazonaws.com" + }, + "fipsDotPrefix": { + "endpoint": "fips.{service}.{region}.amazonaws.com" + }, + "fipsWithoutRegion": { + "endpoint": "{service}-fips.amazonaws.com" + }, + "fips.api.ecr": { + "endpoint": "ecr-fips.{region}.amazonaws.com" + }, + "fips.api.sagemaker": { + "endpoint": "api-fips.sagemaker.{region}.amazonaws.com" + }, + "fips.models.lex": { + "endpoint": "models-fips.lex.{region}.amazonaws.com" + }, + "fips.runtime.lex": { + "endpoint": "runtime-fips.lex.{region}.amazonaws.com" + }, + "fipsWithServiceOnly": { + "endpoint": "{service}.{region}.amazonaws.com" + }, + "dualstackLegacy": { + "endpoint": "{service}.dualstack.{region}.amazonaws.com" + }, + "dualstackLegacyCn": { + "endpoint": "{service}.dualstack.{region}.amazonaws.com.cn" + }, + "dualstackFipsLegacy": { + "endpoint": "{service}-fips.dualstack.{region}.amazonaws.com" + }, + "dualstackFipsLegacyCn": { + "endpoint": "{service}-fips.dualstack.{region}.amazonaws.com.cn" + }, + "dualstackLegacyEc2": { + "endpoint": "api.ec2.{region}.aws" } } } -},{}],55:[function(require,module,exports){ +},{}],57:[function(require,module,exports){ (function (process){(function (){ var AWS = require('./core'); var AcceptorStateMachine = require('./state_machine'); @@ -12464,8 +13295,11 @@ AWS.Request = inherit({ var region = service.config.region; var customUserAgent = service.config.customUserAgent; - // global endpoints sign as us-east-1 - if (service.isGlobalEndpoint) region = 'us-east-1'; + if (service.signingRegion) { + region = service.signingRegion; + } else if (service.isGlobalEndpoint) { + region = 'us-east-1'; + } this.domain = domain && domain.active; this.service = service; @@ -12931,7 +13765,7 @@ AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) if (resp.error) { reject(resp.error); } else { - // define $response property so that it is not enumberable + // define $response property so that it is not enumerable // this prevents circular reference errors when stringifying the JSON object resolve(Object.defineProperty( resp.data || {}, @@ -12957,7 +13791,7 @@ 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){ +},{"./core":19,"./state_machine":71,"_process":90,"jmespath":89}],58:[function(require,module,exports){ /** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -13163,7 +13997,7 @@ AWS.ResourceWaiter = inherit({ } }); -},{"./core":18,"jmespath":85}],57:[function(require,module,exports){ +},{"./core":19,"jmespath":89}],59:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; var jmespath = require('jmespath'); @@ -13366,7 +14200,7 @@ AWS.Response = inherit({ }); -},{"./core":18,"jmespath":85}],58:[function(require,module,exports){ +},{"./core":19,"jmespath":89}],60:[function(require,module,exports){ var AWS = require('./core'); /** @@ -13603,7 +14437,7 @@ AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype. */ module.exports = AWS.SequentialExecutor; -},{"./core":18}],59:[function(require,module,exports){ +},{"./core":19}],61:[function(require,module,exports){ (function (process){(function (){ var AWS = require('./core'); var Api = require('./model/api'); @@ -13611,6 +14445,7 @@ var regionConfig = require('./region_config'); var inherit = AWS.util.inherit; var clientCount = 0; +var region_utils = require('./region/utils'); /** * The service class representing an AWS service. @@ -13632,6 +14467,24 @@ AWS.Service = inherit({ throw AWS.util.error(new Error(), 'Service must be constructed with `new\' operator'); } + + if (config) { + if (config.region) { + var region = config.region; + if (region_utils.isFipsRegion(region)) { + config.region = region_utils.getRealRegion(region); + config.useFipsEndpoint = true; + } + if (region_utils.isGlobalRegion(region)) { + config.region = region_utils.getRealRegion(region); + } + } + if (typeof config.useDualstack === 'boolean' + && typeof config.useDualstackEndpoint !== 'boolean') { + config.useDualstackEndpoint = config.useDualstack; + } + } + var ServiceClass = this.loadServiceClass(config || {}); if (ServiceClass) { var originalConfig = AWS.util.copy(config); @@ -13657,7 +14510,7 @@ AWS.Service = inherit({ if (config) this.config.update(config, true); this.validateService(); - if (!this.config.endpoint) regionConfig(this); + if (!this.config.endpoint) regionConfig.configureEndpoint(this); this.config.endpoint = this.endpointFromTemplate(this.config.endpoint); this.setEndpoint(this.config.endpoint); @@ -14040,6 +14893,8 @@ AWS.Service = inherit({ apiCallEvent.Latency = latency >= 0 ? latency : 0; var response = request.response; if ( + response.error && + response.error.retryable && typeof response.retryCount === 'number' && typeof response.maxRetries === 'number' && (response.retryCount >= response.maxRetries) @@ -14059,6 +14914,14 @@ AWS.Service = inherit({ setupRequestListeners: function setupRequestListeners(request) { }, + /** + * Gets the signing name for a given request + * @api private + */ + getSigningName: function getSigningName() { + return this.api.signingName || this.api.endpointPrefix; + }, + /** * Gets the signer class for a given request * @api private @@ -14124,8 +14987,8 @@ AWS.Service = inherit({ /** * @api private */ - retryDelays: function retryDelays(retryCount) { - return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions); + retryDelays: function retryDelays(retryCount, err) { + return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions, err); }, /** @@ -14199,7 +15062,7 @@ AWS.Service = inherit({ */ isClockSkewed: function isClockSkewed(newServerTime) { if (newServerTime) { - return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000; + return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 300000; } }, @@ -14218,6 +15081,7 @@ AWS.Service = inherit({ case 'RequestThrottledException': case 'TooManyRequestsException': case 'TransactionInProgressException': //dynamodb + case 'EC2ThrottledException': return true; default: return false; @@ -14358,7 +15222,9 @@ AWS.util.update(AWS.Service, { if (api.isApi) { svc.prototype.api = api; } else { - svc.prototype.api = new Api(api); + svc.prototype.api = new Api(api, { + serviceIdentifier: superclass.serviceIdentifier + }); } } @@ -14427,27 +15293,9 @@ AWS.util.mixin(AWS.Service, AWS.SequentialExecutor); module.exports = AWS.Service; }).call(this)}).call(this,require('_process')) -},{"./core":18,"./model/api":38,"./region_config":53,"_process":86}],60:[function(require,module,exports){ -var AWS = require('../core'); - -AWS.util.update(AWS.CognitoIdentity.prototype, { - getOpenIdToken: function getOpenIdToken(params, callback) { - return this.makeUnauthenticatedRequest('getOpenIdToken', params, callback); - }, - - getId: function getId(params, callback) { - return this.makeUnauthenticatedRequest('getId', params, callback); - }, - - getCredentialsForIdentity: function getCredentialsForIdentity(params, callback) { - return this.makeUnauthenticatedRequest('getCredentialsForIdentity', params, callback); - } -}); - -},{"../core":18}],61:[function(require,module,exports){ -(function (process){(function (){ +},{"./core":19,"./model/api":39,"./region/utils":54,"./region_config":55,"_process":90}],62:[function(require,module,exports){ var AWS = require('../core'); -var regionConfig = require('../region_config'); +var resolveRegionalEndpointsFlag = require('../config_regional_endpoint'); var ENV_REGIONAL_ENDPOINT_ENABLED = 'AWS_STS_REGIONAL_ENDPOINTS'; var CONFIG_REGIONAL_ENDPOINT_ENABLED = 'sts_regional_endpoints'; @@ -14499,83 +15347,41 @@ AWS.util.update(AWS.STS.prototype, { /** * @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] + '".' - }); - } + setupRequestListeners: function setupRequestListeners(request) { + request.addListener('validate', this.optInRegionalEndpoint, true); }, /** * @api private */ - optInRegionalEndpoint: function optInRegionalEndpoint() { - this.validateRegionalEndpointsFlag(); - var config = this.config; - if (config.stsRegionalEndpoints === 'regional') { - regionConfig(this); - if (!this.isGlobalEndpoint) return; - this.isGlobalEndpoint = false; + optInRegionalEndpoint: function optInRegionalEndpoint(req) { + var service = req.service; + var config = service.config; + config.stsRegionalEndpoints = resolveRegionalEndpointsFlag(service._originalConfig, { + env: ENV_REGIONAL_ENDPOINT_ENABLED, + sharedConfig: CONFIG_REGIONAL_ENDPOINT_ENABLED, + clientConfig: 'stsRegionalEndpoints' + }); + if ( + config.stsRegionalEndpoints === 'regional' && + service.isGlobalEndpoint + ) { //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) + + var regionalEndpoint = config.endpoint.substring(0, insertPoint) + '.' + config.region + config.endpoint.substring(insertPoint); + req.httpRequest.updateEndpoint(regionalEndpoint); + req.httpRequest.region = config.region; } - }, - - validateService: function validateService() { - this.optInRegionalEndpoint(); } }); -}).call(this)}).call(this,require('_process')) -},{"../core":18,"../region_config":53,"_process":86}],62:[function(require,module,exports){ +},{"../config_regional_endpoint":18,"../core":19}],63:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -14630,8 +15436,8 @@ function signedUrlSigner(request) { var auth = request.httpRequest.headers['Authorization'].split(' '); if (auth[0] === 'AWS') { auth = auth[1].split(':'); - queryParams['AWSAccessKeyId'] = auth[0]; - queryParams['Signature'] = auth[1]; + queryParams['Signature'] = auth.pop(); + queryParams['AWSAccessKeyId'] = auth.join(':'); AWS.util.each(request.httpRequest.headers, function (key, value) { if (key === expiresHeader) key = 'Expires'; @@ -14696,7 +15502,7 @@ AWS.Signers.Presign = inherit({ */ module.exports = AWS.Signers.Presign; -},{"../core":18}],63:[function(require,module,exports){ +},{"../core":19}],64:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -14737,7 +15543,7 @@ 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){ +},{"../core":19,"./presign":63,"./s3":65,"./v2":66,"./v3":67,"./v3https":68,"./v4":69}],65:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -14914,7 +15720,7 @@ AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.S3; -},{"../core":18}],65:[function(require,module,exports){ +},{"../core":19}],66:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -14964,7 +15770,7 @@ AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.V2; -},{"../core":18}],66:[function(require,module,exports){ +},{"../core":19}],67:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -15043,7 +15849,7 @@ AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.V3; -},{"../core":18}],67:[function(require,module,exports){ +},{"../core":19}],68:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -15070,7 +15876,7 @@ AWS.Signers.V3Https = inherit(AWS.Signers.V3, { */ module.exports = AWS.Signers.V3Https; -},{"../core":18,"./v3":66}],68:[function(require,module,exports){ +},{"../core":19,"./v3":67}],69:[function(require,module,exports){ var AWS = require('../core'); var v4Credentials = require('./v4_credentials'); var inherit = AWS.util.inherit; @@ -15252,7 +16058,7 @@ AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { hexEncodedBodyHash: function hexEncodedBodyHash() { var request = this.request; - if (this.isPresigned() && this.serviceName === 's3' && !request.body) { + if (this.isPresigned() && (['s3', 's3-object-lambda'].indexOf(this.serviceName) > -1) && !request.body) { return 'UNSIGNED-PAYLOAD'; } else if (request.headers['X-Amz-Content-Sha256']) { return request.headers['X-Amz-Content-Sha256']; @@ -15287,7 +16093,7 @@ AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.V4; -},{"../core":18,"./v4_credentials":69}],69:[function(require,module,exports){ +},{"../core":19,"./v4_credentials":70}],70:[function(require,module,exports){ var AWS = require('../core'); /** @@ -15389,7 +16195,7 @@ module.exports = { } }; -},{"../core":18}],70:[function(require,module,exports){ +},{"../core":19}],71:[function(require,module,exports){ function AcceptorStateMachine(states, state) { this.currentState = state || null; this.states = states || {}; @@ -15436,7 +16242,7 @@ AcceptorStateMachine.prototype.addState = function addState(name, acceptState, f */ module.exports = AcceptorStateMachine; -},{}],71:[function(require,module,exports){ +},{}],72:[function(require,module,exports){ (function (process,setImmediate){(function (){ /* eslint guard-for-in:0 */ var AWS; @@ -15655,15 +16461,28 @@ var util = { 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]; + line = line.split(/(^|\s)[;#]/)[0].trim(); // remove comments and trim + var isSection = line[0] === '[' && line[line.length - 1] === ']'; + if (isSection) { + currentSection = line.substring(1, line.length - 1); + if (currentSection === '__proto__' || currentSection.split(/\s/)[1] === '__proto__') { + throw util.error( + new Error('Cannot load profile name \'' + currentSection + '\' from shared ini file.') + ); + } } else if (currentSection) { - var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); - if (item) { + var indexOfEqualsSign = line.indexOf('='); + var start = 0; + var end = line.length - 1; + var isAssignment = + indexOfEqualsSign !== -1 && indexOfEqualsSign !== start && indexOfEqualsSign !== end; + + if (isAssignment) { + var name = line.substring(0, indexOfEqualsSign).trim(); + var value = line.substring(indexOfEqualsSign + 1).trim(); + map[currentSection] = map[currentSection] || {}; - map[currentSection][item[1]] = item[2]; + map[currentSection][name] = value; } } }); @@ -16034,7 +16853,7 @@ var util = { Object.defineProperty(err, 'message', {enumerable: true}); } - err.name = options && options.name || err.name || err.code || 'Error'; + err.name = String(options && options.name || err.name || err.code || 'Error'); err.time = new Date(); if (originalError) err.originalError = originalError; @@ -16290,11 +17109,11 @@ var util = { /** * @api private */ - calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) { + calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions, err) { if (!retryDelayOptions) retryDelayOptions = {}; var customBackoff = retryDelayOptions.customBackoff || null; if (typeof customBackoff === 'function') { - return customBackoff(retryCount); + return customBackoff(retryCount, err); } var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100; var delay = Math.random() * (Math.pow(2, retryCount) * base); @@ -16313,13 +17132,17 @@ var util = { var errCallback = function(err) { var maxRetries = options.maxRetries || 0; if (err && err.code === 'TimeoutError') err.retryable = true; + + // Call `calculateRetryDelay()` only when relevant, see #3401 if (err && err.retryable && retryCount < maxRetries) { - retryCount++; - var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions); - setTimeout(sendRequest, delay + (err.retryAfter || 0)); - } else { - cb(err); + var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions, err); + if (delay >= 0) { + retryCount++; + setTimeout(sendRequest, delay + (err.retryAfter || 0)); + return; + } } + cb(err); }; var sendRequest = function() { @@ -16333,7 +17156,10 @@ var util = { } else { var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0; var err = util.error(new Error(), - { retryable: statusCode >= 500 || statusCode === 429 } + { + statusCode: statusCode, + retryable: statusCode >= 500 || statusCode === 429 + } ); if (retryAfter && err.retryable) err.retryAfter = retryAfter; errCallback(err); @@ -16399,17 +17225,62 @@ var util = { filename: process.env[util.sharedConfigFileEnv] }); } - var profilesFromCreds = iniLoader.loadFrom({ - filename: filename || - (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv]) - }); + var profilesFromCreds= {}; + try { + var profilesFromCreds = iniLoader.loadFrom({ + filename: filename || + (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv]) + }); + } catch (error) { + // if using config, assume it is fully descriptive without a credentials file: + if (!process.env[util.configOptInEnv]) throw error; + } for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) { - profiles[profileNames[i]] = profilesFromConfig[profileNames[i]]; + profiles[profileNames[i]] = objectAssign(profiles[profileNames[i]] || {}, profilesFromConfig[profileNames[i]]); } for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) { - profiles[profileNames[i]] = profilesFromCreds[profileNames[i]]; + profiles[profileNames[i]] = objectAssign(profiles[profileNames[i]] || {}, profilesFromCreds[profileNames[i]]); } return profiles; + + /** + * Roughly the semantics of `Object.assign(target, source)` + */ + function objectAssign(target, source) { + for (var i = 0, keys = Object.keys(source); i < keys.length; i++) { + target[keys[i]] = source[keys[i]]; + } + return target; + } + }, + + /** + * @api private + */ + ARN: { + validate: function validateARN(str) { + return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6; + }, + parse: function parseARN(arn) { + var matched = arn.split(':'); + return { + partition: matched[1], + service: matched[2], + region: matched[3], + accountId: matched[4], + resource: matched.slice(5).join(':') + }; + }, + build: function buildARN(arnObject) { + if ( + arnObject.service === undefined || + arnObject.region === undefined || + arnObject.accountId === undefined || + arnObject.resource === undefined + ) throw util.error(new Error('Input ARN object is invalid')); + return 'arn:'+ (arnObject.partition || 'aws') + ':' + arnObject.service + + ':' + arnObject.region + ':' + arnObject.accountId + ':' + arnObject.resource; + } }, /** @@ -16444,7 +17315,7 @@ var util = { 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){ +},{"../apis/metadata.json":4,"./core":19,"_process":90,"fs":80,"timers":97,"uuid":100}],73:[function(require,module,exports){ var util = require('../util'); var Shape = require('../model/shape'); @@ -16555,7 +17426,10 @@ function parseStructure(xml, shape) { getElementByTagName(xml, memberShape.name); if (xmlChild) { data[memberName] = parseXml(xmlChild, memberShape); - } else if (!memberShape.flattened && memberShape.type === 'list') { + } else if ( + !memberShape.flattened && + memberShape.type === 'list' && + !shape.api.xmlNoDefaultLists) { data[memberName] = memberShape.defaultValue; } } @@ -16644,7 +17518,7 @@ function parseUnknown(xml) { */ module.exports = DomXmlParser; -},{"../model/shape":43,"../util":71}],73:[function(require,module,exports){ +},{"../model/shape":44,"../util":72}],74:[function(require,module,exports){ var util = require('../util'); var XmlNode = require('./xml-node').XmlNode; var XmlText = require('./xml-text').XmlText; @@ -16748,7 +17622,7 @@ function applyNamespaces(xml, shape, isRoot) { */ module.exports = XmlBuilder; -},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(require,module,exports){ +},{"../util":72,"./xml-node":77,"./xml-text":78}],75:[function(require,module,exports){ /** * Escapes characters that can not be in an XML attribute. */ @@ -16763,12 +17637,18 @@ module.exports = { escapeAttribute: escapeAttribute }; -},{}],75:[function(require,module,exports){ +},{}],76:[function(require,module,exports){ /** * Escapes characters that can not be in an XML element. */ function escapeElement(value) { - return value.replace(/&/g, '&').replace(//g, '>'); + return value.replace(/&/g, '&') + .replace(//g, '>') + .replace(/\r/g, ' ') + .replace(/\n/g, ' ') + .replace(/\u0085/g, '…') + .replace(/\u2028/, '
'); } /** @@ -16778,7 +17658,7 @@ module.exports = { escapeElement: escapeElement }; -},{}],76:[function(require,module,exports){ +},{}],77:[function(require,module,exports){ var escapeAttribute = require('./escape-attribute').escapeAttribute; /** @@ -16825,7 +17705,7 @@ module.exports = { XmlNode: XmlNode }; -},{"./escape-attribute":74}],77:[function(require,module,exports){ +},{"./escape-attribute":75}],78:[function(require,module,exports){ var escapeElement = require('./escape-element').escapeElement; /** @@ -16847,7 +17727,7 @@ module.exports = { XmlText: XmlText }; -},{"./escape-element":75}],78:[function(require,module,exports){ +},{"./escape-element":76}],79:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -16999,9 +17879,34 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],79:[function(require,module,exports){ - },{}],80:[function(require,module,exports){ + +},{}],81:[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 + } +} + +},{}],82:[function(require,module,exports){ (function (global){(function (){ /*! https://mths.be/punycode v1.3.2 by @mathias */ ;(function(root) { @@ -17524,5202 +18429,5063 @@ function fromByteArray (uint8) { }(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. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var isArray = require('isarray') +},{}],83:[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'; +} +},{}],84:[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. -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 +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(' '); + } -/** - * 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() + 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); + } + that.length = length + } + return str; +}; -/* - * 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 +// 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); + }; } -} -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} + if (process.noDeprecation === true) { + return fn; + } -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') + 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); } - 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) + + 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() {}; } - that.length = length } + return debugs[set]; +}; - 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. + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. * - * The `Uint8Array` prototype remains unmodified. + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) +/* 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; - // 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) + +// 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; } - 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 stylizeNoColor(str, styleType) { + return str; } -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) - } +function arrayToHash(array) { + var hash = {}; - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } + array.forEach(function(val, idx) { + hash[val] = true; + }); - return fromObject(that, value) + return hash; } -/** - * 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 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; } -} -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) + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; } - 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) -} + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); -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 - } + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); } - 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' + // 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); } - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + // 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 length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) + var base = '', array = false, braces = ['{', '}']; - 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) + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; } - 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 + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; } - 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') + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); } - 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) + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); } - 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) + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; } - 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 + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); } - - 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) - } + ctx.seen.push(value); - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } + 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); + }); } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} + ctx.seen.pop(); -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 + return reduceToSingleString(output, base, braces); } -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) +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'); } -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 +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} - 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 +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(''); } } - - if (x < y) return -1 - if (y < x) return 1 - return 0 + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; } -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') +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 (list.length === 0) { - return Buffer.alloc(0) + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length + 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'); } } - - 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') + 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'); } - buf.copy(buffer, pos) - pos += buf.length } - return buffer + + return name + ': ' + str; } -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 +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); - // 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 - } + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } -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. +// 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; - // 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 '' - } +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - if (end === undefined || end > this.length) { - end = this.length - } +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - if (end <= 0) { - return '' - } +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - if (end <= start) { - return '' - } +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - if (!encoding) encoding = 'utf8' +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; - case 'ascii': - return asciiSlice(this, start, end) +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - 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 +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); } +exports.isError = isError; -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 +function isFunction(arg) { + return typeof arg === 'function'; } +exports.isFunction = isFunction; -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 +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; -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 -} +exports.isBuffer = require('./support/isBuffer'); -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) +function objectToString(o) { + return Object.prototype.toString.call(o); } -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 '' +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); } -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 - } +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } +// 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(' '); +} - 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 +// 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)); +}; - if (this === target) return 0 - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) +/** + * 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'); - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; } + return origin; +}; - if (x < y) return -1 - if (y < x) return 1 - return 0 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -// 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) - } +}).call(this)}).call(this,require('_process'),typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":83,"_process":90,"inherits":81}],85:[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 */ - // 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 - } +'use strict' - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') - // 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) - } +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 - throw new TypeError('val must be string, number or Buffer') -} +/** + * 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. -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length + * 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() - 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 - } - } +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } +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 } +} - 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 - } - } +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 { - 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 + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) } + that.length = length } - return -1 + return that } -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} +/** + * 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. + */ -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +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.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +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 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 - } +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') } - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - if (length > strLen / 2) { - length = strLen / 2 + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) } - 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 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 + }) } - return i } -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +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 asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) +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) } -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) } -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) +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 } -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +/** + * 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) } -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { 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 (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } - if (!encoding) encoding = 'utf8' + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + var actual = that.write(string, encoding) - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + 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) + } - case 'ascii': - return asciiWrite(this, string, offset, length) + return that +} - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) +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 +} - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') } -} -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) + 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) } -} -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype } else { - return base64.fromByteArray(buf.slice(start, end)) + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) } + return that } -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) - 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 (that.length === 0) { + return that + } - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint + obj.copy(that, 0, 0, len) + return that + } - 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 (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 (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 + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) } - - res.push(codePoint) - i += bytesPerSequence } - return decodeCodePointsArray(res) + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } -// 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) - ) +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 res + return length | 0 } -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) +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 } - return ret + return Buffer.alloc(+length) } -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - return ret -} -function hexSlice (buf, start, end) { - var len = buf.length + if (a === b) return 0 - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len + var x = a.length + var y = b.length - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } } - return out + + if (x < y) return -1 + if (y < x) return 1 + return 0 } -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) +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 } - 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 +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len + if (list.length === 0) { + return Buffer.alloc(0) } - 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] + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length } } - return newBuf + 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 } -/* - * 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') -} +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 + } -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + var len = string.length + if (len === 0) return 0 - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul + // 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 + } } - - return val } +Buffer.byteLength = byteLength -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } +function slowToString (encoding, start, end) { + var loweredCase = false - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul + // 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 '' } - return val -} + if (end === undefined || end > this.length) { + end = this.length + } -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} + if (end <= 0) { + return '' + } -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} + if (end <= start) { + return '' + } -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) + if (!encoding) encoding = 'utf8' - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} + case 'ascii': + return asciiSlice(this, start, end) -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 + case 'base64': + return base64Slice(this, start, end) - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - return val + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } } -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} - 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.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.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.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.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.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.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) +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.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) +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.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) +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.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } -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') -} + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } -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) + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 } - return offset + byteLength -} + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 -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) - } + if (this === target) return 0 - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF + 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 + } } - return offset + byteLength + if (x < y) return -1 + if (y < x) return 1 + return 0 } -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 -} +// 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 -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 + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 } -} - -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) + 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) } - 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) + // 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 } - 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 + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) } -} -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) + // 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) } - 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 + throw new TypeError('val must be string, number or Buffer') } -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) - } +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length - 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 + 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 } - 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) + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } } - 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 + 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 } - 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 + return -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.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 } -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.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } -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.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } -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) +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining } else { - objectWriteUInt32(this, value, offset, false) + length = Number(length) + if (length > remaining) { + length = remaining + } } - 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') -} + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + if (length > strLen / 2) { + length = strLen / 2 } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 + 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 } -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) } -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 +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } -// 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] +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 { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } - 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 - } + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining - // 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 ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } - if (end <= start) { - return this - } + if (!encoding) encoding = 'utf8' - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - if (!val) val = 0 + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - 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] - } - } + case 'ascii': + return asciiWrite(this, string, offset, length) - return this -} + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) -// HELPER FUNCTIONS -// ================ + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) -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 + '=' + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } - return str } -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } } -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } } -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 - } +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] - // valid lead - leadSurrogate = codePoint + 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 - continue - } + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue + 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 + } + } } - - // 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') + 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 bytes + return decodeCodePointsArray(res) } -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) +// 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() } - return byteArray + + // 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 utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) } - - return byteArray + return ret } -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) -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] + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) } - return i + return ret } -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} +function hexSlice (buf, start, end) { + var len = buf.length -}).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. + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out } -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; +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 +} -// 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; +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end -// 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; -}; + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - if (!this._events) - this._events = {}; + if (end < start) end = start - // 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; - } + 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] } } - handler = this._events[type]; + return newBuf +} - if (isUndefined(handler)) - return false; +/* + * 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') +} - 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); - } +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - return true; -}; + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } -EventEmitter.prototype.addListener = function(type, listener) { - var m; + return val +} - 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(); - } - } +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) } - 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); - } + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul } - g.listener = listener; - this.on(type, g); - - return this; -}; + return val +} -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} - if (!this._events || !this._events[type]) - return this; +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} - list = this._events[type]; - length = list.length; - position = -1; +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if (position < 0) - return this; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - if (this._events.removeListener) - this.emit('removeListener', type, listener); + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul } + mul *= 0x80 - return this; -}; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + return val +} - if (!this._events) - return this; +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - // 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; + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul } + mul *= 0x80 - // 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; - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - listeners = this._events[type]; + return val +} - 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]; +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) +} - return this; -}; +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 +} -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; -}; +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 +} -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -function isFunction(arg) { - return typeof arg === 'function'; + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) } -function isNumber(arg) { - return typeof arg === 'number'; +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) } -function isUndefined(arg) { - return arg === void 0; +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) } -},{}],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] +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} - i += d +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') +} - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} +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) + } - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - 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 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) } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + + 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 } -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 +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 +} - value = Math.abs(value) +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 + } +} - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax +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 { - 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 - } + objectWriteUInt16(this, value, offset, true) } + return offset + 2 +} - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} +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 +} - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} +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[offset + i - d] |= s * 128 +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 } -},{}],84:[function(require,module,exports){ -var toString = {}.toString; +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 +} -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) -},{}],85:[function(require,module,exports){ -(function(exports) { - "use strict"; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; + 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 } - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; - } + 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) } - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; + 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 + } - // 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; - } + return offset + byteLength +} - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value +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 +} - // 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; - } +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 +} - 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; +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 +} - 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; +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 +} - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; +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 { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; + objectWriteUInt32(this, value, offset, false) } + return offset + 4 +} - // 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; +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') +} - 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"; +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 +} - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} - var operatorStartToken = { - "<": true, - ">": true, - "=": true, - "!": true - }; +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 +} - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; +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) +} - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; - } +// 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 - 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 === "_"; + // 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') - function Lexer() { + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start } - 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); - }, + var len = end - start + var i - _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)); - }, + 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 + ) + } - _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("\\'", "'"); - }, + return len +} - _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}; - }, +// 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 + } - _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}; - } - }, + // 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') + } - _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}; - } - } - }, + if (end <= start) { + return this + } - _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; - }, + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - _looksLikeJSON: function(literalString) { - var startingChars = "[{\""; - var jsonLiterals = ["true", "false", "null"]; - var numberLooking = "-0123456789"; + if (!val) val = 0 - 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 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] + } + } - 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; + return this +} - function Parser() { - } +// HELPER FUNCTIONS +// ================ - 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; - }, +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, +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 +} - 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; - }, +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] - _advance: function() { - this.index++; - }, + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) - 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); + // 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 } - }, - 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)); - } - }, + // valid lead + leadSurrogate = codePoint - _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; - } - }, + continue + } - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, + // 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) + } - _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; - } - }, + leadSurrogate = null - _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; - } - }, + // 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') + } + } - _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 - }; - }, + return bytes +} - _parseComparator: function(left, comparator) { - var right = this.expression(bindingPower[comparator]); - return {type: "Comparator", name: comparator, children: [left, right]}; - }, +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 +} - _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(); - } - }, +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - _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; - }, + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } - _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; - } - } - }, + return byteArray +} - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, +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 +} - _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; - } - }, +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, +}).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":79,"buffer":85,"ieee754":87,"isarray":88}],86:[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. - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; - _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; - }, +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[0]); - }, +// 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; - _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; - } - }, +// 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; +}; - _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; - }, +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; - _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; - }, + if (!this._events) + this._events = {}; - _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; - } + // 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 { - return null; + // 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]; - _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; - } - }, + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } - _functionSum: function(resolvedArgs) { - var sum = 0; - var listToSum = resolvedArgs[0]; - for (var i = 0; i < listToSum.length; i++) { - sum += listToSum[i]; + 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 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"; - } - }, + return this; +}; - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - _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; - }, +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, + var fired = false; - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; - } - }, + function g() { + this.removeListener(type, g); - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); - } - }, + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - _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; - }, + g.listener = listener; + this.on(type, g); - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; - } - } - return null; - }, + return this; +}; - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; - _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; - }, + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - _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; - }, + if (!this._events || !this._events[type]) + return this; - _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; - }, + list = this._events[type]; + length = list.length; + position = -1; - 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; + 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; - function compile(stream) { - var parser = new Parser(); - var ast = parser.parse(stream); - return ast; + 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); } - function tokenize(stream) { - var lexer = new Lexer(); - return lexer.tokenize(stream); + 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; } - 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); + // 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; } - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})(typeof exports === "undefined" ? this.jmespath = {} : exports); + listeners = this._events[type]; -},{}],86:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; + 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]; -// 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. + return this; +}; -var cachedSetTimeout; -var cachedClearTimeout; +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; +}; -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); +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 defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); + +function isNumber(arg) { + return typeof arg === 'number'; } -(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 isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +function isUndefined(arg) { + return arg === void 0; } -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); + +},{}],87:[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 clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) } - 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); - } + 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 } -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); +},{}],88:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],89:[function(require,module,exports){ +(function(exports) { + "use strict"; + + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; } else { - queueIndex = -1; + return false; } - if (queue.length) { - drainQueue(); + } + + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; } -} + } -function drainQueue() { - if (draining) { - return; + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } + // 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; } - queueIndex = -1; - len = queue.length; + } + return true; } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} + 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; + } -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]; + 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; } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + } + + 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; + } -// 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 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; + } -function noop() {} + 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 TYPE_NAME_TABLE = { + 0: 'number', + 1: 'any', + 2: 'string', + 3: 'array', + 4: 'object', + 5: 'boolean', + 6: 'expression', + 7: 'null', + 8: 'Array', + 9: 'Array' + }; + + 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 + }; -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; + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; -process.listeners = function (name) { return [] } -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + 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 === "_"; + } -},{}],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. + 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; + }, -'use strict'; + _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); + }, -// 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); -} + _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)); + }, -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; + _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("\\'", "'"); + }, - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } + _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}; + }, - var regexp = /\+/g; - qs = qs.split(sep); + _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}; + } + }, - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } + _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}; + } + } + }, - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } + _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; + }, - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } + 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; + } + } + }; - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); + 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; - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } + function Parser() { } - 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; + 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; + }, - case 'boolean': - return v ? 'true' : 'false'; + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, - case 'number': - return isFinite(v) ? v : ''; + 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; + }, - default: - return ''; - } -}; + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, - 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); + _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."); + } + return node; + 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]}; + } + return this._parseMultiselectList(); + 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); + } + }, - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; + 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]}; + } + // Creating a projection. + this._advance(); + right = this._parseProjectionRHS(rbp); + return {type: "ValueProjection", children: [left, right]}; + 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); + } + this._match(TOK_STAR); + this._match(TOK_RBRACKET); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", children: [left, right]}; + default: + this._errorToken(this._lookaheadToken(0)); + } + }, -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; + _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; + } + }, -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; -} + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, -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'; + _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; + } + }, -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); + _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; + } + }, -},{"./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. + _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 + }; + }, -'use strict'; + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, -// 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); -} + _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(); + } + }, -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; + _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; + }, - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } + _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}; + }, - var regexp = /\+/g; - qs = qs.split(sep); + _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}; + } + }; - 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; + function TreeInterpreter(runtime) { + this.runtime = runtime; } - 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]; - } - } + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, - return obj; -}; + visit: function(node, value) { + var matched, current, result, first, second, field, left, right, collected, i; + switch (node.type) { + case "Field": + if (value !== null && isObject(value)) { + field = value[node.name]; + if (field === undefined) { + return null; + } else { + return field; + } + } + return null; + 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); -},{}],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. + 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); + } + }, -'use strict'; + 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; -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; + if (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } - case 'boolean': - return v ? 'true' : 'false'; + 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; + }, - case 'number': - return isFinite(v) ? v : ''; + 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; + } - default: - return ''; - } -}; + }; -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; + 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}] + } + }; } - 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])); + Runtime.prototype = { + callFunction: function(name, resolvedArgs) { + var functionEntry = this.functionTable[name]; + if (functionEntry === undefined) { + throw new Error("Unknown function: " + name + "()"); } - }).join(sep); + 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) { + var expected = currentSpec + .map(function(typeIdentifier) { + return TYPE_NAME_TABLE[typeIdentifier]; + }) + .join(','); + throw new Error("TypeError: " + name + "() " + + "expected argument " + (i + 1) + + " to be type " + expected + + " but received type " + + TYPE_NAME_TABLE[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; + } + } + }, - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; + }, -},{}],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; + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; + }, -// DOM APIs, for completeness + _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; + } + }, -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(); }; + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, -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); -}; + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[0]); + }, -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; + _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; + }, -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[0]); + }, - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; + _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; + } + }, -// 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); + _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; + }, - immediateIds[id] = true; + _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; + }, - 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); + _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 { - fn.call(null); + return null; } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); + }, - return id; -}; + _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; + } + }, -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. + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, -var punycode = require('punycode'); + _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"; + } + }, -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, -exports.Url = Url; + _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; + }, -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; -} + _functionJoin: function(resolvedArgs) { + var joinChar = resolvedArgs[0]; + var listJoin = resolvedArgs[1]; + return listJoin.join(joinChar); + }, -// Reference: RFC 3986, RFC 1808, RFC 2396 + _functionToArray: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { + return resolvedArgs[0]; + } else { + return [resolvedArgs[0]]; + } + }, -// 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]*$/, + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + _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; + }, - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, - // 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 + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true + + _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; }, - // 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 + + _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; }, - querystring = require('querystring'); -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && isObject(url) && url instanceof Url) return url; + _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; + }, - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} + 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; + } -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + }; + + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; } - 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); + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); } - // 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; - } + 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); } - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { + exports.tokenize = tokenize; + exports.compile = compile; + exports.search = search; + exports.strictDeepEqual = strictDeepEqual; +})(typeof exports === "undefined" ? this.jmespath = {} : exports); - // 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 +},{}],90:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. +// 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. - // 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; - } +var cachedSetTimeout; +var cachedClearTimeout; - // 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); +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; } - - // 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); + 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); + } } - // 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; + +} +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); + } } - // 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 || ''; +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; - // 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] === ']'; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} - // 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; +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(); } - this.hostname = validParts.join('.'); - break; - } } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); + 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]; + } } - - 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('.'); + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); } +}; - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; +// 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 = {}; - // 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; - } - } - } +function noop() {} - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { +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; - // 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); - } - } +process.listeners = function (name) { return [] } +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - // 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 = '/'; - } +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } +},{}],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. - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; +'use strict'; -// 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(); +// 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); } -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; } - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; + var regexp = /\+/g; + qs = qs.split(sep); - 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; - } + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; } - if (this.query && - isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } - var search = this.search || (query && ('?' + query)) || ''; + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } - // 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 = ''; + 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]; + } } - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],92:[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'; - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; - return protocol + host + pathname + search + hash; -}; + case 'boolean': + return v ? 'true' : 'false'; -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} + case 'number': + return isFinite(v) ? v : ''; -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); + default: + return ''; + } }; -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; +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; } - 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 (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 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]; - }); + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - result.href = result.format(); - return result; +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; +} - 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 objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } + return res; +}; - 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]; +},{}],93:[function(require,module,exports){ +'use strict'; - // 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] === ''); - } +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); - 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; - } +},{"./decode":91,"./encode":92}],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. + +'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 (!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 (typeof qs !== 'string' || qs.length === 0) { + return obj; } - // 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 === ''); + var regexp = /\+/g; + qs = qs.split(sep); - // 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--; - } + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; } - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); - // 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(); + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; } } - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + return obj; +}; - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); +},{}],95:[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 ''; } +}; - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; } - //to support request.http - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); + 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); + } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); }; -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; +},{}],96:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"./decode":94,"./encode":95,"dup":93}],97:[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 isString(arg) { - return typeof arg === "string"; +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); +}; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; -function isNull(arg) { - return arg === null; -} -function isNullOrUndefined(arg) { - return arg == null; -} +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; -},{"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 +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); } - }); - }; -} 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 - } -} + // Prevent ids from leaking + exports.clearImmediate(id); + } + }); -},{}],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 (){ + 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":90,"timers":97}],98:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -22741,788 +23507,1357 @@ module.exports = function isBuffer(arg) { // 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])); +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(); } - 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; + 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('.'); } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); + + 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; + } } } - return str; -}; + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { -// 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); - }; + // 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); + } } - 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; + // 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); } - return fn.apply(this, arguments); + 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 = '/'; } - return deprecated; + //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(); +} -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() {}; +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; } } - return debugs[set]; -}; + if (this.query && + isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; -/** - * 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); + 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 = ''; } - // 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; + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; -// 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] -}; + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); -// 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' + return protocol + host + pathname + search + hash; }; +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } +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; + } -function stylizeNoColor(str, styleType) { - return str; -} + 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; -function arrayToHash(array) { - var hash = {}; + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } - array.forEach(function(val, idx) { - hash[val] = true; - }); + // 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]; + }); - return hash; -} + //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; + } -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); + 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; } - return ret; + + 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; } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; + 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] === ''); } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + 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 (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); + 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; } - // 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); + // 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--; + } } - // 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); + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); } } - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); + 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(); + } } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); } - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + //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; +}; - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); +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; +}; - 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); - }); - } +function isString(arg) { + return typeof arg === "string"; +} - ctx.seen.pop(); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - return reduceToSingleString(output, base, braces); +function isNull(arg) { + return arg === null; +} +function isNullOrUndefined(arg) { + return arg == null; } +},{"punycode":82,"querystring":93}],99:[function(require,module,exports){ +"use strict"; -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'); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; +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 -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; + 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(''); } +var _default = bytesToUuid; +exports.default = _default; +},{}],100:[function(require,module,exports){ +"use strict"; -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'); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; } - 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'); - } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; } - 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'); - } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +},{"./v1.js":104,"./v3.js":105,"./v4.js":107,"./v5.js":108}],101:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Array(msg.length); + + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + var i; + var x; + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + var hex; + + for (i = 0; i < length32; i += 8) { + x = input[i >> 5] >>> i % 32 & 0xff; + hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); } - return name + ': ' + str; + return output; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[(len + 64 >>> 9 << 4) + 14] = len; + var i; + var olda; + var oldb; + var oldc; + var oldd; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; } +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ -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); +function bytesToWords(input) { + var i; + var output = []; + output[(input.length >> 2) - 1] = undefined; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - + var length8 = input.length * 8; -// 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; + for (i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } -function isBoolean(arg) { - return typeof arg === 'boolean'; + return output; } -exports.isBoolean = isBoolean; +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; -function isNullOrUndefined(arg) { - return arg == null; +function safeAdd(x, y) { + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; } -exports.isNullOrUndefined = isNullOrUndefined; +/* + * Bitwise rotate a 32-bit number to the left. + */ -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; -function isString(arg) { - return typeof arg === 'string'; +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; } -exports.isString = isString; +/* + * These functions implement the four basic operations the algorithm uses. + */ -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } -exports.isUndefined = isUndefined; -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); } -exports.isRegExp = isRegExp; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); } -exports.isObject = isObject; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); } -exports.isDate = isDate; -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +var _default = md5; +exports.default = _default; +},{}],102:[function(require,module,exports){ +"use strict"; -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; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, +// find the complete implementation of crypto (msCrypto) on IE11. +var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto); +var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef -exports.isBuffer = require('./support/isBuffer'); +function rng() { + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } -function objectToString(o) { - return Object.prototype.toString.call(o); + return getRandomValues(rnds8); } +},{}],103:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + case 1: + return x ^ y ^ z; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + case 2: + return x & y ^ x & z ^ y & z; -// 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(' '); + case 3: + return x ^ y ^ z; + } } +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} -// 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)); -}; - +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; -/** - * 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'); + if (typeof bytes == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + bytes = new Array(msg.length); - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } - return origin; -}; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} + bytes.push(0x80); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); -}).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'); + for (var i = 0; i < N; i++) { + M[i] = new Array(16); + + for (var j = 0; j < 16; j++) { + M[i][j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + } -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; -module.exports = uuid; + for (var i = 0; i < N; i++) { + var W = new Array(80); -},{"./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); -} + for (var t = 0; t < 16; t++) W[t] = M[i][t]; -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(''); -} + for (var t = 16; t < 80; t++) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } -module.exports = bytesToUuid; + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; -},{}],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 + for (var t = 0; t < 80; t++) { + var s = Math.floor(t / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } -// 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)); + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } -if (getRandomValues) { - // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto - var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} - 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); +var _default = sha1; +exports.default = _default; +},{}],104:[function(require,module,exports){ +"use strict"; - 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; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - return rnds; - }; -} +var _rng = _interopRequireDefault(require("./rng.js")); + +var _bytesToUuid = _interopRequireDefault(require("./bytesToUuid.js")); -},{}],101:[function(require,module,exports){ -var rng = require('./lib/rng'); -var bytesToUuid = require('./lib/bytesToUuid'); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // **`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 _clockseq; // Previous uuid creation time + + var _lastMSecs = 0; -var _lastNSecs = 0; +var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details -// 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 + 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(); + var seedBytes = options.random || (options.rng || _rng.default)(); + 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] - ]; + 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, + } // 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 + + 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; + 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 - // 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 + } // 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 + - // 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'); + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; - _clockseq = clockseq; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; + msecs += 12219292800000; // `time_low` - // `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; + b[i++] = tl & 0xff; // `time_mid` - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` - // `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; + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - // `clock_seq_low` - b[i++] = clockseq & 0xff; + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` - // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } - return buf ? buf : bytesToUuid(b); + return buf ? buf : (0, _bytesToUuid.default)(b); +} + +var _default = v1; +exports.default = _default; +},{"./bytesToUuid.js":99,"./rng.js":102}],105:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; +},{"./md5.js":101,"./v35.js":106}],106:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +exports.URL = exports.DNS = void 0; + +var _bytesToUuid = _interopRequireDefault(require("./bytesToUuid.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function uuidToBytes(uuid) { + // Note: We assume we're being passed a valid uuid string + var bytes = []; + uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) { + bytes.push(parseInt(hex, 16)); + }); + return bytes; +} + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + var bytes = new Array(str.length); + + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + var generateUUID = function (value, namespace, buf, offset) { + var off = buf && offset || 0; + if (typeof value == 'string') value = stringToBytes(value); + if (typeof namespace == 'string') namespace = uuidToBytes(namespace); + if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); + if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); // Per 4.3 + + var bytes = hashfunc(namespace.concat(value)); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + for (var idx = 0; idx < 16; ++idx) { + buf[off + idx] = bytes[idx]; + } + } + + return buf || (0, _bytesToUuid.default)(bytes); + }; // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; } +},{"./bytesToUuid.js":99}],107:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); -module.exports = v1; +var _bytesToUuid = _interopRequireDefault(require("./bytesToUuid.js")); -},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(require,module,exports){ -var rng = require('./lib/rng'); -var bytesToUuid = require('./lib/bytesToUuid'); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { var i = buf && offset || 0; - if (typeof(options) == 'string') { + if (typeof options == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } + options = options || {}; - var rnds = options.random || (options.rng || rng)(); + var rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + - // 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; + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } - return buf || bytesToUuid(rnds); + return buf || (0, _bytesToUuid.default)(rnds); } -module.exports = v4; +var _default = v4; +exports.default = _default; +},{"./bytesToUuid.js":99,"./rng.js":102}],108:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); -},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(require,module,exports){ +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; +},{"./sha1.js":103,"./v35.js":106}],109:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LRU_1 = require("./utils/LRU"); @@ -23554,13 +24889,16 @@ var EndpointCache = /** @class */ (function () { var now = Date.now(); var records = this.cache.get(keyString); if (records) { - for (var i = 0; i < records.length; i++) { + for (var i = records.length-1; i >= 0; i--) { var record = records[i]; if (record.Expire < now) { - this.cache.remove(keyString); - return undefined; + records.splice(i, 1); } } + if (records.length === 0) { + this.cache.remove(keyString); + return undefined; + } } return records; }; @@ -23592,7 +24930,7 @@ var EndpointCache = /** @class */ (function () { return EndpointCache; }()); exports.EndpointCache = EndpointCache; -},{"./utils/LRU":104}],104:[function(require,module,exports){ +},{"./utils/LRU":110}],110:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedListNode = /** @class */ (function () { @@ -23700,8 +25038,8 @@ var LRUCache = /** @class */ (function () { return LRUCache; }()); exports.LRUCache = LRUCache; -},{}],105:[function(require,module,exports){ -// AWS SDK for JavaScript v2.553.0 +},{}],111:[function(require,module,exports){ +// AWS SDK for JavaScript v2.1189.0 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt require('./browser_loader'); @@ -23727,15 +25065,8 @@ if (typeof self !== 'undefined') self.AWS = AWS; } 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]); +},{"../apis/connect-2017-02-15.min":3,"./browser_loader":16,"./core":19}]},{},[111]); @@ -23750,7 +25081,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function() { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -23807,11 +25138,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi DESCRIBE_SESSION: "AgentAppService.VoiceId.describeSession", UPDATE_SESSION: "AgentAppService.VoiceId.updateSession", START_VOICE_ID_SESSION: "AgentAppService.Nasa.startVoiceIdSession", - LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations", - START_CONTACT_RECORDING: "AgentAppService.Acs.StartContactRecording", - STOP_CONTACT_RECORDING: "AgentAppService.Acs.StopContactRecording", - SUSPEND_CONTACT_RECORDING: "AgentAppService.Acs.SuspendContactRecording", - RESUME_CONTACT_RECORDING: "AgentAppService.Acs.ResumeContactRecording" + LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations" }; /**--------------------------------------------------------------- @@ -24266,14 +25593,14 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; connect.core = {}; connect.core.initialized = false; - connect.version = "2.2.0"; + connect.version = "2.3.0"; connect.DEFAULT_BATCH_SIZE = 500; var CCP_SYN_TIMEOUT = 1000; // 1 sec @@ -24625,7 +25952,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi }); }); }; - + /** * 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. @@ -25756,12 +27083,17 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * 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. + * + * "caseId" is an optional parameter which is passed when a task is created from a Kesytone case */ - connect.core.activateChannelWithViewType = function (viewType, mediaType, source) { + connect.core.activateChannelWithViewType = function (viewType, mediaType, source, caseId) { const data = { viewType, mediaType }; if (source) { data.source = source; } + if (caseId) { + data.caseId = caseId; + } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, data @@ -26091,7 +27423,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -26136,6 +27468,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi 'authorize_success', 'authorize_retries_exhausted', 'cti_authorize_retries_exhausted', + 'click_stream_data' ]); /**--------------------------------------------------------------- @@ -26461,7 +27794,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi /***/ 286: /***/ (() => { -!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){"use strict";var o=t(1),r="NULL",i="CLIENT_LOGGER",c="DEBUG",s=2e3,a="aws/subscribe",u="aws/unsubscribe",l="aws/heartbeat",f="connected",p="disconnected";function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var b={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return b.assertTrue(null!==e&&void 0!==d(e),Object(o.sprintf)("%s must be provided",n||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==d(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},g=new RegExp("^(wss://)\\w*");b.validWSUrl=function(e){return g.test(e)},b.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},b.assertIsObject=function(e,n){if(!b.isObject(e))throw new Error(n+" is not an object!")},b.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},b.isNetworkOnline=function(){return navigator.onLine},b.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var y=b;function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,n){return!n||"object"!==m(n)&&"function"!=typeof n?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):n}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function k(e,n){return(k=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function v(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function w(e,n){for(var t=0;t=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var n=e.prefix||"";return this._logsDestination===c?this.consoleLoggerWrapper:new N(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||O.DEBUG,this._clientLogger=n.logger||null,this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}}]),e}(),W=function(){function e(){v(this,e)}return C(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),N=function(e){function n(e){var t;return v(this,n),(t=S(this,h(n).call(this))).prefix=e||"",t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&k(e,n)}(n,W),C(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:s;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}var n,t,o;return n=e,(t=[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout(function(){e._execute()},this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}}])&&F(n.prototype,t),o&&F(n,o),e}();t.d(n,"a",function(){return R});var x=function(){var e=E.getLogger({}),n=y.isNetworkOnline(),t={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},c={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},b={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},g=new L(function(){U()}),m=new Set([a,u,l]),S=setInterval(function(){if(n!==y.isNetworkOnline()){if(!(n=y.isNetworkOnline()))return void J(e.info("Network offline"));var t=O();n&&(!t||w(t,WebSocket.CLOSING)||w(t,WebSocket.CLOSED))&&(J(e.info("Network online, connecting to WebSocket server")),U())}},250),h=function(n,t){n.forEach(function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}})},k=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},v=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+k(t.primary)+" | Secondary WebSocket: "+k(t.secondary)))},w=function(e,n){return e&&e.readyState===n},C=function(e){return w(e,WebSocket.OPEN)},T=function(e){return null===e||void 0===e.readyState||w(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},I=function(){return C(O())},W=function(){if(i.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void U();I()?(J(e.debug("Sending heartbeat")),O().send(G(l)),i.pendingResponse=!0):(J(e.warn("Failed to send heartbeat since WebSocket is not open")),v("sendHeartBeat"),U())},N=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},_=function(){b.consecutiveFailedSubscribeAttempts=0,b.consecutiveNoResponseRequest=0,clearInterval(b.responseCheckIntervalId),clearInterval(b.reSubscribeIntervalId)},F=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},x=function(){try{J(e.info("WebSocket connection established!")),v("webSocketOnOpen"),null!==o.connState&&o.connState!==p||h(c.connectionGain),o.connState=f;var n=Date.now();h(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?n-r.noOpenConnectionsTimestamp:null}),F(),N(),O().openTimestamp=Date.now(),0===d.subscribed.size&&C(t.secondary)&&D(t.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(C(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach(function(e){d.subscriptionHistory.add(e),d.pending.add(e)}),d.subscribed.clear(),A()),W(),i.intervalHandle=setInterval(W,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U()},a)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},R=function(n){v("webSocketOnError"),J(e.error("WebSocketManager Error, error_event: ",JSON.stringify(n))),U()},j=function(n){var o=JSON.parse(n.data);switch(o.topic){case a:if(J(e.debug("Subscription Message received from webSocket server",n.data)),b.requestCompleted=!0,b.consecutiveNoResponseRequest=0,"success"===o.content.status)b.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)}),0===d.subscriptionHistory.size?C(t.secondary)&&(J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),D(t.primary,"[Primary WebSocket] Closing WebSocket")):A(),h(c.subscriptionUpdate,o);else{if(clearInterval(b.reSubscribeIntervalId),++b.consecutiveFailedSubscribeAttempts,5===b.consecutiveFailedSubscribeAttempts)return h(c.subscriptionFailure,o),void(b.consecutiveFailedSubscribeAttempts=0);b.reSubscribeIntervalId=setInterval(function(){A()},500)}break;case l:J(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(J(e.debug("Message received for topic "+o.topic)),C(t.primary)&&C(t.secondary)&&0===d.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));h(c.allMessage,o),c.topic.has(o.topic)&&h(c.topic.get(o.topic),o)}else o.message?J(e.warn("WebSocketManager Message Error",o)):J(e.warn("Invalid incoming message",o))}},A=function n(){if(b.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void h(c.subscriptionFailure,y.getSubscriptionResponse(a,!1,Array.from(d.pending)));I()?0!==Array.from(d.pending).length&&(clearInterval(b.responseCheckIntervalId),O().send(G(a,{topics:Array.from(d.pending)})),b.requestCompleted=!1,b.responseCheckIntervalId=setInterval(function(){b.requestCompleted||(++b.consecutiveNoResponseRequest,n())},1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},D=function(n,t){w(n,WebSocket.CONNECTING)||w(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+k(n)))},M=function(e){D(t.primary,"[Primary] WebSocket "+e),D(t.secondary,"[Secondary] WebSocket "+e)},P=function(){r.connectWebSocketRetryCount++;var n=y.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=s.connConfig.urlConnValidTime?(J(e.debug("Scheduling WebSocket reinitialization, after delay "+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return q()},n),o.exponentialBackOffTime*=2):(J(e.warn("WebSocket URL cannot be used to establish connection")),U())},H=function(n){N(),_(),J(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(S),h(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),F()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(y.isObject(n)&&y.isObject(n.webSocketTransport)&&y.isNonEmptyString(n.webSocketTransport.url)&&y.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){if(y.isNetworkOnline())if(o.websocketInitFailed)J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return N(),J(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then(function(n){return s.promiseCompleted=!0,J(e.debug("Successfully fetched webSocket connection configuration",n)),z(n)?(s.connConfig=n,s.connConfig.urlConnValidTime=Date.now()+85e3,g.connected(),q()):(H("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return s.promiseCompleted=!0,J(e.error("Failed to fetch webSocket connection configuration",n)),y.isNetworkFailure(n)?(J(e.info("Retrying fetching new WebSocket connection configuration")),g.retry()):H("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else J(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},q=function(){if(o.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!y.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.info("Initializing Websocket Manager")),v("initWebSocket");try{if(z(s.connConfig)){var n=null;return C(t.primary)?(J(e.debug("Primary Socket connection is already open")),w(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),t.secondary=B()),n=t.secondary):(w(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){C(n)||P()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),H("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(s.connConfig.webSocketTransport.url);return n.addEventListener("open",x),n.addEventListener("message",j),n.addEventListener("error",R),n.addEventListener("close",function(i){return function(n,i){J(e.info("Socket connection is closed",JSON.stringify(n))),v("webSocketOnClose before-cleanup"),h(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),T(t.primary)&&(t.primary=null),T(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(C(t.primary)||C(t.secondary)?T(t.primary)&&C(t.secondary)&&(J(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===p?J(e.info("Ignoring connectionLost callback invocation")):(h(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=p,U()),v("webSocketOnClose after-cleanup"))}(i,n)}),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(y.assertTrue(y.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.initFailure.add(e),o.websocketInitFailed&&e(),function(){return c.initFailure.delete(e)}},this.onConnectionOpen=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionOpen.add(e),function(){return c.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionClose.add(e),function(){return c.connectionClose.delete(e)}},this.onConnectionGain=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionGain.add(e),I()&&e(),function(){return c.connectionGain.delete(e)}},this.onConnectionLost=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionLost.add(e),o.connState===p&&e(),function(){return c.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionFailure.add(e),function(){return c.subscriptionFailure.delete(e)}},this.onMessage=function(e,n){return y.assertNotNull(e,"topicName"),y.assertTrue(y.isFunction(n),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(n):c.topic.set(e,new Set([n])),function(){return c.topic.get(e).delete(n)}},this.onAllMessage=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){y.assertNotNull(e,"topics"),y.assertIsList(e),e.forEach(function(e){d.subscribed.has(e)||d.pending.add(e)}),b.consecutiveNoResponseRequest=0,A()},this.sendMessage=function(n){if(y.assertIsObject(n,"payload"),void 0===n.topic||m.has(n.topic))J(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}I()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){N(),_(),o.reconnectWebSocket=!1,clearInterval(S),M("User request to close WebSocket")},this.terminateWebSocketManager=H},R={create:function(){return new x},setGlobalConfig:function(e){var n=e.loggerConfig;E.updateLoggerConfig(n)},LogLevel:O,Logger:T}},function(e,n,t){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,s,a,u,l,f,p,d=1,b=e.length,g="";for(o=0;o=0),s.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,s.width?parseInt(s.width):0);break;case"e":t=s.precision?parseFloat(t).toExponential(s.precision):parseFloat(t).toExponential();break;case"f":t=s.precision?parseFloat(t).toFixed(s.precision):parseFloat(t);break;case"g":t=s.precision?String(Number(t.toPrecision(s.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=s.precision?t.substring(0,s.precision):t;break;case"t":t=String(!!t),t=s.precision?t.substring(0,s.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=s.precision?t.substring(0,s.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=s.precision?t.substring(0,s.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(s.type)?g+=t:(!r.number.test(s.type)||f&&!s.sign?p="":(p=f?"+":"-",t=t.toString().replace(r.sign,"")),u=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",l=s.width-(p+t).length,a=s.width&&l>0?u.repeat(l):"",g+=s.align?p+t+a:"0"===u?p+a+t:a+p+t)}return g}(function(e){if(s[e])return s[e];var n,t=e,o=[],i=0;for(;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],a=n[2],u=[];if(null===(u=r.key.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(a=a.substring(u[0].length));)if(null!==(u=r.key_access.exec(a)))c.push(u[1]);else{if(null===(u=r.index_access.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return s[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var s=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); +!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",a=2e3,s="AMZ_WEB_SOCKET_MANAGER:",u="Network offline",l="Network online, connecting to WebSocket server",f="Network offline, ignoring this getWebSocketConnConfig request",d="Heartbeat response not received",p="Heartbeat response received",g="Sending heartbeat",b="Failed to send heartbeat since WebSocket is not open",y="WebSocket connection established!",m="WebSocket connection is closed",v="WebSocketManager Error, error_event: ",S="Scheduling WebSocket reinitialization, after delay ",h="WebSocket URL cannot be used to establish connection",k="WebSocket Initialization failed - Terminating and cleaning subscriptions",w="Terminating WebSocket Manager",C="Fetching new WebSocket connection configuration",L="Successfully fetched webSocket connection configuration",T="Failed to fetch webSocket connection configuration",O="Retrying fetching new WebSocket connection configuration",W="Initializing Websocket Manager",I="Initializing Websocket Manager Failed!",N="Websocket connection open",_="Websocket connection close",E="Websocket connection gain",F="Websocket connection lost",A="Websocket subscription failure",R="Reset Websocket state",x="WebSocketManager Message Error",D="Message received for topic ",j="Invalid incoming message",M="WebsocketManager invoke callbacks for topic success ",G="aws/subscribe",z="aws/unsubscribe",P="aws/heartbeat",H="connected",U="disconnected";function q(e){return(q="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 J={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return J.assertTrue(null!==e&&void 0!==q(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"!==q(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},B=new RegExp("^(wss://)\\w*");J.validWSUrl=function(e){return B.test(e)},J.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},J.assertIsObject=function(e,n){if(!J.isObject(e))throw new Error(n+" is not an object!")},J.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)},J.isNetworkOnline=function(){return navigator.onLine},J.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var V=J;function X(e,n){return!n||"object"!==Z(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 $(e){return($=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function K(e,n){return(K=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function Z(e){return(Z="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 Q(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function Y(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||te;return this._logsDestination===c?this.consoleLoggerWrapper:new ce(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||oe.INFO,this._advancedLogWriter="warn",n.advancedLogWriter&&(this._advancedLogWriter=n.advancedLogWriter),n.customizedLogger&&"object"===Z(n.customizedLogger)&&(this.useClientLogger=!0),this._clientLogger=n.logger||this.selectLogger(n),this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}},{key:"selectLogger",value:function(e){return e.customizedLogger&&"object"===Z(e.customizedLogger)?e.customizedLogger:e.useDefaultLogger?(this.consoleLoggerWrapper=ae(),this.consoleLoggerWrapper):null}}]),e}(),ie=function(){function e(){Q(this,e)}return ee(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}},{key:"advancedLog",value:function(){}}]),e}(),ce=function(e){function n(e){var t;return Q(this,n),(t=X(this,$(n).call(this))).prefix=e||te,t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&K(e,n)}(n,ie),ee(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:a;!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}},{key:"getIsConnected",value:function(){return!this.numAttempts}}])&&ue(n.prototype,t),o&&ue(n,o),e}();t.d(n,"a",function(){return de});var fe=function(){var e=se.getLogger({prefix:s}),n=V.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},a={connConfig:null,promiseHandle:null,promiseCompleted:!0},q={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},J={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},B=new le(function(){he()}),X=new Set([G,z,P]),$=setInterval(function(){if(n!==V.isNetworkOnline()){if(!(n=V.isNetworkOnline()))return e.advancedLog(u),void Ce(e.info(u));var t=te();n&&(!t||Y(t,WebSocket.CLOSING)||Y(t,WebSocket.CLOSED))&&(e.advancedLog(l),Ce(e.info(l)),he())}},250),K=function(n,t){n.forEach(function(n){try{n(t)}catch(n){Ce(e.error("Error executing callback",n))}})},Z=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"}},Q=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";Ce(e.debug("["+n+"] Primary WebSocket: "+Z(t.primary)+" | Secondary WebSocket: "+Z(t.secondary)))},Y=function(e,n){return e&&e.readyState===n},ee=function(e){return Y(e,WebSocket.OPEN)},ne=function(e){return null===e||void 0===e.readyState||Y(e,WebSocket.CLOSED)},te=function(){return null!==t.secondary?t.secondary:t.primary},oe=function(){return ee(te())},re=function(){if(i.pendingResponse)return e.advancedLog(d),Ce(e.warn(d)),clearInterval(i.intervalHandle),i.pendingResponse=!1,void he();oe()?(Ce(e.debug(g)),te().send(ve(P)),i.pendingResponse=!0):(e.advancedLog(b),Ce(e.warn(b)),Q("sendHeartBeat"),he())},ie=function(){e.advancedLog(R),o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},ce=function(){J.consecutiveFailedSubscribeAttempts=0,J.consecutiveNoResponseRequest=0,clearInterval(J.responseCheckIntervalId),clearInterval(J.reSubscribeIntervalId)},ae=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},ue=function(){B.connected();try{e.advancedLog(y),Ce(e.info(y)),Q("webSocketOnOpen"),null!==o.connState&&o.connState!==U||K(c.connectionGain),o.connState=H;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}),ae(),ie(),te().openTimestamp=Date.now(),0===q.subscribed.size&&ee(t.secondary)&&ge(t.primary,"[Primary WebSocket] Closing WebSocket"),(q.subscribed.size>0||q.pending.size>0)&&(ee(t.secondary)&&Ce(e.info("Subscribing secondary websocket to topics of primary websocket")),q.subscribed.forEach(function(e){q.subscriptionHistory.add(e),q.pending.add(e)}),q.subscribed.clear(),pe()),re(),i.intervalHandle=setInterval(re,1e4);var s=1e3*a.connConfig.webSocketTransport.transportLifeTimeInSeconds;Ce(e.debug("Scheduling WebSocket manager reconnection, after delay "+s+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){Ce(e.debug("Starting scheduled WebSocket manager reconnection")),he()},s)}catch(n){Ce(e.error("Error after establishing WebSocket connection",n))}},fe=function(n){Q("webSocketOnError"),e.advancedLog(v,JSON.stringify(n)),Ce(e.error(v,JSON.stringify(n))),B.getIsConnected()?he():B.retry()},de=function(n){var o=JSON.parse(n.data);switch(o.topic){case G:if(Ce(e.debug("Subscription Message received from webSocket server",n.data)),J.requestCompleted=!0,J.consecutiveNoResponseRequest=0,"success"===o.content.status)J.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){q.subscriptionHistory.delete(e),q.pending.delete(e),q.subscribed.add(e)}),0===q.subscriptionHistory.size?ee(t.secondary)&&(Ce(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),ge(t.primary,"[Primary WebSocket] Closing WebSocket")):pe(),K(c.subscriptionUpdate,o);else{if(clearInterval(J.reSubscribeIntervalId),++J.consecutiveFailedSubscribeAttempts,5===J.consecutiveFailedSubscribeAttempts)return K(c.subscriptionFailure,o),void(J.consecutiveFailedSubscribeAttempts=0);J.reSubscribeIntervalId=setInterval(function(){pe()},500)}break;case P:Ce(e.debug(p)),i.pendingResponse=!1;break;default:if(o.topic){if(e.advancedLog(D,o.topic),Ce(e.debug(D+o.topic)),ee(t.primary)&&ee(t.secondary)&&0===q.subscriptionHistory.size&&this===t.primary)return void Ce(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void Ce(e.warn("No registered callback listener for Topic",o.topic));e.advancedLog(M,o.topic),K(c.allMessage,o),c.topic.has(o.topic)&&K(c.topic.get(o.topic),o)}else o.message?(e.advancedLog(x,o),Ce(e.warn(x,o))):(e.advancedLog(j,o),Ce(e.warn(j,o)))}},pe=function n(){if(J.consecutiveNoResponseRequest>3)return Ce(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void K(c.subscriptionFailure,V.getSubscriptionResponse(G,!1,Array.from(q.pending)));oe()?0!==Array.from(q.pending).length&&(clearInterval(J.responseCheckIntervalId),te().send(ve(G,{topics:Array.from(q.pending)})),J.requestCompleted=!1,J.responseCheckIntervalId=setInterval(function(){J.requestCompleted||(++J.consecutiveNoResponseRequest,n())},1e3)):Ce(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},ge=function(n,t){Y(n,WebSocket.CONNECTING)||Y(n,WebSocket.OPEN)?n.close(1e3,t):Ce(e.warn("Ignoring WebSocket Close request, WebSocket State: "+Z(n)))},be=function(e){ge(t.primary,"[Primary] WebSocket "+e),ge(t.secondary,"[Secondary] WebSocket "+e)},ye=function(){r.connectWebSocketRetryCount++;var n=V.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=a.connConfig.urlConnValidTime?(e.advancedLog(S),Ce(e.debug(S+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return ke()},n),o.exponentialBackOffTime*=2):(e.advancedLog(h),Ce(e.warn(h)),he())},me=function(n){ie(),ce(),e.advancedLog(k,n),Ce(e.error(k)),o.websocketInitFailed=!0,be(w),clearInterval($),K(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),ae()},ve=function(e,n){return JSON.stringify({topic:e,content:n})},Se=function(n){return!!(V.isObject(n)&&V.isObject(n.webSocketTransport)&&V.isNonEmptyString(n.webSocketTransport.url)&&V.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(Ce(e.error("Invalid WebSocket Connection Configuration",n)),!1)},he=function(){if(!V.isNetworkOnline())return e.advancedLog(f),void Ce(e.info(f));if(o.websocketInitFailed)Ce(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(a.promiseCompleted)return ie(),e.advancedLog(C),Ce(e.info(C)),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),a.promiseCompleted=!1,a.promiseHandle=c.getWebSocketTransport(),a.promiseHandle.then(function(n){return a.promiseCompleted=!0,e.advancedLog(L),Ce(e.debug(L,n)),Se(n)?(a.connConfig=n,a.connConfig.urlConnValidTime=Date.now()+85e3,ke()):(me("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return a.promiseCompleted=!0,e.advancedLog(T),Ce(e.error(T,n)),V.isNetworkFailure(n)?(e.advancedLog(O+JSON.stringify(n)),Ce(e.info(O+JSON.stringify(n))),B.retry()):me("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});Ce(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}},ke=function(){if(o.websocketInitFailed)return Ce(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!V.isNetworkOnline())return Ce(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};e.advancedLog(W),Ce(e.info(W)),Q("initWebSocket");try{if(Se(a.connConfig)){var n=null;return ee(t.primary)?(Ce(e.debug("Primary Socket connection is already open")),Y(t.secondary,WebSocket.CONNECTING)||(Ce(e.debug("Establishing a secondary web-socket connection")),B.numAttempts=0,t.secondary=we()),n=t.secondary):(Y(t.primary,WebSocket.CONNECTING)||(Ce(e.debug("Establishing a primary web-socket connection")),t.primary=we()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){ee(n)||ye()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return Ce(e.error("Error Initializing web-socket-manager",n)),me("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},we=function(){var n=new WebSocket(a.connConfig.webSocketTransport.url);return n.addEventListener("open",ue),n.addEventListener("message",de),n.addEventListener("error",fe),n.addEventListener("close",function(i){return function(n,i){e.advancedLog(m,JSON.stringify(n)),Ce(e.info(m,JSON.stringify(n))),Q("webSocketOnClose before-cleanup"),K(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),ne(t.primary)&&(t.primary=null),ne(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(ee(t.primary)||ee(t.secondary)?ne(t.primary)&&ee(t.secondary)&&(Ce(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(Ce(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===U?Ce(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=U,he()),Q("webSocketOnClose after-cleanup"))}(i,n)}),n},Ce=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(V.assertTrue(V.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,he();Ce(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(n){return e.advancedLog(I),V.assertTrue(V.isFunction(n),"cb must be a function"),c.initFailure.add(n),o.websocketInitFailed&&n(),function(){return c.initFailure.delete(n)}},this.onConnectionOpen=function(n){return e.advancedLog(N),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionOpen.add(n),function(){return c.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return e.advancedLog(_),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionClose.add(n),function(){return c.connectionClose.delete(n)}},this.onConnectionGain=function(n){return e.advancedLog(E),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionGain.add(n),oe()&&n(),function(){return c.connectionGain.delete(n)}},this.onConnectionLost=function(n){return e.advancedLog(F),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionLost.add(n),o.connState===U&&n(),function(){return c.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(e){return V.assertTrue(V.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(n){return e.advancedLog(A),V.assertTrue(V.isFunction(n),"cb must be a function"),c.subscriptionFailure.add(n),function(){return c.subscriptionFailure.delete(n)}},this.onMessage=function(e,n){return V.assertNotNull(e,"topicName"),V.assertTrue(V.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 V.assertTrue(V.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){V.assertNotNull(e,"topics"),V.assertIsList(e),e.forEach(function(e){q.subscribed.has(e)||q.pending.add(e)}),J.consecutiveNoResponseRequest=0,pe()},this.sendMessage=function(n){if(V.assertIsObject(n,"payload"),void 0===n.topic||X.has(n.topic))Ce(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void Ce(e.warn("Error stringify message",n))}oe()?te().send(n):Ce(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){ie(),ce(),o.reconnectWebSocket=!1,clearInterval($),be("User request to close WebSocket")},this.terminateWebSocketManager=me},de={create:function(){return new fe},setGlobalConfig:function(e){var n=e&&e.loggerConfig;se.updateLoggerConfig(n)},LogLevel:oe,Logger:ne}},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,a,s,u,l,f,d,p=1,g=e.length,b="";for(o=0;o=0),a.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,a.width?parseInt(a.width):0);break;case"e":t=a.precision?parseFloat(t).toExponential(a.precision):parseFloat(t).toExponential();break;case"f":t=a.precision?parseFloat(t).toFixed(a.precision):parseFloat(t);break;case"g":t=a.precision?String(Number(t.toPrecision(a.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=a.precision?t.substring(0,a.precision):t;break;case"t":t=String(!!t),t=a.precision?t.substring(0,a.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=a.precision?t.substring(0,a.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=a.precision?t.substring(0,a.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(a.type)?b+=t:(!r.number.test(a.type)||f&&!a.sign?d="":(d=f?"+":"-",t=t.toString().replace(r.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(d+t).length,s=a.width&&l>0?u.repeat(l):"",b+=a.align?d+t+s:"0"===u?d+s+t:s+d+t)}return b}(function(e){if(a[e])return a[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=[],s=n[2],u=[];if(null===(u=r.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(s=s.substring(u[0].length));)if(null!==(u=r.key_access.exec(s)))c.push(u[1]);else{if(null===(u=r.index_access.exec(s)))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 a[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var a=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 @@ -26476,7 +27809,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -27165,7 +28498,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -27261,7 +28594,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -27370,7 +28703,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -27406,7 +28739,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -27503,7 +28836,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -27742,7 +29075,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -28552,7 +29885,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi /*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ (function() { - var ctx = this || window; + var ctx = this || globalThis; var sprintf = function() { if (!sprintf.cache.hasOwnProperty(arguments[0])) { @@ -28699,7 +30032,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function() { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -29035,7 +30368,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function() { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -29208,7 +30541,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -29704,6 +31037,13 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi }); }; + connect.publishClickStreamData = function(report) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.CLICK_STREAM_DATA, + data: report + }); + }; + connect.publishClientSideLogs = function(logs) { var bus = connect.core.getEventBus(); bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); @@ -29860,35 +31200,40 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi 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); + var instance = new Error(connect.vsprintf(format, args)); + Object.setPrototypeOf(instance, connect.ValueError.prototype); + return instance; }; - connect.ValueError.prototype = Object.create(connect.BaseError.prototype); - connect.ValueError.prototype.constructor = connect.ValueError; + Object.setPrototypeOf(connect.ValueError.prototype, Error.prototype); + Object.setPrototypeOf(connect.ValueError, Error); + connect.ValueError.prototype.name = 'ValueError'; connect.NotImplementedError = function () { var args = Array.prototype.slice.call(arguments, 0); var format = args.shift(); - connect.BaseError.call(this, format, args); + var instance = new Error(connect.vsprintf(format, args)); + Object.setPrototypeOf(instance, connect.NotImplementedError.prototype); + return instance; }; - connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype); - connect.NotImplementedError.prototype.constructor = connect.NotImplementedError; + Object.setPrototypeOf(connect.NotImplementedError.prototype, Error.prototype); + Object.setPrototypeOf(connect.NotImplementedError, Error); + connect.NotImplementedError.prototype.name = '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; + var instance = new Error(connect.vsprintf(format, args)); + Object.setPrototypeOf(instance, connect.StateError.prototype); + return instance; + } + Object.setPrototypeOf(connect.StateError.prototype, Error.prototype); + Object.setPrototypeOf(connect.StateError, Error); + connect.StateError.prototype.name = 'StateError'; + + connect.VoiceIdError = function(type, message, err){ var error = {}; @@ -29919,7 +31264,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/agent-app/agent-app.js b/src/agent-app/agent-app.js index 52e2eb49..09de4caf 100644 --- a/src/agent-app/agent-app.js +++ b/src/agent-app/agent-app.js @@ -1,5 +1,5 @@ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/agent-app/app-registry.js b/src/agent-app/app-registry.js index 47fd1c03..6da96d8a 100644 --- a/src/agent-app/app-registry.js +++ b/src/agent-app/app-registry.js @@ -1,5 +1,5 @@ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; diff --git a/src/api.js b/src/api.js index e6dd9415..f9c859d1 100644 --- a/src/api.js +++ b/src/api.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -136,7 +136,6 @@ 'api', 'disconnect' ]); - /*---------------------------------------------------------------- * enum ChannelType @@ -181,6 +180,15 @@ 'other' ]); + /*---------------------------------------------------------------- + * enum for ClickType + */ + connect.ClickType = connect.makeEnum([ + 'Accept', + 'Reject', + 'Hangup' + ]); + /*---------------------------------------------------------------- * enum for VoiceIdErrorTypes */ @@ -254,7 +262,7 @@ ]); /*---------------------------------------------------------------- - * enum for contact flow authentication decision + * enum for contact flow authentication decision */ connect.ContactFlowAuthenticationDecision = connect.makeEnum([ "Authenticated", @@ -278,7 +286,7 @@ ]); /*---------------------------------------------------------------- - * enum for VoiceId EnrollmentRequest Status + * enum for VoiceId EnrollmentRequest Status */ connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum([ "NOT_ENOUGH_SPEECH", @@ -630,7 +638,7 @@ var queueArns = this.getAllQueueARNs(); for (let queueArn of queueArns) { const agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); - + if (agentIdMatch) { return agentIdMatch[1]; } @@ -883,6 +891,13 @@ var client = connect.core.getClient(); var self = this; var contactId = this.getContactId(); + + connect.publishClickStreamData({ + contactId: this.getContactId(), + clickType: connect.ClickType.ACCEPT, + clickTime: new Date().toISOString() + }); + client.call(connect.ClientMethods.ACCEPT_CONTACT, { contactId: contactId }, { @@ -922,6 +937,13 @@ Contact.prototype.reject = function (callbacks) { var client = connect.core.getClient(); + + connect.publishClickStreamData({ + contactId: this.getContactId(), + clickType: connect.ClickType.REJECT, + clickTime: new Date().toISOString() + }); + client.call(connect.ClientMethods.REJECT_CONTACT, { contactId: this.getContactId() }, callbacks); @@ -1129,6 +1151,12 @@ }; Connection.prototype.destroy = function (callbacks) { + connect.publishClickStreamData({ + contactId: this.getContactId(), + clickType: connect.ClickType.HANGUP, + clickTime: new Date().toISOString() + }); + var client = connect.core.getClient(); client.call(connect.ClientMethods.DESTROY_CONNECTION, { contactId: this.getContactId(), @@ -1171,29 +1199,29 @@ } } - // Method for checking whether this connection is an agent-side connection + // 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 + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; } /** - * Utility method for checking whether this connection is an agent-side connection + * 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 + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; } /*---------------------------------------------------------------- * Voice authenticator VoiceId */ - + var VoiceId = function (contactId) { this.contactId = contactId; }; @@ -1219,7 +1247,7 @@ 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") @@ -1279,7 +1307,7 @@ }; // internal only - VoiceId.prototype._optOutSpeakerInLcms = function (speakerId) { + VoiceId.prototype._optOutSpeakerInLcms = function (speakerId, generatedSpeakerId) { var self = this; var client = connect.core.getClient(); return new Promise(function (resolve, reject) { @@ -1289,7 +1317,8 @@ "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), "VoiceIdResult": { - "SpeakerOptedOut": true + "SpeakerOptedOut": true, + "generatedSpeakerId": generatedSpeakerId } }, { success: function (data) { @@ -1321,7 +1350,7 @@ "DomainId" : domainId }, { success: function (data) { - self._optOutSpeakerInLcms(speakerId).catch(function(){}); + self._optOutSpeakerInLcms(speakerId, data.generatedSpeakerId).catch(function(){}); connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, @@ -1421,7 +1450,7 @@ self.checkConferenceCall(); var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var pollTimes = 0; + var pollTimes = 0; return new Promise(function (resolve, reject) { function evaluate() { self.getDomainId().then(function(domainId) { @@ -1445,7 +1474,7 @@ } // Resolve if both authentication and fraud detection are not enabled. - if(!self.isAuthEnabled(data.AuthenticationResult.Decision) && + if(!self.isAuthEnabled(data.AuthenticationResult.Decision) && !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); @@ -1468,7 +1497,7 @@ return; } - if(!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && + if(!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && self.isAuthEnabled(data.AuthenticationResult.Decision)) { switch (data.AuthenticationResult.Decision) { case connect.VoiceIdAuthenticationDecision.ACCEPT: @@ -1488,7 +1517,7 @@ } } - if(!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && + if(!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && self.isFraudEnabled(data.FraudDetectionResult.Decision)) { switch (data.FraudDetectionResult.Decision) { case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: @@ -1529,7 +1558,7 @@ break; default: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); - connect.getLog().error("evaluateSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); + connect.getLog().error("evaluateSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); } reject(error); } @@ -1538,7 +1567,7 @@ reject(err); }); } - + if(!startNew) { self.syncSpeakerId().then(function () { evaluate(); @@ -1547,7 +1576,7 @@ .withObject({err: err}).sendInternalLogToServer(); reject(err); }) - } else { + } else { self.startSession().then(function(data) { self.syncSpeakerId().then(function(data) { setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); @@ -1704,7 +1733,7 @@ }; // internal only - VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId) { + VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId, generatedSpeakerId) { var self = this; var client = connect.core.getClient(); return new Promise(function (resolve, reject) { @@ -1714,7 +1743,7 @@ "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), "VoiceIdResult": { - "generatedSpeakerId": speakerId + "generatedSpeakerId": generatedSpeakerId } }, { success: function (data) { @@ -1747,7 +1776,7 @@ }, { success: function (data) { connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); - self._updateSpeakerIdInLcms(speakerId) + self._updateSpeakerIdInLcms(speakerId, data.generatedSpeakerId) .then(function() { resolve(data); }) @@ -1766,7 +1795,7 @@ break; default: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); - connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: err }).sendInternalLogToServer(); + connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: err }).sendInternalLogToServer(); } reject(error); } @@ -1876,8 +1905,8 @@ /** * @class VoiceConnection - * @param {number} contactId - * @param {number} connectionId + * @param {number} contactId + * @param {number} connectionId * @description - Provides voice media specific operations */ var VoiceConnection = function (contactId, connectionId) { @@ -1890,7 +1919,7 @@ /** * @deprecated - * Please use getMediaInfo + * Please use getMediaInfo */ VoiceConnection.prototype.getSoftphoneMediaInfo = function () { return this._getData().softphoneMediaInfo; @@ -1917,7 +1946,7 @@ } VoiceConnection.prototype.optOutVoiceIdSpeaker = function() { - + return this._speakerAuthenticator.optOutSpeaker(); } @@ -1961,10 +1990,11 @@ }, callbacks); }; + /** * @class ChatConnection - * @param {*} contactId - * @param {*} connectionId + * @param {*} contactId + * @param {*} connectionId * @description adds the chat media specific functionality */ var ChatConnection = function (contactId, connectionId) { @@ -2005,7 +2035,7 @@ }; /** - * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. + * 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() @@ -2055,8 +2085,8 @@ /** * @class TaskConnection - * @param {*} contactId - * @param {*} connectionId + * @param {*} contactId + * @param {*} connectionId * @description adds the task media specific functionality */ var TaskConnection = function (contactId, connectionId) { diff --git a/src/aws-client.js b/src/aws-client.js index 0ef89e2c..cf96aaf5 100644 --- a/src/aws-client.js +++ b/src/aws-client.js @@ -1,4 +1,4 @@ -// AWS SDK for JavaScript v2.553.0 +// AWS SDK for JavaScript v2.1189.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="function"==typeof require&&require;if(!f&&c)return c(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="function"==typeof require&&require,i=0;i= 0) { + return configValue.toLowerCase(); + } else { + throw AWS.util.error(new Error(), errorOptions); + } +} + +/** + * Resolve the configuration value for regional endpoint from difference sources: client + * config, environmental variable, shared config file. Value can be case-insensitive + * 'legacy' or 'reginal'. + * @param originalConfig user-supplied config object to resolve + * @param options a map of config property names from individual configuration source + * - env: name of environmental variable that refers to the config + * - sharedConfig: name of shared configuration file property that refers to the config + * - clientConfig: name of client configuration property that refers to the config + * + * @api private + */ +function resolveRegionalEndpointsFlag(originalConfig, options) { + originalConfig = originalConfig || {}; + //validate config value + var resolved; + if (originalConfig[options.clientConfig]) { + resolved = validateRegionalEndpointsFlagValue(originalConfig[options.clientConfig], { + code: 'InvalidConfiguration', + message: 'invalid "' + options.clientConfig + '" configuration. Expect "legacy" ' + + ' or "regional". Got "' + originalConfig[options.clientConfig] + '".' + }); + if (resolved) return resolved; + } + if (!AWS.util.isNode()) return resolved; + //validate environmental variable + if (Object.prototype.hasOwnProperty.call(process.env, options.env)) { + var envFlag = process.env[options.env]; + resolved = validateRegionalEndpointsFlagValue(envFlag, { + code: 'InvalidEnvironmentalVariable', + message: 'invalid ' + options.env + ' environmental variable. Expect "legacy" ' + + ' or "regional". Got "' + process.env[options.env] + '".' + }); + if (resolved) return resolved; + } + //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, options.sharedConfig)) { + var fileFlag = profile[options.sharedConfig]; + resolved = validateRegionalEndpointsFlagValue(fileFlag, { + code: 'InvalidConfiguration', + message: 'invalid ' + options.sharedConfig + ' profile config. Expect "legacy" ' + + ' or "regional". Got "' + profile[options.sharedConfig] + '".' + }); + if (resolved) return resolved; + } + return resolved; +} + +module.exports = resolveRegionalEndpointsFlag; + +}).call(this)}).call(this,require('_process')) +},{"./core":19,"_process":90}],19:[function(require,module,exports){ /** * The main AWS namespace */ @@ -4332,7 +4983,7 @@ AWS.util.update(AWS, { /** * @constant */ - VERSION: '2.553.0', + VERSION: '2.1189.0', /** * @api private @@ -4420,7 +5071,7 @@ 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){ +},{"../vendor/endpoint-cache":109,"./api_loader":9,"./config":17,"./event_listeners":34,"./http":35,"./json/builder":37,"./json/parser":38,"./model/api":39,"./model/operation":41,"./model/paginator":42,"./model/resource_waiter":43,"./model/shape":44,"./param_validator":45,"./protocol/json":47,"./protocol/query":48,"./protocol/rest":49,"./protocol/rest_json":50,"./protocol/rest_xml":51,"./request":57,"./resource_waiter":58,"./response":59,"./sequential_executor":60,"./service":61,"./signers/request_signer":64,"./util":72,"./xml/builder":74}],20:[function(require,module,exports){ var AWS = require('./core'); /** @@ -4668,7 +5319,7 @@ AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() { AWS.util.addPromises(AWS.Credentials); -},{"./core":18}],20:[function(require,module,exports){ +},{"./core":19}],21:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -4870,7 +5521,7 @@ AWS.ChainableTemporaryCredentials = AWS.util.inherit(AWS.Credentials, { } }); -},{"../../clients/sts":8,"../core":18}],21:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],22:[function(require,module,exports){ var AWS = require('../core'); var CognitoIdentity = require('../../clients/cognitoidentity'); var STS = require('../../clients/sts'); @@ -5257,7 +5908,7 @@ AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, { })() }); -},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(require,module,exports){ +},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":19}],23:[function(require,module,exports){ var AWS = require('../core'); /** @@ -5412,6 +6063,7 @@ AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, { * AWS.CredentialProviderChain.defaultProviders = [ * function () { return new AWS.EnvironmentCredentials('AWS'); }, * function () { return new AWS.EnvironmentCredentials('AMAZON'); }, + * function () { return new AWS.SsoCredentials(); }, * function () { return new AWS.SharedIniFileCredentials(); }, * function () { return new AWS.ECSCredentials(); }, * function () { return new AWS.ProcessCredentials(); }, @@ -5438,7 +6090,7 @@ AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFro AWS.util.addPromises(AWS.CredentialProviderChain); -},{"../core":18}],23:[function(require,module,exports){ +},{"../core":19}],24:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -5534,7 +6186,7 @@ AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, { }); -},{"../../clients/sts":8,"../core":18}],24:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],25:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -5665,7 +6317,7 @@ AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, { }); -},{"../../clients/sts":8,"../core":18}],25:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],26:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); @@ -5782,7 +6434,7 @@ AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, { }); -},{"../../clients/sts":8,"../core":18}],26:[function(require,module,exports){ +},{"../../clients/sts":8,"../core":19}],27:[function(require,module,exports){ (function (process){(function (){ var AWS = require('./core'); var util = require('./util'); @@ -5953,19 +6605,14 @@ function requiredDiscoverEndpoint(request, done) { }]); 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); + request.response.error = util.error(err, { retryable: false }); 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.request.response.error = util.error(err, { retryable: false }); requestContext.callback(); }); delete requestQueue[cacheKeyStr]; @@ -6050,23 +6697,28 @@ function isFalsy(value) { } /** - * If endpoint discovery should perform for this request when endpoint discovery is optional. + * If endpoint discovery should perform for this request when no operation requires endpoint + * discovery for the given service. * 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. + * 1. If set in client configuration. + * 2. If set in env AWS_ENABLE_ENDPOINT_DISCOVERY. + * 3. If set in shared ini config file with key 'endpoint_discovery_enabled'. * @param [object] request request object. + * @returns [boolean|undefined] if endpoint discovery config is not set in any source, this + * function returns undefined * @api private */ -function isEndpointDiscoveryApplicable(request) { +function resolveEndpointDiscoveryConfig(request) { var service = request.service || {}; - if (service.config.endpointDiscoveryEnabled === true) return true; + if (service.config.endpointDiscoveryEnabled !== undefined) { + return service.config.endpointDiscoveryEnabled; + } //shared ini file is only available in Node //not to check env in browser - if (util.isBrowser()) return false; + if (util.isBrowser()) return undefined; + // If any of recognized endpoint discovery config env is set for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) { var env = endpointDiscoveryEnabledEnvs[i]; if (Object.prototype.hasOwnProperty.call(process.env, env)) { @@ -6076,7 +6728,7 @@ function isEndpointDiscoveryApplicable(request) { message: 'environmental variable ' + env + ' cannot be set to nothing' }); } - if (!isFalsy(process.env[env])) return true; + return !isFalsy(process.env[env]); } } @@ -6097,9 +6749,9 @@ function isEndpointDiscoveryApplicable(request) { message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing' }); } - if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true; + return !isFalsy(sharedFileConfig.endpoint_discovery_enabled); } - return false; + return undefined; } /** @@ -6111,20 +6763,38 @@ 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'; + var isEnabled = resolveEndpointDiscoveryConfig(request); + var hasRequiredEndpointDiscovery = service.api.hasRequiredEndpointDiscovery; + if (isEnabled || hasRequiredEndpointDiscovery) { + // Once a customer enables endpoint discovery, the SDK should start appending + // the string endpoint-discovery to the user-agent on all requests. + request.httpRequest.appendToUserAgent('endpoint-discovery'); + } switch (isEndpointDiscoveryRequired) { case 'OPTIONAL': - optionalDiscoverEndpoint(request); - request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); + if (isEnabled || hasRequiredEndpointDiscovery) { + // For a given service; if at least one operation requires endpoint discovery then the SDK must enable endpoint discovery + // by default for all operations of that service, including operations where endpoint discovery is optional. + optionalDiscoverEndpoint(request); + request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); + } done(); break; case 'REQUIRED': + if (isEnabled === false) { + // For a given operation; if endpoint discovery is required and it has been disabled on the SDK client, + // then the SDK must return a clear and actionable exception. + request.response.error = util.error(new Error(), { + code: 'ConfigurationException', + message: 'Endpoint Discovery is disabled but ' + service.api.className + '.' + request.operation + + '() requires it. Please check your configurations.' + }); + done(); + break; + } request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); requiredDiscoverEndpoint(request, done); break; @@ -6145,7 +6815,7 @@ module.exports = { }; }).call(this)}).call(this,require('_process')) -},{"./core":18,"./util":71,"_process":86}],27:[function(require,module,exports){ +},{"./core":19,"./util":72,"_process":90}],28:[function(require,module,exports){ var eventMessageChunker = require('../event-stream/event-message-chunker').eventMessageChunker; var parseEvent = require('./parse-event').parseEvent; @@ -6168,7 +6838,7 @@ module.exports = { createEventStream: createEventStream }; -},{"../event-stream/event-message-chunker":28,"./parse-event":30}],28:[function(require,module,exports){ +},{"../event-stream/event-message-chunker":29,"./parse-event":31}],29:[function(require,module,exports){ /** * Takes in a buffer of event messages and splits them into individual messages. * @param {Buffer} buffer @@ -6200,7 +6870,7 @@ module.exports = { eventMessageChunker: eventMessageChunker }; -},{}],29:[function(require,module,exports){ +},{}],30:[function(require,module,exports){ var util = require('../core').util; var toBuffer = util.buffer.toBuffer; @@ -6295,7 +6965,7 @@ module.exports = { Int64: Int64 }; -},{"../core":18}],30:[function(require,module,exports){ +},{"../core":19}],31:[function(require,module,exports){ var parseMessage = require('./parse-message').parseMessage; /** @@ -6370,7 +7040,7 @@ module.exports = { parseEvent: parseEvent }; -},{"./parse-message":31}],31:[function(require,module,exports){ +},{"./parse-message":32}],32:[function(require,module,exports){ var Int64 = require('./int64').Int64; var splitMessage = require('./split-message').splitMessage; @@ -6500,7 +7170,7 @@ module.exports = { parseMessage: parseMessage }; -},{"./int64":29,"./split-message":32}],32:[function(require,module,exports){ +},{"./int64":30,"./split-message":33}],33:[function(require,module,exports){ var util = require('../core').util; var toBuffer = util.buffer.toBuffer; @@ -6572,7 +7242,8 @@ module.exports = { splitMessage: splitMessage }; -},{"../core":18}],33:[function(require,module,exports){ +},{"../core":19}],34:[function(require,module,exports){ +(function (process){(function (){ var AWS = require('./core'); var SequentialExecutor = require('./sequential_executor'); var DISCOVER_ENDPOINT = require('./discover_endpoint').discoverEndpoint; @@ -6656,16 +7327,22 @@ AWS.EventListeners = { req.service.config.getCredentials(function(err) { if (err) { req.response.error = AWS.util.error(err, - {code: 'CredentialsError', message: 'Missing credentials in config'}); + {code: 'CredentialsError', message: 'Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1'}); } 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'}); + if (!req.service.isGlobalEndpoint) { + var dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!req.service.config.region) { + req.response.error = AWS.util.error(new Error(), + {code: 'ConfigError', message: 'Missing region in config'}); + } else if (!dnsHostRegex.test(req.service.config.region)) { + req.response.error = AWS.util.error(new Error(), + {code: 'ConfigError', message: 'Invalid region in config'}); + } } }); @@ -6701,6 +7378,28 @@ AWS.EventListeners = { new AWS.ParamValidator(validation).validate(rules, req.params); }); + add('COMPUTE_CHECKSUM', 'afterBuild', function COMPUTE_CHECKSUM(req) { + if (!req.service.api.operations) { + return; + } + var operation = req.service.api.operations[req.operation]; + if (!operation) { + return; + } + var body = req.httpRequest.body; + var isNonStreamingPayload = body && (AWS.util.Buffer.isBuffer(body) || typeof body === 'string'); + var headers = req.httpRequest.headers; + if ( + operation.httpChecksumRequired && + req.service.config.computeChecksums && + isNonStreamingPayload && + !headers['Content-MD5'] + ) { + var md5 = AWS.util.crypto.md5(body, 'base64'); + headers['Content-MD5'] = md5; + } + }); + addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) { req.haltHandlersOnError(); if (!req.service.api.operations) { @@ -6758,6 +7457,24 @@ AWS.EventListeners = { req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; }); + add('SET_TRACE_ID', 'afterBuild', function SET_TRACE_ID(req) { + var traceIdHeaderName = 'X-Amzn-Trace-Id'; + if (AWS.util.isNode() && !Object.hasOwnProperty.call(req.httpRequest.headers, traceIdHeaderName)) { + var ENV_LAMBDA_FUNCTION_NAME = 'AWS_LAMBDA_FUNCTION_NAME'; + var ENV_TRACE_ID = '_X_AMZN_TRACE_ID'; + var functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + var traceId = process.env[ENV_TRACE_ID]; + if ( + typeof functionName === 'string' && + functionName.length > 0 && + typeof traceId === 'string' && + traceId.length > 0 + ) { + req.httpRequest.headers[traceIdHeaderName] = traceId; + } + } + }); + add('RESTART', 'restart', function RESTART() { var err = this.response.error; if (!err || !err.retryable) return; @@ -6794,7 +7511,7 @@ AWS.EventListeners = { var date = service.getSkewCorrectedDate(); var SignerClass = service.getSignerClass(req); var signer = new SignerClass(req.httpRequest, - service.api.signingName || service.api.endpointPrefix, + service.getSigningName(req), { signatureCache: service.config.signatureCache, operation: operation, @@ -6828,6 +7545,16 @@ AWS.EventListeners = { } }); + add('ERROR', 'error', function ERROR(err, resp) { + var errorCodeMapping = resp.request.service.api.errorCodeMapping; + if (errorCodeMapping && err && err.code) { + var mapping = errorCodeMapping[err.code]; + if (mapping) { + resp.error.code = mapping.code; + } + } + }, true); + addAsync('SEND', 'send', function SEND(resp, done) { resp.httpResponse._abortCallback = done; resp.error = null; @@ -7029,7 +7756,7 @@ AWS.EventListeners = { 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; + resp.error.retryDelay = this.service.retryDelays(resp.retryCount, resp.error) || 0; } } }); @@ -7048,7 +7775,8 @@ AWS.EventListeners = { } } - if (willRetry) { + // delay < 0 is a signal from customBackoff to skip retries + if (willRetry && delay >= 0) { resp.error = null; setTimeout(done, delay); } else { @@ -7062,8 +7790,14 @@ AWS.EventListeners = { 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 + + function isDNSError(err) { + return err.errno === 'ENOTFOUND' || + typeof err.errno === 'number' && + typeof AWS.util.getSystemErrorName === 'function' && + ['EAI_NONAME', 'EAI_NODATA'].indexOf(AWS.util.getSystemErrorName(err.errno) >= 0); + } + if (err.code === 'NetworkingError' && isDNSError(err)) { + var message = 'Inaccessible host: `' + err.hostname + '\' at port `' + err.port + '\'. This service may not be available in the `' + err.region + '\' region.'; this.response.error = AWS.util.error(new Error(message), { @@ -7086,6 +7820,9 @@ AWS.EventListeners = { if (!shape) { return shape; } + if (inputShape.isSensitive) { + return '***SensitiveInformation***'; + } switch (inputShape.type) { case 'structure': var struct = {}; @@ -7110,11 +7847,7 @@ AWS.EventListeners = { }); return map; default: - if (inputShape.isSensitive) { - return '***SensitiveInformation***'; - } else { - return shape; - } + return shape; } } @@ -7189,7 +7922,8 @@ AWS.EventListeners = { }) }; -},{"./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){ +}).call(this)}).call(this,require('_process')) +},{"./core":19,"./discover_endpoint":27,"./protocol/json":47,"./protocol/query":48,"./protocol/rest":49,"./protocol/rest_json":50,"./protocol/rest_xml":51,"./sequential_executor":60,"_process":90,"util":84}],35:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; @@ -7353,6 +8087,9 @@ AWS.HttpRequest = inherit({ var newEndpoint = new AWS.Endpoint(endpointStr); this.endpoint = newEndpoint; this.path = newEndpoint.path || '/'; + if (this.headers['Host']) { + this.headers['Host'] = newEndpoint.host; + } } }); @@ -7426,7 +8163,7 @@ AWS.HttpClient.getInstance = function getInstance() { return this.singleton; }; -},{"./core":18}],35:[function(require,module,exports){ +},{"./core":19}],36:[function(require,module,exports){ var AWS = require('../core'); var EventEmitter = require('events').EventEmitter; require('../http'); @@ -7564,7 +8301,7 @@ AWS.HttpClient.prototype = AWS.XHRClient.prototype; */ AWS.HttpClient.streamsApiVersion = 1; -},{"../core":18,"../http":34,"events":82}],36:[function(require,module,exports){ +},{"../core":19,"../http":35,"events":86}],37:[function(require,module,exports){ var util = require('../util'); function JsonBuilder() { } @@ -7585,6 +8322,9 @@ function translate(value, shape) { } function translateStructure(structure, shape) { + if (shape.isDocument) { + return structure; + } var struct = {}; util.each(structure, function(name, value) { var memberShape = shape.members[name]; @@ -7625,7 +8365,7 @@ function translateScalar(value, shape) { */ module.exports = JsonBuilder; -},{"../util":71}],37:[function(require,module,exports){ +},{"../util":72}],38:[function(require,module,exports){ var util = require('../util'); function JsonParser() { } @@ -7647,6 +8387,7 @@ function translate(value, shape) { function translateStructure(structure, shape) { if (structure == null) return undefined; + if (shape.isDocument) return structure; var struct = {}; var shapeMembers = shape.members; @@ -7694,12 +8435,13 @@ function translateScalar(value, shape) { */ module.exports = JsonParser; -},{"../util":71}],38:[function(require,module,exports){ +},{"../util":72}],39:[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 metadata = require('../../apis/metadata.json'); var util = require('../util'); var property = util.property; @@ -7713,6 +8455,9 @@ function Api(api, options) { api.metadata = api.metadata || {}; + var serviceIdentifier = options.serviceIdentifier; + delete options.serviceIdentifier; + property(this, 'isApi', true, false); property(this, 'apiVersion', api.metadata.apiVersion); property(this, 'endpointPrefix', api.metadata.endpointPrefix); @@ -7727,6 +8472,9 @@ function Api(api, options) { property(this, 'abbreviation', api.metadata.serviceAbbreviation); property(this, 'fullName', api.metadata.serviceFullName); property(this, 'serviceId', api.metadata.serviceId); + if (serviceIdentifier && metadata[serviceIdentifier]) { + property(this, 'xmlNoDefaultLists', metadata[serviceIdentifier].xmlNoDefaultLists, false); + } memoizedProperty(this, 'className', function() { var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName; @@ -7741,6 +8489,13 @@ function Api(api, options) { if (operation.endpointoperation === true) { property(self, 'endpointOperation', util.string.lowerFirst(name)); } + if (operation.endpointdiscovery && !self.hasRequiredEndpointDiscovery) { + property( + self, + 'hasRequiredEndpointDiscovery', + operation.endpointdiscovery.required === true + ); + } } property(this, 'operations', new Collection(api.operations, options, function(name, operation) { @@ -7763,6 +8518,7 @@ function Api(api, options) { property(this, 'documentation', api.documentation); property(this, 'documentationUrl', api.documentationUrl); } + property(this, 'errorCodeMapping', api.awsQueryCompatible); } /** @@ -7770,7 +8526,7 @@ function Api(api, options) { */ module.exports = Api; -},{"../util":71,"./collection":39,"./operation":40,"./paginator":41,"./resource_waiter":42,"./shape":43}],39:[function(require,module,exports){ +},{"../../apis/metadata.json":4,"../util":72,"./collection":40,"./operation":41,"./paginator":42,"./resource_waiter":43,"./shape":44}],40:[function(require,module,exports){ var memoizedProperty = require('../util').memoizedProperty; function memoize(name, value, factory, nameTr) { @@ -7796,7 +8552,7 @@ function Collection(iterable, options, factory, nameTr, callback) { */ module.exports = Collection; -},{"../util":71}],40:[function(require,module,exports){ +},{"../util":72}],41:[function(require,module,exports){ var Shape = require('./shape'); var util = require('../util'); @@ -7823,6 +8579,12 @@ function Operation(name, operation, options) { 'NULL' ); + // httpChecksum replaces usage of httpChecksumRequired, but some APIs + // (s3control) still uses old trait. + var httpChecksumRequired = operation.httpChecksumRequired + || (operation.httpChecksum && operation.httpChecksum.requestChecksumRequired); + property(this, 'httpChecksumRequired', httpChecksumRequired, false); + memoizedProperty(this, 'input', function() { if (!operation.input) { return new Shape.create({type: 'structure'}, options); @@ -7911,7 +8673,7 @@ function hasEventStream(topLevelShape) { */ module.exports = Operation; -},{"../util":71,"./shape":43}],41:[function(require,module,exports){ +},{"../util":72,"./shape":44}],42:[function(require,module,exports){ var property = require('../util').property; function Paginator(name, paginator) { @@ -7927,7 +8689,7 @@ function Paginator(name, paginator) { */ module.exports = Paginator; -},{"../util":71}],42:[function(require,module,exports){ +},{"../util":72}],43:[function(require,module,exports){ var util = require('../util'); var property = util.property; @@ -7962,7 +8724,7 @@ function ResourceWaiter(name, waiter, options) { */ module.exports = ResourceWaiter; -},{"../util":71}],43:[function(require,module,exports){ +},{"../util":72}],44:[function(require,module,exports){ var Collection = require('./collection'); var util = require('../util'); @@ -8131,6 +8893,7 @@ function StructureShape(shape, options) { property(this, 'memberNames', []); property(this, 'required', []); property(this, 'isRequired', function() { return false; }); + property(this, 'isDocument', Boolean(shape.document)); } if (shape.members) { @@ -8370,7 +9133,7 @@ Shape.shapes = { */ module.exports = Shape; -},{"../util":71,"./collection":39}],44:[function(require,module,exports){ +},{"../util":72,"./collection":40}],45:[function(require,module,exports){ var AWS = require('./core'); /** @@ -8424,8 +9187,9 @@ AWS.ParamValidator = AWS.util.inherit({ }, validateStructure: function validateStructure(shape, params, context) { - this.validateType(params, context, ['object'], 'structure'); + if (shape.isDocument) return true; + this.validateType(params, context, ['object'], 'structure'); var paramName; for (var i = 0; shape.required && i < shape.required.length; i++) { paramName = shape.required[i]; @@ -8446,7 +9210,7 @@ AWS.ParamValidator = AWS.util.inherit({ if (memberShape !== undefined) { var memberContext = [context, paramName].join('.'); this.validateMember(memberShape, paramValue, memberContext); - } else { + } else if (paramValue !== undefined && paramValue !== null) { this.fail('UnexpectedParameter', 'Unexpected key \'' + paramName + '\' found in ' + context); } @@ -8642,7 +9406,7 @@ AWS.ParamValidator = AWS.util.inherit({ } }); -},{"./core":18}],45:[function(require,module,exports){ +},{"./core":19}],46:[function(require,module,exports){ var util = require('../util'); var AWS = require('../core'); @@ -8733,7 +9497,7 @@ module.exports = { populateHostPrefix: populateHostPrefix }; -},{"../core":18,"../util":71}],46:[function(require,module,exports){ +},{"../core":19,"../util":72}],47:[function(require,module,exports){ var util = require('../util'); var JsonBuilder = require('../json/builder'); var JsonParser = require('../json/parser'); @@ -8767,8 +9531,9 @@ function extractError(resp) { 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(); + var code = e.__type || e.code || e.Code; + if (code) { + error.code = code.split('#').pop(); } if (error.code === 'RequestEntityTooLarge') { error.message = 'Request body must be less than 1 MB'; @@ -8808,7 +9573,7 @@ module.exports = { extractData: extractData }; -},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(require,module,exports){ +},{"../json/builder":37,"../json/parser":38,"../util":72,"./helpers":46}],48:[function(require,module,exports){ var AWS = require('../core'); var util = require('../util'); var QueryParamSerializer = require('../query/query_param_serializer'); @@ -8920,7 +9685,7 @@ module.exports = { extractData: extractData }; -},{"../core":18,"../model/shape":43,"../query/query_param_serializer":51,"../util":71,"./helpers":45}],48:[function(require,module,exports){ +},{"../core":19,"../model/shape":44,"../query/query_param_serializer":52,"../util":72,"./helpers":46}],49:[function(require,module,exports){ var util = require('../util'); var populateHostPrefix = require('./helpers').populateHostPrefix; @@ -9070,7 +9835,7 @@ module.exports = { generateURI: generateURI }; -},{"../util":71,"./helpers":45}],49:[function(require,module,exports){ +},{"../util":72,"./helpers":46}],50:[function(require,module,exports){ var util = require('../util'); var Rest = require('./rest'); var Json = require('./json'); @@ -9085,30 +9850,24 @@ function populateBody(req) { 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); + req.httpRequest.body = builder.build(params || {}, payloadShape); applyContentTypeHeader(req); - } else { // non-JSON payload + } else if (params !== undefined) { + // 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; - } + req.httpRequest.body = builder.build(req.params, input); 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; @@ -9118,8 +9877,8 @@ function applyContentTypeHeader(req, isBinary) { function buildRequest(req) { Rest.buildRequest(req); - // never send body payload on HEAD/DELETE - if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { + // never send body payload on GET/HEAD/DELETE + if (['GET', 'HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { populateBody(req); } } @@ -9171,7 +9930,7 @@ module.exports = { extractData: extractData }; -},{"../json/builder":36,"../json/parser":37,"../util":71,"./json":46,"./rest":48}],50:[function(require,module,exports){ +},{"../json/builder":37,"../json/parser":38,"../util":72,"./json":47,"./rest":49}],51:[function(require,module,exports){ var AWS = require('../core'); var util = require('../util'); var Rest = require('./rest'); @@ -9281,7 +10040,7 @@ module.exports = { extractData: extractData }; -},{"../core":18,"../util":71,"./rest":48}],51:[function(require,module,exports){ +},{"../core":19,"../util":72,"./rest":49}],52:[function(require,module,exports){ var util = require('../util'); function QueryParamSerializer() { @@ -9367,7 +10126,7 @@ function serializeMember(name, value, rules, fn) { */ module.exports = QueryParamSerializer; -},{"../util":71}],52:[function(require,module,exports){ +},{"../util":72}],53:[function(require,module,exports){ module.exports = { //provide realtime clock for performance measurement now: function now() { @@ -9378,13 +10137,35 @@ module.exports = { } }; -},{}],53:[function(require,module,exports){ +},{}],54:[function(require,module,exports){ +function isFipsRegion(region) { + return typeof region === 'string' && (region.startsWith('fips-') || region.endsWith('-fips')); +} + +function isGlobalRegion(region) { + return typeof region === 'string' && ['aws-global', 'aws-us-gov-global'].includes(region); +} + +function getRealRegion(region) { + return ['fips-aws-global', 'aws-fips', 'aws-global'].includes(region) + ? 'us-east-1' + : ['fips-aws-us-gov-global', 'aws-us-gov-global'].includes(region) + ? 'us-gov-west-1' + : region.replace(/fips-(dkr-|prod-)?|-fips/, ''); +} + +module.exports = { + isFipsRegion: isFipsRegion, + isGlobalRegion: isGlobalRegion, + getRealRegion: getRealRegion +}; + +},{}],55:[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('-') + '-*'; @@ -9418,24 +10199,31 @@ function applyConfig(service, config) { function configureEndpoint(service) { var keys = derivedKeys(service); + var useFipsEndpoint = service.config.useFipsEndpoint; + var useDualstackEndpoint = service.config.useDualstackEndpoint; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!key) continue; - if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) { - var config = regionConfig.rules[key]; + var rules = useFipsEndpoint + ? useDualstackEndpoint + ? regionConfig.dualstackFipsRules + : regionConfig.fipsRules + : useDualstackEndpoint + ? regionConfig.dualstackRules + : regionConfig.rules; + + if (Object.prototype.hasOwnProperty.call(rules, key)) { + var config = rules[key]; if (typeof config === 'string') { config = regionConfig.patterns[config]; } - // set dualstack endpoint - if (service.config.useDualstack && util.isDualstackAvailable(service)) { - config = util.copy(config); - config.endpoint = '{service}.dualstack.{region}.amazonaws.com'; - } - // set global endpoint service.isGlobalEndpoint = !!config.globalEndpoint; + if (config.signingRegion) { + service.signingRegion = config.signingRegion; + } // signature version if (!config.signatureVersion) config.signatureVersion = 'v4'; @@ -9447,12 +10235,33 @@ function configureEndpoint(service) { } } +function getEndpointSuffix(region) { + var regionRegexes = { + '^(us|eu|ap|sa|ca|me)\\-\\w+\\-\\d+$': 'amazonaws.com', + '^cn\\-\\w+\\-\\d+$': 'amazonaws.com.cn', + '^us\\-gov\\-\\w+\\-\\d+$': 'amazonaws.com', + '^us\\-iso\\-\\w+\\-\\d+$': 'c2s.ic.gov', + '^us\\-isob\\-\\w+\\-\\d+$': 'sc2s.sgov.gov' + }; + var defaultSuffix = 'amazonaws.com'; + var regexes = Object.keys(regionRegexes); + for (var i = 0; i < regexes.length; i++) { + var regionPattern = RegExp(regexes[i]); + var dnsSuffix = regionRegexes[regexes[i]]; + if (regionPattern.test(region)) return dnsSuffix; + } + return defaultSuffix; +} + /** * @api private */ -module.exports = configureEndpoint; +module.exports = { + configureEndpoint: configureEndpoint, + getEndpointSuffix: getEndpointSuffix, +}; -},{"./region_config_data.json":54,"./util":71}],54:[function(require,module,exports){ +},{"./region_config_data.json":56,"./util":72}],56:[function(require,module,exports){ module.exports={ "rules": { "*/*": { @@ -9461,22 +10270,45 @@ module.exports={ "cn-*/*": { "endpoint": "{service}.{region}.amazonaws.com.cn" }, + "us-iso-*/*": "usIso", + "us-isob-*/*": "usIsob", "*/budgets": "globalSSL", "*/cloudfront": "globalSSL", - "*/iam": "globalSSL", "*/sts": "globalSSL", "*/importexport": { "endpoint": "{service}.amazonaws.com", "signatureVersion": "v2", "globalEndpoint": true }, - "*/route53": { - "endpoint": "https://{service}.amazonaws.com", - "signatureVersion": "v3https", - "globalEndpoint": true + + "*/route53": "globalSSL", + "cn-*/route53": { + "endpoint": "{service}.amazonaws.com.cn", + "globalEndpoint": true, + "signingRegion": "cn-northwest-1" + }, + "us-gov-*/route53": "globalGovCloud", + "us-iso-*/route53": { + "endpoint": "{service}.c2s.ic.gov", + "globalEndpoint": true, + "signingRegion": "us-iso-east-1" + }, + "us-isob-*/route53": { + "endpoint": "{service}.sc2s.sgov.gov", + "globalEndpoint": true, + "signingRegion": "us-isob-east-1" }, + "*/waf": "globalSSL", + + "*/iam": "globalSSL", + "cn-*/iam": { + "endpoint": "{service}.cn-north-1.amazonaws.com.cn", + "globalEndpoint": true, + "signingRegion": "cn-north-1" + }, "us-gov-*/iam": "globalGovCloud", + "us-gov-*/sts": { "endpoint": "{service}.{region}.amazonaws.com" }, @@ -9502,22 +10334,164 @@ module.exports={ } }, + "fipsRules": { + "*/*": "fipsStandard", + "us-gov-*/*": "fipsStandard", + "us-iso-*/*": { + "endpoint": "{service}-fips.{region}.c2s.ic.gov" + }, + "us-iso-*/dms": "usIso", + "us-isob-*/*": { + "endpoint": "{service}-fips.{region}.sc2s.sgov.gov" + }, + "us-isob-*/dms": "usIsob", + "cn-*/*": { + "endpoint": "{service}-fips.{region}.amazonaws.com.cn" + }, + "*/api.ecr": "fips.api.ecr", + "*/api.sagemaker": "fips.api.sagemaker", + "*/batch": "fipsDotPrefix", + "*/eks": "fipsDotPrefix", + "*/models.lex": "fips.models.lex", + "*/runtime.lex": "fips.runtime.lex", + "*/runtime.sagemaker": { + "endpoint": "runtime-fips.sagemaker.{region}.amazonaws.com" + }, + "*/iam": "fipsWithoutRegion", + "*/route53": "fipsWithoutRegion", + "*/transcribe": "fipsDotPrefix", + "*/waf": "fipsWithoutRegion", + + "us-gov-*/transcribe": "fipsDotPrefix", + "us-gov-*/api.ecr": "fips.api.ecr", + "us-gov-*/api.sagemaker": "fips.api.sagemaker", + "us-gov-*/models.lex": "fips.models.lex", + "us-gov-*/runtime.lex": "fips.runtime.lex", + "us-gov-*/acm-pca": "fipsWithServiceOnly", + "us-gov-*/batch": "fipsWithServiceOnly", + "us-gov-*/config": "fipsWithServiceOnly", + "us-gov-*/eks": "fipsWithServiceOnly", + "us-gov-*/elasticmapreduce": "fipsWithServiceOnly", + "us-gov-*/identitystore": "fipsWithServiceOnly", + "us-gov-*/dynamodb": "fipsWithServiceOnly", + "us-gov-*/elasticloadbalancing": "fipsWithServiceOnly", + "us-gov-*/guardduty": "fipsWithServiceOnly", + "us-gov-*/monitoring": "fipsWithServiceOnly", + "us-gov-*/resource-groups": "fipsWithServiceOnly", + "us-gov-*/runtime.sagemaker": "fipsWithServiceOnly", + "us-gov-*/servicecatalog-appregistry": "fipsWithServiceOnly", + "us-gov-*/servicequotas": "fipsWithServiceOnly", + "us-gov-*/ssm": "fipsWithServiceOnly", + "us-gov-*/sts": "fipsWithServiceOnly", + "us-gov-*/support": "fipsWithServiceOnly", + "us-gov-west-1/states": "fipsWithServiceOnly", + "us-iso-east-1/elasticfilesystem": { + "endpoint": "elasticfilesystem-fips.{region}.c2s.ic.gov" + }, + "us-gov-west-1/organizations": "fipsWithServiceOnly", + "us-gov-west-1/route53": { + "endpoint": "route53.us-gov.amazonaws.com" + } + }, + + "dualstackRules": { + "*/*": { + "endpoint": "{service}.{region}.api.aws" + }, + "cn-*/*": { + "endpoint": "{service}.{region}.api.amazonwebservices.com.cn" + }, + + "*/s3": "dualstackLegacy", + "cn-*/s3": "dualstackLegacyCn", + "*/s3-control": "dualstackLegacy", + "cn-*/s3-control": "dualstackLegacyCn", + + "ap-south-1/ec2": "dualstackLegacyEc2", + "eu-west-1/ec2": "dualstackLegacyEc2", + "sa-east-1/ec2": "dualstackLegacyEc2", + "us-east-1/ec2": "dualstackLegacyEc2", + "us-east-2/ec2": "dualstackLegacyEc2", + "us-west-2/ec2": "dualstackLegacyEc2" + }, + + "dualstackFipsRules": { + "*/*": { + "endpoint": "{service}-fips.{region}.api.aws" + }, + "cn-*/*": { + "endpoint": "{service}-fips.{region}.api.amazonwebservices.com.cn" + }, + "*/s3": "dualstackFipsLegacy", + "cn-*/s3": "dualstackFipsLegacyCn", + "*/s3-control": "dualstackFipsLegacy", + "cn-*/s3-control": "dualstackFipsLegacyCn" + }, + "patterns": { "globalSSL": { "endpoint": "https://{service}.amazonaws.com", - "globalEndpoint": true + "globalEndpoint": true, + "signingRegion": "us-east-1" }, "globalGovCloud": { - "endpoint": "{service}.us-gov.amazonaws.com" + "endpoint": "{service}.us-gov.amazonaws.com", + "globalEndpoint": true, + "signingRegion": "us-gov-west-1" }, "s3signature": { "endpoint": "{service}.{region}.amazonaws.com", "signatureVersion": "s3" + }, + "usIso": { + "endpoint": "{service}.{region}.c2s.ic.gov" + }, + "usIsob": { + "endpoint": "{service}.{region}.sc2s.sgov.gov" + }, + "fipsStandard": { + "endpoint": "{service}-fips.{region}.amazonaws.com" + }, + "fipsDotPrefix": { + "endpoint": "fips.{service}.{region}.amazonaws.com" + }, + "fipsWithoutRegion": { + "endpoint": "{service}-fips.amazonaws.com" + }, + "fips.api.ecr": { + "endpoint": "ecr-fips.{region}.amazonaws.com" + }, + "fips.api.sagemaker": { + "endpoint": "api-fips.sagemaker.{region}.amazonaws.com" + }, + "fips.models.lex": { + "endpoint": "models-fips.lex.{region}.amazonaws.com" + }, + "fips.runtime.lex": { + "endpoint": "runtime-fips.lex.{region}.amazonaws.com" + }, + "fipsWithServiceOnly": { + "endpoint": "{service}.{region}.amazonaws.com" + }, + "dualstackLegacy": { + "endpoint": "{service}.dualstack.{region}.amazonaws.com" + }, + "dualstackLegacyCn": { + "endpoint": "{service}.dualstack.{region}.amazonaws.com.cn" + }, + "dualstackFipsLegacy": { + "endpoint": "{service}-fips.dualstack.{region}.amazonaws.com" + }, + "dualstackFipsLegacyCn": { + "endpoint": "{service}-fips.dualstack.{region}.amazonaws.com.cn" + }, + "dualstackLegacyEc2": { + "endpoint": "api.ec2.{region}.aws" } } } -},{}],55:[function(require,module,exports){ +},{}],57:[function(require,module,exports){ (function (process){(function (){ var AWS = require('./core'); var AcceptorStateMachine = require('./state_machine'); @@ -9834,8 +10808,11 @@ AWS.Request = inherit({ var region = service.config.region; var customUserAgent = service.config.customUserAgent; - // global endpoints sign as us-east-1 - if (service.isGlobalEndpoint) region = 'us-east-1'; + if (service.signingRegion) { + region = service.signingRegion; + } else if (service.isGlobalEndpoint) { + region = 'us-east-1'; + } this.domain = domain && domain.active; this.service = service; @@ -10301,7 +11278,7 @@ AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) if (resp.error) { reject(resp.error); } else { - // define $response property so that it is not enumberable + // define $response property so that it is not enumerable // this prevents circular reference errors when stringifying the JSON object resolve(Object.defineProperty( resp.data || {}, @@ -10327,7 +11304,7 @@ 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){ +},{"./core":19,"./state_machine":71,"_process":90,"jmespath":89}],58:[function(require,module,exports){ /** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -10533,7 +11510,7 @@ AWS.ResourceWaiter = inherit({ } }); -},{"./core":18,"jmespath":85}],57:[function(require,module,exports){ +},{"./core":19,"jmespath":89}],59:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; var jmespath = require('jmespath'); @@ -10736,7 +11713,7 @@ AWS.Response = inherit({ }); -},{"./core":18,"jmespath":85}],58:[function(require,module,exports){ +},{"./core":19,"jmespath":89}],60:[function(require,module,exports){ var AWS = require('./core'); /** @@ -10973,7 +11950,7 @@ AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype. */ module.exports = AWS.SequentialExecutor; -},{"./core":18}],59:[function(require,module,exports){ +},{"./core":19}],61:[function(require,module,exports){ (function (process){(function (){ var AWS = require('./core'); var Api = require('./model/api'); @@ -10981,6 +11958,7 @@ var regionConfig = require('./region_config'); var inherit = AWS.util.inherit; var clientCount = 0; +var region_utils = require('./region/utils'); /** * The service class representing an AWS service. @@ -11002,6 +11980,24 @@ AWS.Service = inherit({ throw AWS.util.error(new Error(), 'Service must be constructed with `new\' operator'); } + + if (config) { + if (config.region) { + var region = config.region; + if (region_utils.isFipsRegion(region)) { + config.region = region_utils.getRealRegion(region); + config.useFipsEndpoint = true; + } + if (region_utils.isGlobalRegion(region)) { + config.region = region_utils.getRealRegion(region); + } + } + if (typeof config.useDualstack === 'boolean' + && typeof config.useDualstackEndpoint !== 'boolean') { + config.useDualstackEndpoint = config.useDualstack; + } + } + var ServiceClass = this.loadServiceClass(config || {}); if (ServiceClass) { var originalConfig = AWS.util.copy(config); @@ -11027,7 +12023,7 @@ AWS.Service = inherit({ if (config) this.config.update(config, true); this.validateService(); - if (!this.config.endpoint) regionConfig(this); + if (!this.config.endpoint) regionConfig.configureEndpoint(this); this.config.endpoint = this.endpointFromTemplate(this.config.endpoint); this.setEndpoint(this.config.endpoint); @@ -11410,6 +12406,8 @@ AWS.Service = inherit({ apiCallEvent.Latency = latency >= 0 ? latency : 0; var response = request.response; if ( + response.error && + response.error.retryable && typeof response.retryCount === 'number' && typeof response.maxRetries === 'number' && (response.retryCount >= response.maxRetries) @@ -11429,6 +12427,14 @@ AWS.Service = inherit({ setupRequestListeners: function setupRequestListeners(request) { }, + /** + * Gets the signing name for a given request + * @api private + */ + getSigningName: function getSigningName() { + return this.api.signingName || this.api.endpointPrefix; + }, + /** * Gets the signer class for a given request * @api private @@ -11494,8 +12500,8 @@ AWS.Service = inherit({ /** * @api private */ - retryDelays: function retryDelays(retryCount) { - return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions); + retryDelays: function retryDelays(retryCount, err) { + return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions, err); }, /** @@ -11569,7 +12575,7 @@ AWS.Service = inherit({ */ isClockSkewed: function isClockSkewed(newServerTime) { if (newServerTime) { - return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000; + return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 300000; } }, @@ -11588,6 +12594,7 @@ AWS.Service = inherit({ case 'RequestThrottledException': case 'TooManyRequestsException': case 'TransactionInProgressException': //dynamodb + case 'EC2ThrottledException': return true; default: return false; @@ -11728,7 +12735,9 @@ AWS.util.update(AWS.Service, { if (api.isApi) { svc.prototype.api = api; } else { - svc.prototype.api = new Api(api); + svc.prototype.api = new Api(api, { + serviceIdentifier: superclass.serviceIdentifier + }); } } @@ -11797,27 +12806,9 @@ AWS.util.mixin(AWS.Service, AWS.SequentialExecutor); module.exports = AWS.Service; }).call(this)}).call(this,require('_process')) -},{"./core":18,"./model/api":38,"./region_config":53,"_process":86}],60:[function(require,module,exports){ -var AWS = require('../core'); - -AWS.util.update(AWS.CognitoIdentity.prototype, { - getOpenIdToken: function getOpenIdToken(params, callback) { - return this.makeUnauthenticatedRequest('getOpenIdToken', params, callback); - }, - - getId: function getId(params, callback) { - return this.makeUnauthenticatedRequest('getId', params, callback); - }, - - getCredentialsForIdentity: function getCredentialsForIdentity(params, callback) { - return this.makeUnauthenticatedRequest('getCredentialsForIdentity', params, callback); - } -}); - -},{"../core":18}],61:[function(require,module,exports){ -(function (process){(function (){ +},{"./core":19,"./model/api":39,"./region/utils":54,"./region_config":55,"_process":90}],62:[function(require,module,exports){ var AWS = require('../core'); -var regionConfig = require('../region_config'); +var resolveRegionalEndpointsFlag = require('../config_regional_endpoint'); var ENV_REGIONAL_ENDPOINT_ENABLED = 'AWS_STS_REGIONAL_ENDPOINTS'; var CONFIG_REGIONAL_ENDPOINT_ENABLED = 'sts_regional_endpoints'; @@ -11869,83 +12860,41 @@ AWS.util.update(AWS.STS.prototype, { /** * @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] + '".' - }); - } + setupRequestListeners: function setupRequestListeners(request) { + request.addListener('validate', this.optInRegionalEndpoint, true); }, /** * @api private */ - optInRegionalEndpoint: function optInRegionalEndpoint() { - this.validateRegionalEndpointsFlag(); - var config = this.config; - if (config.stsRegionalEndpoints === 'regional') { - regionConfig(this); - if (!this.isGlobalEndpoint) return; - this.isGlobalEndpoint = false; + optInRegionalEndpoint: function optInRegionalEndpoint(req) { + var service = req.service; + var config = service.config; + config.stsRegionalEndpoints = resolveRegionalEndpointsFlag(service._originalConfig, { + env: ENV_REGIONAL_ENDPOINT_ENABLED, + sharedConfig: CONFIG_REGIONAL_ENDPOINT_ENABLED, + clientConfig: 'stsRegionalEndpoints' + }); + if ( + config.stsRegionalEndpoints === 'regional' && + service.isGlobalEndpoint + ) { //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) + + var regionalEndpoint = config.endpoint.substring(0, insertPoint) + '.' + config.region + config.endpoint.substring(insertPoint); + req.httpRequest.updateEndpoint(regionalEndpoint); + req.httpRequest.region = config.region; } - }, - - validateService: function validateService() { - this.optInRegionalEndpoint(); } }); -}).call(this)}).call(this,require('_process')) -},{"../core":18,"../region_config":53,"_process":86}],62:[function(require,module,exports){ +},{"../config_regional_endpoint":18,"../core":19}],63:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -12000,8 +12949,8 @@ function signedUrlSigner(request) { var auth = request.httpRequest.headers['Authorization'].split(' '); if (auth[0] === 'AWS') { auth = auth[1].split(':'); - queryParams['AWSAccessKeyId'] = auth[0]; - queryParams['Signature'] = auth[1]; + queryParams['Signature'] = auth.pop(); + queryParams['AWSAccessKeyId'] = auth.join(':'); AWS.util.each(request.httpRequest.headers, function (key, value) { if (key === expiresHeader) key = 'Expires'; @@ -12066,7 +13015,7 @@ AWS.Signers.Presign = inherit({ */ module.exports = AWS.Signers.Presign; -},{"../core":18}],63:[function(require,module,exports){ +},{"../core":19}],64:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -12107,7 +13056,7 @@ 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){ +},{"../core":19,"./presign":63,"./s3":65,"./v2":66,"./v3":67,"./v3https":68,"./v4":69}],65:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -12284,7 +13233,7 @@ AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.S3; -},{"../core":18}],65:[function(require,module,exports){ +},{"../core":19}],66:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -12334,7 +13283,7 @@ AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.V2; -},{"../core":18}],66:[function(require,module,exports){ +},{"../core":19}],67:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -12413,7 +13362,7 @@ AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.V3; -},{"../core":18}],67:[function(require,module,exports){ +},{"../core":19}],68:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; @@ -12440,7 +13389,7 @@ AWS.Signers.V3Https = inherit(AWS.Signers.V3, { */ module.exports = AWS.Signers.V3Https; -},{"../core":18,"./v3":66}],68:[function(require,module,exports){ +},{"../core":19,"./v3":67}],69:[function(require,module,exports){ var AWS = require('../core'); var v4Credentials = require('./v4_credentials'); var inherit = AWS.util.inherit; @@ -12622,7 +13571,7 @@ AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { hexEncodedBodyHash: function hexEncodedBodyHash() { var request = this.request; - if (this.isPresigned() && this.serviceName === 's3' && !request.body) { + if (this.isPresigned() && (['s3', 's3-object-lambda'].indexOf(this.serviceName) > -1) && !request.body) { return 'UNSIGNED-PAYLOAD'; } else if (request.headers['X-Amz-Content-Sha256']) { return request.headers['X-Amz-Content-Sha256']; @@ -12657,7 +13606,7 @@ AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { */ module.exports = AWS.Signers.V4; -},{"../core":18,"./v4_credentials":69}],69:[function(require,module,exports){ +},{"../core":19,"./v4_credentials":70}],70:[function(require,module,exports){ var AWS = require('../core'); /** @@ -12759,7 +13708,7 @@ module.exports = { } }; -},{"../core":18}],70:[function(require,module,exports){ +},{"../core":19}],71:[function(require,module,exports){ function AcceptorStateMachine(states, state) { this.currentState = state || null; this.states = states || {}; @@ -12806,7 +13755,7 @@ AcceptorStateMachine.prototype.addState = function addState(name, acceptState, f */ module.exports = AcceptorStateMachine; -},{}],71:[function(require,module,exports){ +},{}],72:[function(require,module,exports){ (function (process,setImmediate){(function (){ /* eslint guard-for-in:0 */ var AWS; @@ -13025,15 +13974,28 @@ var util = { 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]; + line = line.split(/(^|\s)[;#]/)[0].trim(); // remove comments and trim + var isSection = line[0] === '[' && line[line.length - 1] === ']'; + if (isSection) { + currentSection = line.substring(1, line.length - 1); + if (currentSection === '__proto__' || currentSection.split(/\s/)[1] === '__proto__') { + throw util.error( + new Error('Cannot load profile name \'' + currentSection + '\' from shared ini file.') + ); + } } else if (currentSection) { - var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); - if (item) { + var indexOfEqualsSign = line.indexOf('='); + var start = 0; + var end = line.length - 1; + var isAssignment = + indexOfEqualsSign !== -1 && indexOfEqualsSign !== start && indexOfEqualsSign !== end; + + if (isAssignment) { + var name = line.substring(0, indexOfEqualsSign).trim(); + var value = line.substring(indexOfEqualsSign + 1).trim(); + map[currentSection] = map[currentSection] || {}; - map[currentSection][item[1]] = item[2]; + map[currentSection][name] = value; } } }); @@ -13404,7 +14366,7 @@ var util = { Object.defineProperty(err, 'message', {enumerable: true}); } - err.name = options && options.name || err.name || err.code || 'Error'; + err.name = String(options && options.name || err.name || err.code || 'Error'); err.time = new Date(); if (originalError) err.originalError = originalError; @@ -13660,11 +14622,11 @@ var util = { /** * @api private */ - calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) { + calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions, err) { if (!retryDelayOptions) retryDelayOptions = {}; var customBackoff = retryDelayOptions.customBackoff || null; if (typeof customBackoff === 'function') { - return customBackoff(retryCount); + return customBackoff(retryCount, err); } var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100; var delay = Math.random() * (Math.pow(2, retryCount) * base); @@ -13683,13 +14645,17 @@ var util = { var errCallback = function(err) { var maxRetries = options.maxRetries || 0; if (err && err.code === 'TimeoutError') err.retryable = true; + + // Call `calculateRetryDelay()` only when relevant, see #3401 if (err && err.retryable && retryCount < maxRetries) { - retryCount++; - var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions); - setTimeout(sendRequest, delay + (err.retryAfter || 0)); - } else { - cb(err); + var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions, err); + if (delay >= 0) { + retryCount++; + setTimeout(sendRequest, delay + (err.retryAfter || 0)); + return; + } } + cb(err); }; var sendRequest = function() { @@ -13703,7 +14669,10 @@ var util = { } else { var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0; var err = util.error(new Error(), - { retryable: statusCode >= 500 || statusCode === 429 } + { + statusCode: statusCode, + retryable: statusCode >= 500 || statusCode === 429 + } ); if (retryAfter && err.retryable) err.retryAfter = retryAfter; errCallback(err); @@ -13769,17 +14738,62 @@ var util = { filename: process.env[util.sharedConfigFileEnv] }); } - var profilesFromCreds = iniLoader.loadFrom({ - filename: filename || - (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv]) - }); + var profilesFromCreds= {}; + try { + var profilesFromCreds = iniLoader.loadFrom({ + filename: filename || + (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv]) + }); + } catch (error) { + // if using config, assume it is fully descriptive without a credentials file: + if (!process.env[util.configOptInEnv]) throw error; + } for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) { - profiles[profileNames[i]] = profilesFromConfig[profileNames[i]]; + profiles[profileNames[i]] = objectAssign(profiles[profileNames[i]] || {}, profilesFromConfig[profileNames[i]]); } for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) { - profiles[profileNames[i]] = profilesFromCreds[profileNames[i]]; + profiles[profileNames[i]] = objectAssign(profiles[profileNames[i]] || {}, profilesFromCreds[profileNames[i]]); } return profiles; + + /** + * Roughly the semantics of `Object.assign(target, source)` + */ + function objectAssign(target, source) { + for (var i = 0, keys = Object.keys(source); i < keys.length; i++) { + target[keys[i]] = source[keys[i]]; + } + return target; + } + }, + + /** + * @api private + */ + ARN: { + validate: function validateARN(str) { + return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6; + }, + parse: function parseARN(arn) { + var matched = arn.split(':'); + return { + partition: matched[1], + service: matched[2], + region: matched[3], + accountId: matched[4], + resource: matched.slice(5).join(':') + }; + }, + build: function buildARN(arnObject) { + if ( + arnObject.service === undefined || + arnObject.region === undefined || + arnObject.accountId === undefined || + arnObject.resource === undefined + ) throw util.error(new Error('Input ARN object is invalid')); + return 'arn:'+ (arnObject.partition || 'aws') + ':' + arnObject.service + + ':' + arnObject.region + ':' + arnObject.accountId + ':' + arnObject.resource; + } }, /** @@ -13814,7 +14828,7 @@ var util = { 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){ +},{"../apis/metadata.json":4,"./core":19,"_process":90,"fs":80,"timers":97,"uuid":100}],73:[function(require,module,exports){ var util = require('../util'); var Shape = require('../model/shape'); @@ -13925,7 +14939,10 @@ function parseStructure(xml, shape) { getElementByTagName(xml, memberShape.name); if (xmlChild) { data[memberName] = parseXml(xmlChild, memberShape); - } else if (!memberShape.flattened && memberShape.type === 'list') { + } else if ( + !memberShape.flattened && + memberShape.type === 'list' && + !shape.api.xmlNoDefaultLists) { data[memberName] = memberShape.defaultValue; } } @@ -14014,7 +15031,7 @@ function parseUnknown(xml) { */ module.exports = DomXmlParser; -},{"../model/shape":43,"../util":71}],73:[function(require,module,exports){ +},{"../model/shape":44,"../util":72}],74:[function(require,module,exports){ var util = require('../util'); var XmlNode = require('./xml-node').XmlNode; var XmlText = require('./xml-text').XmlText; @@ -14118,7 +15135,7 @@ function applyNamespaces(xml, shape, isRoot) { */ module.exports = XmlBuilder; -},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(require,module,exports){ +},{"../util":72,"./xml-node":77,"./xml-text":78}],75:[function(require,module,exports){ /** * Escapes characters that can not be in an XML attribute. */ @@ -14133,12 +15150,18 @@ module.exports = { escapeAttribute: escapeAttribute }; -},{}],75:[function(require,module,exports){ +},{}],76:[function(require,module,exports){ /** * Escapes characters that can not be in an XML element. */ function escapeElement(value) { - return value.replace(/&/g, '&').replace(//g, '>'); + return value.replace(/&/g, '&') + .replace(//g, '>') + .replace(/\r/g, ' ') + .replace(/\n/g, ' ') + .replace(/\u0085/g, '…') + .replace(/\u2028/, '
'); } /** @@ -14148,7 +15171,7 @@ module.exports = { escapeElement: escapeElement }; -},{}],76:[function(require,module,exports){ +},{}],77:[function(require,module,exports){ var escapeAttribute = require('./escape-attribute').escapeAttribute; /** @@ -14195,7 +15218,7 @@ module.exports = { XmlNode: XmlNode }; -},{"./escape-attribute":74}],77:[function(require,module,exports){ +},{"./escape-attribute":75}],78:[function(require,module,exports){ var escapeElement = require('./escape-element').escapeElement; /** @@ -14217,7 +15240,7 @@ module.exports = { XmlText: XmlText }; -},{"./escape-element":75}],78:[function(require,module,exports){ +},{"./escape-element":76}],79:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -14369,9 +15392,34 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],79:[function(require,module,exports){ - },{}],80:[function(require,module,exports){ + +},{}],81:[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 + } +} + +},{}],82:[function(require,module,exports){ (function (global){(function (){ /*! https://mths.be/punycode v1.3.2 by @mathias */ ;(function(root) { @@ -14905,2388 +15953,2998 @@ function fromByteArray (uint8) { }(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 +},{}],83:[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'; } +},{}],84:[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. -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') +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(' '); } - 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) + + 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); } that.length = length } + return str; +}; - 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. - */ +// 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); + }; + } -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) + if (process.noDeprecation === true) { + return fn; } - // 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' - ) + 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 allocUnsafe(this, arg) + return fn.apply(this, arguments); } - return from(this, arg, encodingOrOffset, length) -} -Buffer.poolSize = 8192 // not used by this implementation + return deprecated; +}; -// 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') +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]; +}; - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) +/** + * 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); } - - return fromObject(that, value) + // 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; -/** - * 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 - }) - } -} +// 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] +}; -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') - } -} +// 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 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 stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; -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 - } + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; } - return that } -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) + +function stylizeNoColor(str, styleType) { + return str; } -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; } -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') +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; } - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - var actual = that.write(string, encoding) + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - 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) + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); } - return that -} + // 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); + } -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 + // 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); + } } - return that -} -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer + var base = '', array = false, braces = ['{', '}']; - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; } - 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) + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); } - 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) + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); } - 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 + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); } - 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 (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); } } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} + ctx.seen.push(value); -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') + 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); + }); } - return length | 0 -} -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} + ctx.seen.pop(); -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) + return reduceToSingleString(output, base, braces); } -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 - } +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 (x < y) return -1 - if (y < x) return 1 - return 0 + 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'); } -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') - } +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} - 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 +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(''); } } - - 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') + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer + }); + return output; } -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length + +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 (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; } - if (typeof string !== 'string') { - string = '' + string + 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'); + } } - - 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 + 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; } -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. +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); - // 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 (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; } - if (end === undefined || end > this.length) { - end = this.length - } + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} - if (end <= 0) { - return '' - } - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 +// 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; - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - case 'ascii': - return asciiSlice(this, start, end) +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - case 'base64': - return base64Slice(this, start, end) +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } +function isUndefined(arg) { + return arg === void 0; } +exports.isUndefined = isUndefined; -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +exports.isObject = isObject; -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 +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; } +exports.isDate = isDate; -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 +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); } +exports.isError = isError; -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 +function isFunction(arg) { + return typeof arg === 'function'; } +exports.isFunction = isFunction; -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) +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; -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 +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); } -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 '' + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); } -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 - } +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } +// 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(' '); +} - 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 +// 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)); +}; - if (this === target) return 0 - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) +/** + * 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'); - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; } + return origin; +}; - if (x < y) return -1 - if (y < x) return 1 - return 0 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -// 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 +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":83,"_process":90,"inherits":81}],85:[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 */ - // 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) - } +'use strict' - // 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 - } +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 - // 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) - } +/** + * 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. - throw new TypeError('val must be string, number or Buffer') -} + * 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() -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() - 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 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 read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} - 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 - } - } +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 { - 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 + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) } + that.length = length } - return -1 + return that } -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} +/** + * 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. + */ -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +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.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +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 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 - } +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') } - // 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 + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) } - 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 + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) } - return i -} -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + return fromObject(that, value) } -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) +/** + * 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) } -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, 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 base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) +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 ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +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) } -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 +/** + * 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 } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) } + return that +} - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining +/** + * 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) +} - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' } - if (!encoding) encoding = 'utf8' + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + var actual = that.write(string, encoding) - case 'ascii': - return asciiWrite(this, string, offset, length) + 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) + } - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + return that +} - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +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 +} - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') } -} -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') } -} -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) } else { - return base64.fromByteArray(buf.slice(start, end)) + 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 utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) - 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 (that.length === 0) { + return that + } - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint + obj.copy(that, 0, 0, len) + return that + } - 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 (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 (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 + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) } - - res.push(codePoint) - i += bytesPerSequence } - return decodeCodePointsArray(res) + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } -// 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() +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 +} - // 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) - ) +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 } - return res + return Buffer.alloc(+length) } -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 +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) } -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]) +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - return ret -} -function hexSlice (buf, start, end) { - var len = buf.length + if (a === b) return 0 - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len + var x = a.length + var y = b.length - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } } - return out + + if (x < y) return -1 + if (y < x) return 1 + return 0 } -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) +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 } - 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 +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len + if (list.length === 0) { + return Buffer.alloc(0) } - 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] + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length } } - return newBuf + 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 } -/* - * 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') -} +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 + } -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + var len = string.length + if (len === 0) return 0 - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul + // 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 + } } - - return val } +Buffer.byteLength = byteLength -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } +function slowToString (encoding, start, end) { + var loweredCase = false - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul + // 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 '' } - return val -} + if (end === undefined || end > this.length) { + end = this.length + } -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} + if (end <= 0) { + return '' + } -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} + if (end <= start) { + return '' + } -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) + if (!encoding) encoding = 'utf8' - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} + case 'ascii': + return asciiSlice(this, start, end) -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) + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - return val -} + case 'base64': + return base64Slice(this, start, end) -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } } - 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) +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i } -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.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.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) +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.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) +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.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) +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.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) +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 } -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.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.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) +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') } - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length } - 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) + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 } - return offset + byteLength -} + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 -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 -} + if (this === target) return 0 -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 - } -} + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) -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 -} + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) -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) + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } } - return offset + 2 + + if (x < y) return -1 + if (y < x) return 1 + return 0 } -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 - } -} +// 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 -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) + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 } - 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) + 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) } - 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) + // 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 + } - checkInt(this, value, offset, byteLength, limit - 1, -limit) + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) } - 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 + // 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 } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + 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) } - return offset + byteLength + throw new TypeError('val must be string, number or Buffer') } -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length - checkInt(this, value, offset, byteLength, limit - 1, -limit) + 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 + } } - 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 + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } - return offset + byteLength -} + 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 + } + } -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 + return -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.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 } -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.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } -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.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } -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) +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining } else { - objectWriteUInt32(this, value, offset, false) + length = Number(length) + if (length > remaining) { + length = remaining + } } - 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') -} + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + if (length > strLen / 2) { + length = strLen / 2 } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 + 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 } -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) } -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 +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } -// 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] +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 { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } - 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 - } + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining - // 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 ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } - if (end <= start) { - return this - } + if (!encoding) encoding = 'utf8' - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - if (!val) val = 0 + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - 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] - } - } + case 'ascii': + return asciiWrite(this, string, offset, length) - return this -} + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) -// HELPER FUNCTIONS -// ================ + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) -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 + '=' + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } - return str } -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } } -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } } -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 +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] - continue - } + 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 - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint - // 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) + 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 + } + } + } } - 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') + 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 bytes + return decodeCodePointsArray(res) } -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) +// 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() } - return byteArray + + // 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 utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) } - - return byteArray + return ret } -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) -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] + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) } - return i + return ret } -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} +function hexSlice (buf, start, end) { + var len = buf.length -}).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. + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out } -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; +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 +} -// 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; +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end -// 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; -}; + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - if (!this._events) - this._events = {}; + if (end < start) end = start - // 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; - } + 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] } } - handler = this._events[type]; - - if (isUndefined(handler)) - return false; + return newBuf +} - 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); - } +/* + * 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') +} - return true; -}; +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -EventEmitter.prototype.addListener = function(type, listener) { - var m; + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + return val +} - if (!this._events) - this._events = {}; +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } - // 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); + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } - 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]; + return val +} - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} - 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(); - } - } - } +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} - return this; -}; +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} -EventEmitter.prototype.on = EventEmitter.prototype.addListener; +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} - var fired = false; +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - function g() { - this.removeListener(type, g); + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} - if (!fired) { - fired = true; - listener.apply(this, arguments); - } +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 - g.listener = listener; - this.on(type, g); + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - return this; -}; + return val +} -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - if (!this._events || !this._events[type]) - return this; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - list = this._events[type]; - length = list.length; - position = -1; + return val +} - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); +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) +} - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } +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 +} - if (position < 0) - return this; +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 +} - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} - return this; -}; +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} - if (!this._events) - return this; +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} - // 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; - } +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} - // 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; - } +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} - listeners = this._events[type]; +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} - 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]; +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') +} - return this; -}; +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) + } -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; -}; + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + return offset + byteLength +} - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; +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) } - return 0; -}; -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } -function isFunction(arg) { - return typeof arg === 'function'; + return offset + byteLength } -function isNumber(arg) { - return typeof arg === 'number'; +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 isObject(arg) { - return typeof arg === 'object' && arg !== null; +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 + } } -function isUndefined(arg) { - return arg === void 0; +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 } -},{}],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) {} +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 +} - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} +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 + } +} - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) +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 { - m = m + Math.pow(2, mLen) - e = e - eBias + objectWriteUInt32(this, value, offset, true) } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + return offset + 4 } -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 +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 +} - value = Math.abs(value) +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) - 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 - } + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - 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 + 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 } - 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 + return offset + byteLength } -},{}],84:[function(require,module,exports){ -var toString = {}.toString; +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } -},{}],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; + 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 } - 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; - } + return offset + byteLength +} - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value +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 +} - // 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; - } +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 +} - 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; +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 +} - 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; +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 +} - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; +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 { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; + objectWriteUInt32(this, value, offset, false) } + return offset + 4 +} - // 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; +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') +} - 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"; +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 +} - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; +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":79,"buffer":85,"ieee754":87,"isarray":88}],86:[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; +} + +},{}],87:[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 +} + +},{}],88:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],89:[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 TYPE_NAME_TABLE = { + 0: 'number', + 1: 'any', + 2: 'string', + 3: 'array', + 4: 'object', + 5: 'boolean', + 6: 'expression', + 7: 'null', + 8: 'Array', + 9: 'Array' + }; + + 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, @@ -17649,10 +19307,8 @@ module.exports = Array.isArray || function (arr) { 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; + return node; case TOK_NOT: right = this.expression(bindingPower.Not); return {type: "NotExpression", children: [right]}; @@ -17686,10 +19342,8 @@ module.exports = Array.isArray || function (arr) { right = this._parseProjectionRHS(bindingPower.Star); return {type: "Projection", children: [{type: "Identity"}, right]}; - } else { - return this._parseMultiselectList(); } - break; + return this._parseMultiselectList(); case TOK_CURRENT: return {type: TOK_CURRENT}; case TOK_EXPREF: @@ -17721,13 +19375,11 @@ module.exports = Array.isArray || function (arr) { 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; + // Creating a projection. + this._advance(); + right = this._parseProjectionRHS(rbp); + return {type: "ValueProjection", children: [left, right]}; case TOK_PIPE: right = this.expression(bindingPower.Pipe); return {type: TOK_PIPE, children: [left, right]}; @@ -17781,13 +19433,11 @@ module.exports = Array.isArray || function (arr) { 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; + this._match(TOK_STAR); + this._match(TOK_RBRACKET); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", children: [left, right]}; default: this._errorToken(this._lookaheadToken(0)); } @@ -17964,19 +19614,15 @@ module.exports = Array.isArray || function (arr) { 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)) { + if (value !== null && isObject(value)) { field = value[node.name]; if (field === undefined) { return null; } else { return field; } - } else { - return null; } - break; + return null; case "Subexpression": result = this.visit(node.children[0], value); for (i = 1; i < node.children.length; i++) { @@ -18347,11 +19993,16 @@ module.exports = Array.isArray || function (arr) { } } if (!typeMatched) { + var expected = currentSpec + .map(function(typeIdentifier) { + return TYPE_NAME_TABLE[typeIdentifier]; + }) + .join(','); throw new Error("TypeError: " + name + "() " + "expected argument " + (i + 1) + - " to be type " + currentSpec + - " but received type " + actualType + - " instead."); + " to be type " + expected + + " but received type " + + TYPE_NAME_TABLE[actualType] + " instead."); } } }, @@ -18764,7 +20415,7 @@ module.exports = Array.isArray || function (arr) { exports.strictDeepEqual = strictDeepEqual; })(typeof exports === "undefined" ? this.jmespath = {} : exports); -},{}],86:[function(require,module,exports){ +},{}],90:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -18934,202 +20585,23 @@ 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; -} +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; -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; -}; +process.listeners = function (name) { return [] } -},{}],89:[function(require,module,exports){ -'use strict'; +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -},{"./decode":87,"./encode":88}],90:[function(require,module,exports){ +},{}],91:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -19201,7 +20673,7 @@ module.exports = function(qs, sep, eq, options) { if (!hasOwnProperty(obj, k)) { obj[k] = v; - } else if (Array.isArray(obj[k])) { + } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; @@ -19211,154 +20683,11 @@ module.exports = function(qs, sep, eq, options) { 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)); +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],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 @@ -19370,1540 +20699,1689 @@ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : // 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; +// 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 u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} +'use strict'; -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; - var rest = url; + case 'boolean': + return v ? 'true' : 'false'; - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); + case 'number': + return isFinite(v) ? v : ''; - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); + default: + return ''; } +}; - // 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; - } +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; } - 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; - } + 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); - // 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); - } + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; - // 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; +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); +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; +} - // pull out port. - this.parseHost(); +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; +}; - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; +},{}],93:[function(require,module,exports){ +'use strict'; - // 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] === ']'; +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); - // 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; - } - } - } - } +},{"./decode":91,"./encode":92}],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. - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } +'use strict'; - 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('.'); - } +// 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); +} - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; - // 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; - } - } + if (typeof qs !== 'string' || qs.length === 0) { + return obj; } - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { + var regexp = /\+/g; + qs = qs.split(sep); - // 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); - } + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; } - - // 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 len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } - 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); + + 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 = ''; } - 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; + 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]; + } } - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; + return obj; }; -// 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(); -} +},{}],95:[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. -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } +'use strict'; - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; - 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; - } - } + case 'boolean': + return v ? 'true' : 'false'; - if (this.query && - isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; } +}; - var search = this.search || (query && ('?' + query)) || ''; +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + 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); - // 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; + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); +},{}],96:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"./decode":94,"./encode":95,"dup":93}],97:[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; - return protocol + host + pathname + search + hash; +// 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 urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); +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); +}; -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); +// 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; }; -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} +exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { + delete immediateIds[id]; +}; +}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) +},{"process/browser.js":90,"timers":97}],98:[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. -Url.prototype.resolveObject = function(relative) { - if (isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } +var punycode = require('punycode'); - var result = new Url(); - Object.keys(this).forEach(function(k) { - result[k] = this[k]; - }, this); +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; +exports.Url = Url; - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } +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; +} - // 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]; - }); +// Reference: RFC 3986, RFC 1808, RFC 2396 - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } +// 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]*$/, - result.href = result.format(); - return result; - } + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - 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; - } + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - 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; - } + // 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'); - 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]; +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; - // 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] === ''); - } + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} - 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; +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } - 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; - } + var rest = url; - // 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 === ''); + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); - // 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--; - } + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); } - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); + // 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 (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } + // 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 - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. - // 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(); + // 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; } - } - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + // 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); + } - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } + // 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); + } - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } + // 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; - //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; -}; + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); -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); + // 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; + } + } + } } - host = host.substr(0, host.length - port.length); - } - if (host) this.hostname = host; -}; -function isString(arg) { - return typeof arg === "string"; -} + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} + 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('.'); + } -function isNull(arg) { - return arg === null; -} -function isNullOrUndefined(arg) { - return arg == null; -} + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; -},{"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 + // 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; } - }); - }; -} 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. + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { -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])); + // 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); } - 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); + + // 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 = {}; } - return str; + 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(); +} -// 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); - }; +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; } - if (process.noDeprecation === true) { - return fn; - } + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; - 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; + 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; } - return fn.apply(this, arguments); } - return deprecated; -}; + if (this.query && + isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + var search = this.search || (query && ('?' + query)) || ''; -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() {}; - } + 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 = ''; } - return debugs[set]; -}; + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; -/** - * 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; + 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); +} -// 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] +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); }; -// 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 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; + } -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + var result = new Url(); + Object.keys(this).forEach(function(k) { + result[k] = this[k]; + }, this); - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + // 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]; + }); -function stylizeNoColor(str, styleType) { - return str; -} + //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; + } -function arrayToHash(array) { - var hash = {}; + 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; + } - array.forEach(function(val, idx) { - hash[val] = true; - }); + 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; + } - return hash; -} + 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] === ''); + } -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); + 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--; } - 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); + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } } - // 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); + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); } - // 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); - } + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); } - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; + // 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(); + } } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); } - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + //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; +}; - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); +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; +}; - 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); - }); - } +function isString(arg) { + return typeof arg === "string"; +} - ctx.seen.pop(); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - return reduceToSingleString(output, base, braces); +function isNull(arg) { + return arg === null; +} +function isNullOrUndefined(arg) { + return arg == null; } +},{"punycode":82,"querystring":93}],99:[function(require,module,exports){ +"use strict"; -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'); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; +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 -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; + 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(''); } +var _default = bytesToUuid; +exports.default = _default; +},{}],100:[function(require,module,exports){ +"use strict"; -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'); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; } - 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'); - } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; } - 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'); - } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +},{"./v1.js":104,"./v3.js":105,"./v4.js":107,"./v5.js":108}],101:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Array(msg.length); + + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } - return name + ': ' + str; + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); } +/* + * Convert an array of little-endian words to an array of bytes + */ -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); +function md5ToHexEncodedArray(input) { + var i; + var x; + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + var hex; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; + for (i = 0; i < length32; i += 8) { + x = input[i >> 5] >>> i % 32 & 0xff; + hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + return output; } +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ -// 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); +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[(len + 64 >>> 9 << 4) + 14] = len; + var i; + var olda; + var oldb; + var oldc; + var oldd; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; } -exports.isArray = isArray; +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; +function bytesToWords(input) { + var i; + var output = []; + output[(input.length >> 2) - 1] = undefined; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; + } -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + var length8 = input.length * 8; -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + for (i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } -function isSymbol(arg) { - return typeof arg === 'symbol'; + return output; } -exports.isSymbol = isSymbol; +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ -function isUndefined(arg) { - return arg === void 0; + +function safeAdd(x, y) { + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; } -exports.isUndefined = isUndefined; +/* + * Bitwise rotate a 32-bit number to the left. + */ -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; } -exports.isRegExp = isRegExp; +/* + * These functions implement the four basic operations the algorithm uses. + */ -function isObject(arg) { - return typeof arg === 'object' && arg !== null; + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } -exports.isObject = isObject; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); } -exports.isDate = isDate; -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); } -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'; +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); } -exports.isPrimitive = isPrimitive; -exports.isBuffer = require('./support/isBuffer'); +var _default = md5; +exports.default = _default; +},{}],102:[function(require,module,exports){ +"use strict"; -function objectToString(o) { - return Object.prototype.toString.call(o); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, +// find the complete implementation of crypto (msCrypto) on IE11. +var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto); +var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef +function rng() { + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); + return getRandomValues(rnds8); } +},{}],103:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; -// 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(' '); -} + case 1: + return x ^ y ^ z; + case 2: + return x & y ^ x & z ^ y & z; -// 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)); -}; + case 3: + return x ^ y ^ z; + } +} +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} -/** - * 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'); +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + if (typeof bytes == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + bytes = new Array(msg.length); + + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } - return origin; -}; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} + bytes.push(0x80); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); -}).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'); + for (var i = 0; i < N; i++) { + M[i] = new Array(16); -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; + for (var j = 0; j < 16; j++) { + M[i][j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + } -module.exports = uuid; + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; -},{"./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); -} + for (var i = 0; i < N; i++) { + var W = new Array(80); -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(''); -} + for (var t = 0; t < 16; t++) W[t] = M[i][t]; -module.exports = bytesToUuid; + for (var t = 16; t < 80; t++) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } -},{}],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); + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; - 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; + for (var t = 0; t < 80; t++) { + var s = Math.floor(t / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; } - return rnds; - }; + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; } -},{}],101:[function(require,module,exports){ -var rng = require('./lib/rng'); -var bytesToUuid = require('./lib/bytesToUuid'); +var _default = sha1; +exports.default = _default; +},{}],104:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _bytesToUuid = _interopRequireDefault(require("./bytesToUuid.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // **`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 _clockseq; // Previous uuid creation time + + var _lastMSecs = 0; -var _lastNSecs = 0; +var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details -// 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 + 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(); + var seedBytes = options.random || (options.rng || _rng.default)(); + 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] - ]; + 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, + } // 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 + + 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; + 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 - // 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 + } // 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 + - // 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'); + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; - _clockseq = clockseq; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; + msecs += 12219292800000; // `time_low` - // `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; + b[i++] = tl & 0xff; // `time_mid` - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` - // `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; + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - // `clock_seq_low` - b[i++] = clockseq & 0xff; + b[i++] = clockseq & 0xff; // `node` - // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } - return buf ? buf : bytesToUuid(b); + return buf ? buf : (0, _bytesToUuid.default)(b); +} + +var _default = v1; +exports.default = _default; +},{"./bytesToUuid.js":99,"./rng.js":102}],105:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; +},{"./md5.js":101,"./v35.js":106}],106:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +exports.URL = exports.DNS = void 0; + +var _bytesToUuid = _interopRequireDefault(require("./bytesToUuid.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function uuidToBytes(uuid) { + // Note: We assume we're being passed a valid uuid string + var bytes = []; + uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) { + bytes.push(parseInt(hex, 16)); + }); + return bytes; +} + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + var bytes = new Array(str.length); + + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + var generateUUID = function (value, namespace, buf, offset) { + var off = buf && offset || 0; + if (typeof value == 'string') value = stringToBytes(value); + if (typeof namespace == 'string') namespace = uuidToBytes(namespace); + if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); + if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); // Per 4.3 + + var bytes = hashfunc(namespace.concat(value)); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + for (var idx = 0; idx < 16; ++idx) { + buf[off + idx] = bytes[idx]; + } + } + + return buf || (0, _bytesToUuid.default)(bytes); + }; // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; } +},{"./bytesToUuid.js":99}],107:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -module.exports = v1; +var _rng = _interopRequireDefault(require("./rng.js")); -},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(require,module,exports){ -var rng = require('./lib/rng'); -var bytesToUuid = require('./lib/bytesToUuid'); +var _bytesToUuid = _interopRequireDefault(require("./bytesToUuid.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { var i = buf && offset || 0; - if (typeof(options) == 'string') { + if (typeof options == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } + options = options || {}; - var rnds = options.random || (options.rng || rng)(); + var rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // 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 + 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); + return buf || (0, _bytesToUuid.default)(rnds); } -module.exports = v4; +var _default = v4; +exports.default = _default; +},{"./bytesToUuid.js":99,"./rng.js":102}],108:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); -},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(require,module,exports){ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; +},{"./sha1.js":103,"./v35.js":106}],109:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LRU_1 = require("./utils/LRU"); @@ -20935,13 +22413,16 @@ var EndpointCache = /** @class */ (function () { var now = Date.now(); var records = this.cache.get(keyString); if (records) { - for (var i = 0; i < records.length; i++) { + for (var i = records.length-1; i >= 0; i--) { var record = records[i]; if (record.Expire < now) { - this.cache.remove(keyString); - return undefined; + records.splice(i, 1); } } + if (records.length === 0) { + this.cache.remove(keyString); + return undefined; + } } return records; }; @@ -20973,7 +22454,7 @@ var EndpointCache = /** @class */ (function () { return EndpointCache; }()); exports.EndpointCache = EndpointCache; -},{"./utils/LRU":104}],104:[function(require,module,exports){ +},{"./utils/LRU":110}],110:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedListNode = /** @class */ (function () { @@ -21081,8 +22562,8 @@ var LRUCache = /** @class */ (function () { return LRUCache; }()); exports.LRUCache = LRUCache; -},{}],105:[function(require,module,exports){ -// AWS SDK for JavaScript v2.553.0 +},{}],111:[function(require,module,exports){ +// AWS SDK for JavaScript v2.1189.0 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt require('./browser_loader'); @@ -21108,13 +22589,6 @@ if (typeof self !== 'undefined') self.AWS = AWS; } 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]); +},{"../apis/connect-2017-02-15.min":3,"./browser_loader":16,"./core":19}]},{},[111]); diff --git a/src/client.js b/src/client.js index 68034ab5..60622ef7 100644 --- a/src/client.js +++ b/src/client.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function() { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/core.js b/src/core.js index 8b71bc57..cfd18188 100644 --- a/src/core.js +++ b/src/core.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -363,7 +363,7 @@ }); }); }; - + /** * 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. @@ -1494,12 +1494,17 @@ * 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. + * + * "caseId" is an optional parameter which is passed when a task is created from a Kesytone case */ - connect.core.activateChannelWithViewType = function (viewType, mediaType, source) { + connect.core.activateChannelWithViewType = function (viewType, mediaType, source, caseId) { const data = { viewType, mediaType }; if (source) { data.source = source; } + if (caseId) { + data.caseId = caseId; + } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, data diff --git a/src/event.js b/src/event.js index 3b9790a1..7934478f 100644 --- a/src/event.js +++ b/src/event.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; @@ -49,6 +49,7 @@ 'authorize_success', 'authorize_retries_exhausted', 'cti_authorize_retries_exhausted', + 'click_stream_data' ]); /**--------------------------------------------------------------- diff --git a/src/index.d.ts b/src/index.d.ts index d947ec5a..a3915673 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -219,6 +219,7 @@ declare namespace connect { AUTHORIZE_SUCCESS = 'authorize_success', AUTHORIZE_RETRIES_EXHAUSTED = 'authorize_retries_exhausted', CTI_AUTHORIZE_RETRIES_EXHAUSTED = 'cti_authorize_retries_exhausted', + CLICK_STREAM_DATA = 'click_stream_data' } const core: Core; @@ -640,6 +641,12 @@ declare namespace connect { OTHER = "other", } + enum ClickType { + ACCEPT = "Accept", + REJECT = "Reject", + HANGUP = "Hangup", + } + enum CTIExceptions { ACCESS_DENIED_EXCEPTION = "AccessDeniedException", INVALID_STATE_EXCEPTION = "InvalidStateException", diff --git a/src/lib/amazon-connect-websocket-manager.js b/src/lib/amazon-connect-websocket-manager.js index 9b8b3729..28997b51 100644 --- a/src/lib/amazon-connect-websocket-manager.js +++ b/src/lib/amazon-connect-websocket-manager.js @@ -1,2 +1,2 @@ -!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){"use strict";var o=t(1),r="NULL",i="CLIENT_LOGGER",c="DEBUG",s=2e3,a="aws/subscribe",u="aws/unsubscribe",l="aws/heartbeat",f="connected",p="disconnected";function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var b={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return b.assertTrue(null!==e&&void 0!==d(e),Object(o.sprintf)("%s must be provided",n||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==d(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},g=new RegExp("^(wss://)\\w*");b.validWSUrl=function(e){return g.test(e)},b.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},b.assertIsObject=function(e,n){if(!b.isObject(e))throw new Error(n+" is not an object!")},b.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},b.isNetworkOnline=function(){return navigator.onLine},b.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var y=b;function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,n){return!n||"object"!==m(n)&&"function"!=typeof n?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):n}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function k(e,n){return(k=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function v(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function w(e,n){for(var t=0;t=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var n=e.prefix||"";return this._logsDestination===c?this.consoleLoggerWrapper:new N(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||O.DEBUG,this._clientLogger=n.logger||null,this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}}]),e}(),W=function(){function e(){v(this,e)}return C(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),N=function(e){function n(e){var t;return v(this,n),(t=S(this,h(n).call(this))).prefix=e||"",t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&k(e,n)}(n,W),C(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:s;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}var n,t,o;return n=e,(t=[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout(function(){e._execute()},this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}}])&&F(n.prototype,t),o&&F(n,o),e}();t.d(n,"a",function(){return R});var x=function(){var e=E.getLogger({}),n=y.isNetworkOnline(),t={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},c={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},b={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},g=new L(function(){U()}),m=new Set([a,u,l]),S=setInterval(function(){if(n!==y.isNetworkOnline()){if(!(n=y.isNetworkOnline()))return void J(e.info("Network offline"));var t=O();n&&(!t||w(t,WebSocket.CLOSING)||w(t,WebSocket.CLOSED))&&(J(e.info("Network online, connecting to WebSocket server")),U())}},250),h=function(n,t){n.forEach(function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}})},k=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},v=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+k(t.primary)+" | Secondary WebSocket: "+k(t.secondary)))},w=function(e,n){return e&&e.readyState===n},C=function(e){return w(e,WebSocket.OPEN)},T=function(e){return null===e||void 0===e.readyState||w(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},I=function(){return C(O())},W=function(){if(i.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void U();I()?(J(e.debug("Sending heartbeat")),O().send(G(l)),i.pendingResponse=!0):(J(e.warn("Failed to send heartbeat since WebSocket is not open")),v("sendHeartBeat"),U())},N=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},_=function(){b.consecutiveFailedSubscribeAttempts=0,b.consecutiveNoResponseRequest=0,clearInterval(b.responseCheckIntervalId),clearInterval(b.reSubscribeIntervalId)},F=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},x=function(){try{J(e.info("WebSocket connection established!")),v("webSocketOnOpen"),null!==o.connState&&o.connState!==p||h(c.connectionGain),o.connState=f;var n=Date.now();h(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?n-r.noOpenConnectionsTimestamp:null}),F(),N(),O().openTimestamp=Date.now(),0===d.subscribed.size&&C(t.secondary)&&D(t.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(C(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach(function(e){d.subscriptionHistory.add(e),d.pending.add(e)}),d.subscribed.clear(),A()),W(),i.intervalHandle=setInterval(W,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U()},a)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},R=function(n){v("webSocketOnError"),J(e.error("WebSocketManager Error, error_event: ",JSON.stringify(n))),U()},j=function(n){var o=JSON.parse(n.data);switch(o.topic){case a:if(J(e.debug("Subscription Message received from webSocket server",n.data)),b.requestCompleted=!0,b.consecutiveNoResponseRequest=0,"success"===o.content.status)b.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)}),0===d.subscriptionHistory.size?C(t.secondary)&&(J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),D(t.primary,"[Primary WebSocket] Closing WebSocket")):A(),h(c.subscriptionUpdate,o);else{if(clearInterval(b.reSubscribeIntervalId),++b.consecutiveFailedSubscribeAttempts,5===b.consecutiveFailedSubscribeAttempts)return h(c.subscriptionFailure,o),void(b.consecutiveFailedSubscribeAttempts=0);b.reSubscribeIntervalId=setInterval(function(){A()},500)}break;case l:J(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(J(e.debug("Message received for topic "+o.topic)),C(t.primary)&&C(t.secondary)&&0===d.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));h(c.allMessage,o),c.topic.has(o.topic)&&h(c.topic.get(o.topic),o)}else o.message?J(e.warn("WebSocketManager Message Error",o)):J(e.warn("Invalid incoming message",o))}},A=function n(){if(b.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void h(c.subscriptionFailure,y.getSubscriptionResponse(a,!1,Array.from(d.pending)));I()?0!==Array.from(d.pending).length&&(clearInterval(b.responseCheckIntervalId),O().send(G(a,{topics:Array.from(d.pending)})),b.requestCompleted=!1,b.responseCheckIntervalId=setInterval(function(){b.requestCompleted||(++b.consecutiveNoResponseRequest,n())},1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},D=function(n,t){w(n,WebSocket.CONNECTING)||w(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+k(n)))},M=function(e){D(t.primary,"[Primary] WebSocket "+e),D(t.secondary,"[Secondary] WebSocket "+e)},P=function(){r.connectWebSocketRetryCount++;var n=y.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=s.connConfig.urlConnValidTime?(J(e.debug("Scheduling WebSocket reinitialization, after delay "+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return q()},n),o.exponentialBackOffTime*=2):(J(e.warn("WebSocket URL cannot be used to establish connection")),U())},H=function(n){N(),_(),J(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(S),h(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),F()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(y.isObject(n)&&y.isObject(n.webSocketTransport)&&y.isNonEmptyString(n.webSocketTransport.url)&&y.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){if(y.isNetworkOnline())if(o.websocketInitFailed)J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return N(),J(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then(function(n){return s.promiseCompleted=!0,J(e.debug("Successfully fetched webSocket connection configuration",n)),z(n)?(s.connConfig=n,s.connConfig.urlConnValidTime=Date.now()+85e3,g.connected(),q()):(H("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return s.promiseCompleted=!0,J(e.error("Failed to fetch webSocket connection configuration",n)),y.isNetworkFailure(n)?(J(e.info("Retrying fetching new WebSocket connection configuration")),g.retry()):H("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else J(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},q=function(){if(o.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!y.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.info("Initializing Websocket Manager")),v("initWebSocket");try{if(z(s.connConfig)){var n=null;return C(t.primary)?(J(e.debug("Primary Socket connection is already open")),w(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),t.secondary=B()),n=t.secondary):(w(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){C(n)||P()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),H("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(s.connConfig.webSocketTransport.url);return n.addEventListener("open",x),n.addEventListener("message",j),n.addEventListener("error",R),n.addEventListener("close",function(i){return function(n,i){J(e.info("Socket connection is closed",JSON.stringify(n))),v("webSocketOnClose before-cleanup"),h(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),T(t.primary)&&(t.primary=null),T(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(C(t.primary)||C(t.secondary)?T(t.primary)&&C(t.secondary)&&(J(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===p?J(e.info("Ignoring connectionLost callback invocation")):(h(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=p,U()),v("webSocketOnClose after-cleanup"))}(i,n)}),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(y.assertTrue(y.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.initFailure.add(e),o.websocketInitFailed&&e(),function(){return c.initFailure.delete(e)}},this.onConnectionOpen=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionOpen.add(e),function(){return c.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionClose.add(e),function(){return c.connectionClose.delete(e)}},this.onConnectionGain=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionGain.add(e),I()&&e(),function(){return c.connectionGain.delete(e)}},this.onConnectionLost=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionLost.add(e),o.connState===p&&e(),function(){return c.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionFailure.add(e),function(){return c.subscriptionFailure.delete(e)}},this.onMessage=function(e,n){return y.assertNotNull(e,"topicName"),y.assertTrue(y.isFunction(n),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(n):c.topic.set(e,new Set([n])),function(){return c.topic.get(e).delete(n)}},this.onAllMessage=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){y.assertNotNull(e,"topics"),y.assertIsList(e),e.forEach(function(e){d.subscribed.has(e)||d.pending.add(e)}),b.consecutiveNoResponseRequest=0,A()},this.sendMessage=function(n){if(y.assertIsObject(n,"payload"),void 0===n.topic||m.has(n.topic))J(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}I()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){N(),_(),o.reconnectWebSocket=!1,clearInterval(S),M("User request to close WebSocket")},this.terminateWebSocketManager=H},R={create:function(){return new x},setGlobalConfig:function(e){var n=e.loggerConfig;E.updateLoggerConfig(n)},LogLevel:O,Logger:T}},function(e,n,t){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,s,a,u,l,f,p,d=1,b=e.length,g="";for(o=0;o=0),s.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,s.width?parseInt(s.width):0);break;case"e":t=s.precision?parseFloat(t).toExponential(s.precision):parseFloat(t).toExponential();break;case"f":t=s.precision?parseFloat(t).toFixed(s.precision):parseFloat(t);break;case"g":t=s.precision?String(Number(t.toPrecision(s.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=s.precision?t.substring(0,s.precision):t;break;case"t":t=String(!!t),t=s.precision?t.substring(0,s.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=s.precision?t.substring(0,s.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=s.precision?t.substring(0,s.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(s.type)?g+=t:(!r.number.test(s.type)||f&&!s.sign?p="":(p=f?"+":"-",t=t.toString().replace(r.sign,"")),u=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",l=s.width-(p+t).length,a=s.width&&l>0?u.repeat(l):"",g+=s.align?p+t+a:"0"===u?p+a+t:a+p+t)}return g}(function(e){if(s[e])return s[e];var n,t=e,o=[],i=0;for(;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],a=n[2],u=[];if(null===(u=r.key.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(a=a.substring(u[0].length));)if(null!==(u=r.key_access.exec(a)))c.push(u[1]);else{if(null===(u=r.index_access.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return s[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var s=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); +!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",a=2e3,s="AMZ_WEB_SOCKET_MANAGER:",u="Network offline",l="Network online, connecting to WebSocket server",f="Network offline, ignoring this getWebSocketConnConfig request",d="Heartbeat response not received",p="Heartbeat response received",g="Sending heartbeat",b="Failed to send heartbeat since WebSocket is not open",y="WebSocket connection established!",m="WebSocket connection is closed",v="WebSocketManager Error, error_event: ",S="Scheduling WebSocket reinitialization, after delay ",h="WebSocket URL cannot be used to establish connection",k="WebSocket Initialization failed - Terminating and cleaning subscriptions",w="Terminating WebSocket Manager",C="Fetching new WebSocket connection configuration",L="Successfully fetched webSocket connection configuration",T="Failed to fetch webSocket connection configuration",O="Retrying fetching new WebSocket connection configuration",W="Initializing Websocket Manager",I="Initializing Websocket Manager Failed!",N="Websocket connection open",_="Websocket connection close",E="Websocket connection gain",F="Websocket connection lost",A="Websocket subscription failure",R="Reset Websocket state",x="WebSocketManager Message Error",D="Message received for topic ",j="Invalid incoming message",M="WebsocketManager invoke callbacks for topic success ",G="aws/subscribe",z="aws/unsubscribe",P="aws/heartbeat",H="connected",U="disconnected";function q(e){return(q="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 J={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return J.assertTrue(null!==e&&void 0!==q(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"!==q(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},B=new RegExp("^(wss://)\\w*");J.validWSUrl=function(e){return B.test(e)},J.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},J.assertIsObject=function(e,n){if(!J.isObject(e))throw new Error(n+" is not an object!")},J.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)},J.isNetworkOnline=function(){return navigator.onLine},J.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var V=J;function X(e,n){return!n||"object"!==Z(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 $(e){return($=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function K(e,n){return(K=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function Z(e){return(Z="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 Q(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function Y(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||te;return this._logsDestination===c?this.consoleLoggerWrapper:new ce(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||oe.INFO,this._advancedLogWriter="warn",n.advancedLogWriter&&(this._advancedLogWriter=n.advancedLogWriter),n.customizedLogger&&"object"===Z(n.customizedLogger)&&(this.useClientLogger=!0),this._clientLogger=n.logger||this.selectLogger(n),this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}},{key:"selectLogger",value:function(e){return e.customizedLogger&&"object"===Z(e.customizedLogger)?e.customizedLogger:e.useDefaultLogger?(this.consoleLoggerWrapper=ae(),this.consoleLoggerWrapper):null}}]),e}(),ie=function(){function e(){Q(this,e)}return ee(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}},{key:"advancedLog",value:function(){}}]),e}(),ce=function(e){function n(e){var t;return Q(this,n),(t=X(this,$(n).call(this))).prefix=e||te,t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&K(e,n)}(n,ie),ee(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:a;!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}},{key:"getIsConnected",value:function(){return!this.numAttempts}}])&&ue(n.prototype,t),o&&ue(n,o),e}();t.d(n,"a",function(){return de});var fe=function(){var e=se.getLogger({prefix:s}),n=V.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},a={connConfig:null,promiseHandle:null,promiseCompleted:!0},q={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},J={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},B=new le(function(){he()}),X=new Set([G,z,P]),$=setInterval(function(){if(n!==V.isNetworkOnline()){if(!(n=V.isNetworkOnline()))return e.advancedLog(u),void Ce(e.info(u));var t=te();n&&(!t||Y(t,WebSocket.CLOSING)||Y(t,WebSocket.CLOSED))&&(e.advancedLog(l),Ce(e.info(l)),he())}},250),K=function(n,t){n.forEach(function(n){try{n(t)}catch(n){Ce(e.error("Error executing callback",n))}})},Z=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"}},Q=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";Ce(e.debug("["+n+"] Primary WebSocket: "+Z(t.primary)+" | Secondary WebSocket: "+Z(t.secondary)))},Y=function(e,n){return e&&e.readyState===n},ee=function(e){return Y(e,WebSocket.OPEN)},ne=function(e){return null===e||void 0===e.readyState||Y(e,WebSocket.CLOSED)},te=function(){return null!==t.secondary?t.secondary:t.primary},oe=function(){return ee(te())},re=function(){if(i.pendingResponse)return e.advancedLog(d),Ce(e.warn(d)),clearInterval(i.intervalHandle),i.pendingResponse=!1,void he();oe()?(Ce(e.debug(g)),te().send(ve(P)),i.pendingResponse=!0):(e.advancedLog(b),Ce(e.warn(b)),Q("sendHeartBeat"),he())},ie=function(){e.advancedLog(R),o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},ce=function(){J.consecutiveFailedSubscribeAttempts=0,J.consecutiveNoResponseRequest=0,clearInterval(J.responseCheckIntervalId),clearInterval(J.reSubscribeIntervalId)},ae=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},ue=function(){B.connected();try{e.advancedLog(y),Ce(e.info(y)),Q("webSocketOnOpen"),null!==o.connState&&o.connState!==U||K(c.connectionGain),o.connState=H;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}),ae(),ie(),te().openTimestamp=Date.now(),0===q.subscribed.size&&ee(t.secondary)&&ge(t.primary,"[Primary WebSocket] Closing WebSocket"),(q.subscribed.size>0||q.pending.size>0)&&(ee(t.secondary)&&Ce(e.info("Subscribing secondary websocket to topics of primary websocket")),q.subscribed.forEach(function(e){q.subscriptionHistory.add(e),q.pending.add(e)}),q.subscribed.clear(),pe()),re(),i.intervalHandle=setInterval(re,1e4);var s=1e3*a.connConfig.webSocketTransport.transportLifeTimeInSeconds;Ce(e.debug("Scheduling WebSocket manager reconnection, after delay "+s+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){Ce(e.debug("Starting scheduled WebSocket manager reconnection")),he()},s)}catch(n){Ce(e.error("Error after establishing WebSocket connection",n))}},fe=function(n){Q("webSocketOnError"),e.advancedLog(v,JSON.stringify(n)),Ce(e.error(v,JSON.stringify(n))),B.getIsConnected()?he():B.retry()},de=function(n){var o=JSON.parse(n.data);switch(o.topic){case G:if(Ce(e.debug("Subscription Message received from webSocket server",n.data)),J.requestCompleted=!0,J.consecutiveNoResponseRequest=0,"success"===o.content.status)J.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){q.subscriptionHistory.delete(e),q.pending.delete(e),q.subscribed.add(e)}),0===q.subscriptionHistory.size?ee(t.secondary)&&(Ce(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),ge(t.primary,"[Primary WebSocket] Closing WebSocket")):pe(),K(c.subscriptionUpdate,o);else{if(clearInterval(J.reSubscribeIntervalId),++J.consecutiveFailedSubscribeAttempts,5===J.consecutiveFailedSubscribeAttempts)return K(c.subscriptionFailure,o),void(J.consecutiveFailedSubscribeAttempts=0);J.reSubscribeIntervalId=setInterval(function(){pe()},500)}break;case P:Ce(e.debug(p)),i.pendingResponse=!1;break;default:if(o.topic){if(e.advancedLog(D,o.topic),Ce(e.debug(D+o.topic)),ee(t.primary)&&ee(t.secondary)&&0===q.subscriptionHistory.size&&this===t.primary)return void Ce(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void Ce(e.warn("No registered callback listener for Topic",o.topic));e.advancedLog(M,o.topic),K(c.allMessage,o),c.topic.has(o.topic)&&K(c.topic.get(o.topic),o)}else o.message?(e.advancedLog(x,o),Ce(e.warn(x,o))):(e.advancedLog(j,o),Ce(e.warn(j,o)))}},pe=function n(){if(J.consecutiveNoResponseRequest>3)return Ce(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void K(c.subscriptionFailure,V.getSubscriptionResponse(G,!1,Array.from(q.pending)));oe()?0!==Array.from(q.pending).length&&(clearInterval(J.responseCheckIntervalId),te().send(ve(G,{topics:Array.from(q.pending)})),J.requestCompleted=!1,J.responseCheckIntervalId=setInterval(function(){J.requestCompleted||(++J.consecutiveNoResponseRequest,n())},1e3)):Ce(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},ge=function(n,t){Y(n,WebSocket.CONNECTING)||Y(n,WebSocket.OPEN)?n.close(1e3,t):Ce(e.warn("Ignoring WebSocket Close request, WebSocket State: "+Z(n)))},be=function(e){ge(t.primary,"[Primary] WebSocket "+e),ge(t.secondary,"[Secondary] WebSocket "+e)},ye=function(){r.connectWebSocketRetryCount++;var n=V.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=a.connConfig.urlConnValidTime?(e.advancedLog(S),Ce(e.debug(S+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return ke()},n),o.exponentialBackOffTime*=2):(e.advancedLog(h),Ce(e.warn(h)),he())},me=function(n){ie(),ce(),e.advancedLog(k,n),Ce(e.error(k)),o.websocketInitFailed=!0,be(w),clearInterval($),K(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),ae()},ve=function(e,n){return JSON.stringify({topic:e,content:n})},Se=function(n){return!!(V.isObject(n)&&V.isObject(n.webSocketTransport)&&V.isNonEmptyString(n.webSocketTransport.url)&&V.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(Ce(e.error("Invalid WebSocket Connection Configuration",n)),!1)},he=function(){if(!V.isNetworkOnline())return e.advancedLog(f),void Ce(e.info(f));if(o.websocketInitFailed)Ce(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(a.promiseCompleted)return ie(),e.advancedLog(C),Ce(e.info(C)),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),a.promiseCompleted=!1,a.promiseHandle=c.getWebSocketTransport(),a.promiseHandle.then(function(n){return a.promiseCompleted=!0,e.advancedLog(L),Ce(e.debug(L,n)),Se(n)?(a.connConfig=n,a.connConfig.urlConnValidTime=Date.now()+85e3,ke()):(me("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return a.promiseCompleted=!0,e.advancedLog(T),Ce(e.error(T,n)),V.isNetworkFailure(n)?(e.advancedLog(O+JSON.stringify(n)),Ce(e.info(O+JSON.stringify(n))),B.retry()):me("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});Ce(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}},ke=function(){if(o.websocketInitFailed)return Ce(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!V.isNetworkOnline())return Ce(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};e.advancedLog(W),Ce(e.info(W)),Q("initWebSocket");try{if(Se(a.connConfig)){var n=null;return ee(t.primary)?(Ce(e.debug("Primary Socket connection is already open")),Y(t.secondary,WebSocket.CONNECTING)||(Ce(e.debug("Establishing a secondary web-socket connection")),B.numAttempts=0,t.secondary=we()),n=t.secondary):(Y(t.primary,WebSocket.CONNECTING)||(Ce(e.debug("Establishing a primary web-socket connection")),t.primary=we()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){ee(n)||ye()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return Ce(e.error("Error Initializing web-socket-manager",n)),me("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},we=function(){var n=new WebSocket(a.connConfig.webSocketTransport.url);return n.addEventListener("open",ue),n.addEventListener("message",de),n.addEventListener("error",fe),n.addEventListener("close",function(i){return function(n,i){e.advancedLog(m,JSON.stringify(n)),Ce(e.info(m,JSON.stringify(n))),Q("webSocketOnClose before-cleanup"),K(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),ne(t.primary)&&(t.primary=null),ne(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(ee(t.primary)||ee(t.secondary)?ne(t.primary)&&ee(t.secondary)&&(Ce(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(Ce(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===U?Ce(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=U,he()),Q("webSocketOnClose after-cleanup"))}(i,n)}),n},Ce=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(V.assertTrue(V.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,he();Ce(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(n){return e.advancedLog(I),V.assertTrue(V.isFunction(n),"cb must be a function"),c.initFailure.add(n),o.websocketInitFailed&&n(),function(){return c.initFailure.delete(n)}},this.onConnectionOpen=function(n){return e.advancedLog(N),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionOpen.add(n),function(){return c.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return e.advancedLog(_),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionClose.add(n),function(){return c.connectionClose.delete(n)}},this.onConnectionGain=function(n){return e.advancedLog(E),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionGain.add(n),oe()&&n(),function(){return c.connectionGain.delete(n)}},this.onConnectionLost=function(n){return e.advancedLog(F),V.assertTrue(V.isFunction(n),"cb must be a function"),c.connectionLost.add(n),o.connState===U&&n(),function(){return c.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(e){return V.assertTrue(V.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(n){return e.advancedLog(A),V.assertTrue(V.isFunction(n),"cb must be a function"),c.subscriptionFailure.add(n),function(){return c.subscriptionFailure.delete(n)}},this.onMessage=function(e,n){return V.assertNotNull(e,"topicName"),V.assertTrue(V.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 V.assertTrue(V.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){V.assertNotNull(e,"topics"),V.assertIsList(e),e.forEach(function(e){q.subscribed.has(e)||q.pending.add(e)}),J.consecutiveNoResponseRequest=0,pe()},this.sendMessage=function(n){if(V.assertIsObject(n,"payload"),void 0===n.topic||X.has(n.topic))Ce(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void Ce(e.warn("Error stringify message",n))}oe()?te().send(n):Ce(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){ie(),ce(),o.reconnectWebSocket=!1,clearInterval($),be("User request to close WebSocket")},this.terminateWebSocketManager=me},de={create:function(){return new fe},setGlobalConfig:function(e){var n=e&&e.loggerConfig;se.updateLoggerConfig(n)},LogLevel:oe,Logger:ne}},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,a,s,u,l,f,d,p=1,g=e.length,b="";for(o=0;o=0),a.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,a.width?parseInt(a.width):0);break;case"e":t=a.precision?parseFloat(t).toExponential(a.precision):parseFloat(t).toExponential();break;case"f":t=a.precision?parseFloat(t).toFixed(a.precision):parseFloat(t);break;case"g":t=a.precision?String(Number(t.toPrecision(a.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=a.precision?t.substring(0,a.precision):t;break;case"t":t=String(!!t),t=a.precision?t.substring(0,a.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=a.precision?t.substring(0,a.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=a.precision?t.substring(0,a.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(a.type)?b+=t:(!r.number.test(a.type)||f&&!a.sign?d="":(d=f?"+":"-",t=t.toString().replace(r.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(d+t).length,s=a.width&&l>0?u.repeat(l):"",b+=a.align?d+t+s:"0"===u?d+s+t:s+d+t)}return b}(function(e){if(a[e])return a[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=[],s=n[2],u=[];if(null===(u=r.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(s=s.substring(u[0].length));)if(null!==(u=r.key_access.exec(s)))c.push(u[1]);else{if(null===(u=r.index_access.exec(s)))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 a[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var a=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); //# sourceMappingURL=amazon-connect-websocket-manager.js.map diff --git a/src/lib/amazon-connect-websocket-manager.js.map b/src/lib/amazon-connect-websocket-manager.js.map index 6157b434..e24953b7 100644 --- a/src/lib/amazon-connect-websocket-manager.js.map +++ b/src/lib/amazon-connect-websocket-manager.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/constants.js","webpack:///./src/utils.js","webpack:///./src/log.js","webpack:///./src/retryProvider.js","webpack:///./src/webSocketManager.js","webpack:///./node_modules/sprintf-js/src/sprintf.js","webpack:///./src/index.js","webpack:///(webpack)/buildin/global.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","LOGS_DESTINATION","WEBSOCKET_RETRY_RATE_MS","ROUTE_KEY","CONN_STATE","Utils","premise","message","Error","assertTrue","undefined","_typeof","sprintf","length","Array","isArray","obj","constructor","apply","wsRegex","RegExp","validWSUrl","wsUrl","test","getSubscriptionResponse","routeKey","isSuccess","topicList","topic","content","status","topics","assertIsObject","isObject","addJitter","base","maxJitter","arguments","Math","min","sign","random","floor","isNetworkOnline","navigator","onLine","isNetworkFailure","reason","_debug","type","Logger","data","LogLevel","DEBUG","INFO","WARN","ERROR","LogManagerImpl","_classCallCheck","this","updateLoggerConfig","consoleLoggerWrapper","createConsoleLogger","level","logStatement","hasClientLogger","_clientLogger","debug","info","warn","error","_level","options","prefix","_logsDestination","LoggerWrapperImpl","inputConfig","config","logger","LoggerWrapper","_this","_possibleConstructorReturn","_getPrototypeOf","_len","args","_key","_log","_len2","_key2","_len3","_key3","_len4","_key4","LogManager","isLevelEnabled","writeToClientLogger","_shouldLog","_convertToSingleStatement","_writeToClientLogger","index","arg","_convertToString","isString","isFunction","toString","toStringResult","JSON","stringify","console","RetryProvider","executor","defaultRetry","retryProvider_classCallCheck","numAttempts","hasActiveReconnection","setTimeout","_execute","_getDelay","calculatedDelay","pow","__webpack_exports__","WebSocketManagerObject","WebSocketManager","getLogger","online","webSocket","primary","secondary","reconnectConfig","reconnectWebSocket","websocketInitFailed","exponentialBackOffTime","exponentialTimeoutHandle","lifeTimeTimeoutHandle","webSocketInitCheckerTimeoutId","connState","metrics","connectWebSocketRetryCount","connectionAttemptStartTime","noOpenConnectionsTimestamp","heartbeatConfig","pendingResponse","intervalHandle","callbacks","initFailure","Set","getWebSocketTransport","subscriptionUpdate","subscriptionFailure","Map","allMessage","connectionGain","connectionLost","connectionOpen","connectionClose","webSocketConfig","connConfig","promiseHandle","promiseCompleted","topicSubscription","subscribed","pending","subscriptionHistory","topicSubscriptionConfig","responseCheckIntervalId","requestCompleted","reSubscribeIntervalId","consecutiveFailedSubscribeAttempts","consecutiveNoResponseRequest","reconnectionClient","getWebSocketConnConfig","invalidSendMessageRouteKeys","networkConnectivityChecker","setInterval","sendInternalLogToServer","ws","getDefaultWebSocket","isWebSocketState","WebSocket","CLOSING","CLOSED","invokeCallbacks","response","forEach","callback","getWebSocketStates","readyState","CONNECTING","OPEN","printWebSocketState","event","webSocketStateCode","isWebSocketOpen","isWebSocketClosed","isDefaultWebSocketOpen","sendHeartBeat","clearInterval","send","createWebSocketPayload","resetWebSocketState","clearTimeout","resetSubscriptions","resetMetrics","webSocketOnOpen","now","Date","connectionEstablishedTime","timeToConnect","timeWithoutConnection","openTimestamp","size","closeSpecificWebSocket","add","clear","subscribePendingTopics","webSocketLifetimeTimeout","webSocketTransport","transportLifeTimeInSeconds","webSocketOnError","webSocketOnMessage","parse","topicName","has","from","close","closeWebSocket","retryWebSocketInitialization","waitTime","urlConnValidTime","initWebSocket","terminateWebSocketManager","validWebSocketConnConfig","isNonEmptyString","url","then","connected","webSocketConnectionFailed","retry","getNewWebSocket","addEventListener","closeTimestamp","connectionDuration","code","webSocketOnClose","logEntry","init","transportHandle","onInitFailure","cb","onConnectionOpen","onConnectionClose","onConnectionGain","onConnectionLost","onSubscriptionUpdate","onSubscriptionFailure","onMessage","assertNotNull","set","onAllMessage","subscribeTopics","assertIsList","sendMessage","payload","setGlobalConfig","loggerConfig","__WEBPACK_AMD_DEFINE_RESULT__","re","not_string","not_bool","not_type","not_primitive","number","numeric_arg","json","not_json","text","modulo","placeholder","key_access","index_access","parse_tree","argv","k","ph","pad","pad_character","pad_length","is_positive","cursor","tree_length","output","keys","param_no","Function","isNaN","TypeError","parseInt","String","fromCharCode","width","precision","parseFloat","toExponential","toFixed","Number","toPrecision","substring","slice","toLowerCase","valueOf","toUpperCase","replace","pad_char","charAt","repeat","align","sprintf_format","fmt","sprintf_cache","match","_fmt","arg_names","exec","push","SyntaxError","field_list","replacement_field","field_match","sprintf_parse","vsprintf","concat","window","global","_webSocketManager__WEBPACK_IMPORTED_MODULE_0__","connect","g","e"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,KAQvDrB,EAAoBsB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQrB,EAAoBqB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFA1B,EAAoBkB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOrB,EAAoBU,EAAEe,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,GAIRzB,EAAoB6B,EAAI,SAAS1B,GAChC,IAAIS,EAAST,GAAUA,EAAOqB,WAC7B,WAAwB,OAAOrB,EAAgB,SAC/C,WAA8B,OAAOA,GAEtC,OADAH,EAAoBU,EAAEE,EAAQ,IAAKA,GAC5BA,GAIRZ,EAAoBa,EAAI,SAASiB,EAAQC,GAAY,OAAOjB,OAAOkB,UAAUC,eAAe1B,KAAKuB,EAAQC,IAGzG/B,EAAoBkC,EAAI,GAIjBlC,EAAoBA,EAAoBmC,EAAI,G,0CCjFxCC,EACL,OADKA,EAEI,gBAFJA,EAGJ,QAYIC,EAA0B,IAK1BC,EACA,gBADAA,EAEE,kBAFFA,EAGA,gBAGAC,EACA,YADAA,EAEG,e,qOC1BhB,IAAMC,EAAQ,CAKdA,WAAmB,SAASC,EAASC,GACnC,IAAKD,EACH,MAAM,IAAIE,MAAMD,IAOpBF,cAAsB,SAASnB,EAAOV,GAKpC,OAJA6B,EAAMI,WACM,OAAVvB,QAAmCwB,IAAjBC,EAAOzB,GACzB0B,kBAAQ,sBAAuBpC,GAAQ,YAElCU,GAGTmB,iBAAyB,SAASnB,GAChC,MAAwB,iBAAVA,GAAsBA,EAAM2B,OAAS,GAGrDR,aAAqB,SAASnB,EAAOM,GACnC,IAAKsB,MAAMC,QAAQ7B,GACjB,MAAM,IAAIsB,MAAMhB,EAAM,qBAQ1Ba,WAAmB,SAASW,GAC1B,SAAUA,GAAOA,EAAIC,aAAeD,EAAI5C,MAAQ4C,EAAIE,QAGtDb,SAAiB,SAASnB,GACxB,QAA0B,WAAjByB,EAAOzB,IAAgC,OAAVA,IAGxCmB,SAAiB,SAASnB,GACxB,MAAwB,iBAAVA,GAGhBmB,SAAiB,SAASnB,GACxB,MAAwB,iBAAVA,IAGViC,EAAU,IAAIC,OAAO,iBAC3Bf,EAAMgB,WAAa,SAAUC,GAC3B,OAAOH,EAAQI,KAAKD,IAGtBjB,EAAMmB,wBAA0B,SAACC,EAAUC,EAAWC,GACpD,MAAO,CACLC,MAAOH,EACPI,QAAU,CACRC,OAAQJ,EAAY,UAAY,UAChCK,OAAQJ,KAKdtB,EAAM2B,eAAiB,SAAS9C,EAAOM,GACrC,IAAKa,EAAM4B,SAAS/C,GAClB,MAAM,IAAIsB,MAAMhB,EAAM,uBAI1Ba,EAAM6B,UAAY,SAAUC,GAAqB,IAAfC,EAAeC,UAAAxB,OAAA,QAAAH,IAAA2B,UAAA,GAAAA,UAAA,GAAH,EAC5CD,EAAYE,KAAKC,IAAIH,EAAW,GAChC,IAAMI,EAAOF,KAAKG,SAAW,GAAM,GAAK,EACxC,OAAOH,KAAKI,MAAMP,EAAOK,EAAOL,EAAOG,KAAKG,SAAWL,IAGzD/B,EAAMsC,gBAAkB,kBAAMC,UAAUC,QAExCxC,EAAMyC,iBAAmB,SAACC,GACxB,SAAGA,EAAOC,SAAUD,EAAOC,OAAOC,ODlEL,oBCmEpBF,EAAOC,OAAOC,MAKV5C,Q,k8BCvFT6C,E,0EACEC,M,2BAEDA,M,2BAEAA,M,4BAECA,Q,KAIFC,EAAW,CACfC,MAAO,GACPC,KAAM,GACNC,KAAM,GACNC,MAAO,IAGHC,E,WACJ,SAAAA,IAAcC,EAAAC,KAAAF,GACZE,KAAKC,qBACLD,KAAKE,qBAAuBC,I,sDAGVC,EAAOC,GACzB,GAAKL,KAAKM,kBAGV,OAAQF,GACN,KAAKX,EAASC,MACZ,OAAOM,KAAKO,cAAcC,MAAMH,GAClC,KAAKZ,EAASE,KACZ,OAAOK,KAAKO,cAAcE,KAAKJ,GACjC,KAAKZ,EAASG,KACZ,OAAOI,KAAKO,cAAcG,KAAKL,GACjC,KAAKZ,EAASI,MACZ,OAAOG,KAAKO,cAAcI,MAAMN,M,qCAIvBD,GACb,OAAOA,GAASJ,KAAKY,S,wCAIrB,OAA8B,OAAvBZ,KAAKO,gB,gCAGJM,GACR,IAAIC,EAASD,EAAQC,QAAU,GAC/B,OAAId,KAAKe,mBAAqBzE,EACrB0D,KAAKE,qBAEP,IAAIc,EAAkBF,K,yCAGZG,GACjB,IAAIC,EAASD,GAAe,GAC5BjB,KAAKY,OAASM,EAAOd,OAASX,EAASC,MACvCM,KAAKO,cAAgBW,EAAOC,QAAU,KACtCnB,KAAKe,iBAAmBzE,EACpB4E,EAAOV,QACTR,KAAKe,iBAAmBzE,GAEtB4E,EAAOC,SACTnB,KAAKe,iBAAmBzE,O,KAKxB8E,E,uLAUAJ,E,YACJ,SAAAA,EAAYF,GAAQ,IAAAO,EAAA,OAAAtB,EAAAC,KAAAgB,IAClBK,EAAAC,EAAAtB,KAAAuB,EAAAP,GAAAvG,KAAAuF,QACKc,OAASA,GAAU,GAFNO,E,4OADUD,G,mCAMf,QAAAI,EAAA9C,UAAAxB,OAANuE,EAAM,IAAAtE,MAAAqE,GAAAE,EAAA,EAAAA,EAAAF,EAAAE,IAAND,EAAMC,GAAAhD,UAAAgD,GACb,OAAO1B,KAAK2B,KAAKlC,EAASC,MAAO+B,K,6BAGrB,QAAAG,EAAAlD,UAAAxB,OAANuE,EAAM,IAAAtE,MAAAyE,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANJ,EAAMI,GAAAnD,UAAAmD,GACZ,OAAO7B,KAAK2B,KAAKlC,EAASE,KAAM8B,K,6BAGpB,QAAAK,EAAApD,UAAAxB,OAANuE,EAAM,IAAAtE,MAAA2E,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANN,EAAMM,GAAArD,UAAAqD,GACZ,OAAO/B,KAAK2B,KAAKlC,EAASG,KAAM6B,K,8BAGnB,QAAAO,EAAAtD,UAAAxB,OAANuE,EAAM,IAAAtE,MAAA6E,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANR,EAAMQ,GAAAvD,UAAAuD,GACb,OAAOjC,KAAK2B,KAAKlC,EAASI,MAAO4B,K,iCAGxBrB,GACT,OAAO8B,EAAW5B,mBAAqB4B,EAAWC,eAAe/B,K,2CAG9CA,EAAOC,GAC1B,OAAO6B,EAAWE,oBAAoBhC,EAAOC,K,2BAG1CD,EAAOqB,GACV,GAAIzB,KAAKqC,WAAWjC,GAAQ,CAC1B,IAAIC,EAAeL,KAAKsC,0BAA0Bb,GAClD,OAAOzB,KAAKuC,qBAAqBnC,EAAOC,M,gDAIlBoB,GACxB,IAAIpB,EAAe,GACfL,KAAKc,SACPT,GAAgBL,KAAKc,OAAS,KAEhC,IAAK,IAAI0B,EAAQ,EAAGA,EAAQf,EAAKvE,OAAQsF,IAAS,CAChD,IAAIC,EAAMhB,EAAKe,GACfnC,GAAgBL,KAAK0C,iBAAiBD,GAAO,IAE/C,OAAOpC,I,uCAGQoC,GACf,IACE,IAAKA,EACH,MAAO,GAET,GAAI/F,EAAMiG,SAASF,GACjB,OAAOA,EAET,GAAI/F,EAAM4B,SAASmE,IAAQ/F,EAAMkG,WAAWH,EAAII,UAAW,CACzD,IAAIC,EAAiBL,EAAII,WACzB,GAAuB,oBAAnBC,EACF,OAAOA,EAGX,OAAOC,KAAKC,UAAUP,GACtB,MAAO9B,GAEP,OADAsC,QAAQtC,MAAM,4CAA6C8B,EAAK9B,GACzD,Q,KAKTR,EAAsB,WACxB,IAAIgB,EAAS,IAAIC,EAKjB,OAJAD,EAAOX,MAAQyC,QAAQzC,MACvBW,EAAOV,KAAOwC,QAAQxC,KACtBU,EAAOT,KAAOuC,QAAQvC,KACtBS,EAAOR,MAAQsC,QAAQtC,MAChBQ,GAGHe,EAAa,IAAIpC,E,0KClKjBoD,E,WACJ,SAAAA,EAAYC,GAAkD,IAAxCC,EAAwC1E,UAAAxB,OAAA,QAAAH,IAAA2B,UAAA,GAAAA,UAAA,GAAzBnC,G,4FAAyB8G,CAAArD,KAAAkD,GAC5DlD,KAAKsD,YAAc,EACnBtD,KAAKmD,SAAWA,EAChBnD,KAAKuD,uBAAwB,EAC7BvD,KAAKoD,aAAeA,E,uDAGd,IAAA/B,EAAArB,KAEFA,KAAKuD,wBACPvD,KAAKuD,uBAAwB,EAC7BC,WAAW,WACTnC,EAAKoC,YACJzD,KAAK0D,gB,iCAKV1D,KAAKuD,uBAAwB,EAC7BvD,KAAKmD,WACLnD,KAAKsD,gB,kCAILtD,KAAKsD,YAAc,I,kCAInB,IAAMK,EAAkBhF,KAAKiF,IAAI,EAAG5D,KAAKsD,aAAetD,KAAKoD,aAC7D,OAAOO,GHfgC,IGeiBA,EHfjB,S,gCIjB3CzJ,EAAAU,EAAAiJ,EAAA,sBAAAC,IAiBA,IAAMC,EAAmB,WAErB,IAAM5C,EAASe,EAAW8B,UAAU,IAEhCC,EAASvH,EAAMsC,kBAEfkF,EAAY,CACZC,QAAS,KACTC,UAAW,MAGXC,EAAkB,CAClBC,oBAAoB,EACpBC,qBAAqB,EACrBC,uBAAwB,IACxBC,yBAA0B,KAC1BC,sBAAuB,KACvBC,8BAA+B,KAC/BC,UAAW,MAGXC,EAAU,CACVC,2BAA4B,EAC5BC,2BAA4B,KAC5BC,2BAA4B,MAG5BC,EAAkB,CAClBC,iBAAiB,EACjBC,eAAgB,MAGhBC,EAAY,CACZC,YAAa,IAAIC,IACjBC,sBAAuB,KACvBC,mBAAoB,IAAIF,IACxBG,oBAAqB,IAAIH,IACzBrH,MAAO,IAAIyH,IACXC,WAAY,IAAIL,IAChBM,eAAgB,IAAIN,IACpBO,eAAgB,IAAIP,IACpBQ,eAAgB,IAAIR,IACpBS,gBAAiB,IAAIT,KAGrBU,EAAkB,CAClBC,WAAY,KACZC,cAAe,KACfC,kBAAkB,GAGlBC,EAAoB,CACpBC,WAAY,IAAIf,IAChBgB,QAAS,IAAIhB,IACbiB,oBAAqB,IAAIjB,KAGzBkB,EAA0B,CAC1BC,wBAAyB,KACzBC,kBAAkB,EAClBC,sBAAuB,KACvBC,mCAAoC,EACpCC,6BAA8B,GAG5BC,EAAqB,IAAI5D,EAAc,WAAQ6D,MAE/CC,EAA8B,IAAI1B,IAAI,CAAC9I,EAAqBA,EAAuBA,IAEnFyK,EAA6BC,YAAY,WAC7C,GAAIjD,IAAWvH,EAAMsC,kBAAmB,CAElC,KADAiF,EAASvH,EAAMsC,mBAIX,YAFAmI,EAAwBhG,EAAOV,KAAK,oBAIxC,IAAM2G,EAAKC,IACPpD,KAAYmD,GAAME,EAAiBF,EAAIG,UAAUC,UAAYF,EAAiBF,EAAIG,UAAUE,WAC5FN,EAAwBhG,EAAOV,KAAK,mDAEpCsG,OJpF8B,KIyFpCW,EAAkB,SAAStC,EAAWuC,GACxCvC,EAAUwC,QAAQ,SAAUC,GACxB,IACIA,EAASF,GACX,MAAOhH,GACLwG,EAAwBhG,EAAOR,MAAM,2BAA4BA,QAKvEmH,EAAqB,SAASV,GAChC,GAAW,OAAPA,EAAa,MAAO,OACxB,OAAQA,EAAGW,YACP,KAAKR,UAAUS,WACX,MAAO,aACX,KAAKT,UAAUU,KACX,MAAO,OACX,KAAKV,UAAUC,QACX,MAAO,UACX,KAAKD,UAAUE,OACX,MAAO,SACX,QACI,MAAO,cAIbS,EAAsB,WAAsB,IAAZC,EAAYzJ,UAAAxB,OAAA,QAAAH,IAAA2B,UAAA,GAAAA,UAAA,GAAJ,GAC1CyI,EAAwBhG,EAAOX,MAAM,IAAM2H,EAAQ,wBAA0BL,EAAmB5D,EAAUC,SACpG,2BAAkC2D,EAAmB5D,EAAUE,cAGnEkD,EAAmB,SAASF,EAAIgB,GAClC,OAAOhB,GAAMA,EAAGW,aAAeK,GAG7BC,EAAkB,SAASjB,GAC7B,OAAOE,EAAiBF,EAAIG,UAAUU,OAGpCK,EAAoB,SAASlB,GAE/B,OAAc,OAAPA,QAAiCrK,IAAlBqK,EAAGW,YAA4BT,EAAiBF,EAAIG,UAAUE,SAQlFJ,EAAsB,WACxB,OAA4B,OAAxBnD,EAAUE,UACHF,EAAUE,UAEdF,EAAUC,SAGfoE,EAAyB,WAC3B,OAAOF,EAAgBhB,MAGrBmB,EAAgB,WAClB,GAAIvD,EAAgBC,gBAMhB,OALAiC,EAAwBhG,EAAOT,KAAK,oCAEpC+H,cAAcxD,EAAgBE,gBAC9BF,EAAgBC,iBAAkB,OAClC6B,IAGAwB,KACApB,EAAwBhG,EAAOX,MAAM,sBAErC6G,IAAsBqB,KAAKC,EAAuBnM,IAClDyI,EAAgBC,iBAAkB,IAElCiC,EAAwBhG,EAAOT,KAAK,yDAEpCwH,EAAoB,iBACpBnB,MAIF6B,EAAsB,WACxBvE,EAAgBG,uBAAyB,IACzCS,EAAgBC,iBAAkB,EAClCb,EAAgBC,oBAAqB,EAErCuE,aAAaxE,EAAgBK,uBAC7B+D,cAAcxD,EAAgBE,gBAC9B0D,aAAaxE,EAAgBI,0BAC7BoE,aAAaxE,EAAgBM,gCAG3BmE,EAAqB,WACvBtC,EAAwBI,mCAAqC,EAC7DJ,EAAwBK,6BAA+B,EACvD4B,cAAcjC,EAAwBC,yBACtCgC,cAAcjC,EAAwBG,wBAGpCoC,EAAe,WACjBlE,EAAQC,2BAA6B,EACrCD,EAAQE,2BAA6B,KACrCF,EAAQG,2BAA6B,MAGnCgE,EAAkB,WACpB,IACI7B,EAAwBhG,EAAOV,KAAK,sCAEpCyH,EAAoB,mBACc,OAA9B7D,EAAgBO,WAAsBP,EAAgBO,YAAcnI,GACpEiL,EAAgBtC,EAAUQ,gBAE9BvB,EAAgBO,UAAYnI,EAG5B,IAAMwM,EAAMC,KAAKD,MACjBvB,EAAgBtC,EAAUU,eAAgB,CACtChB,2BAA4BD,EAAQC,2BACpCC,2BAA4BF,EAAQE,2BACpCC,2BAA4BH,EAAQG,2BACpCmE,0BAA2BF,EAC3BG,cAAeH,EAAMpE,EAAQE,2BAC7BsE,sBACIxE,EAAQG,2BAA6BiE,EAAMpE,EAAQG,2BAA6B,OAGxF+D,IACAH,IACAvB,IAAsBiC,cAAgBJ,KAAKD,MAGD,IAAtC7C,EAAkBC,WAAWkD,MAAclB,EAAgBnE,EAAUE,YACrEoF,EAAuBtF,EAAUC,QAAS,0CAE1CiC,EAAkBC,WAAWkD,KAAO,GAAKnD,EAAkBE,QAAQiD,KAAO,KACtElB,EAAgBnE,EAAUE,YAC1B+C,EAAwBhG,EAAOV,KAAK,mEAExC2F,EAAkBC,WAAWuB,QAAQ,SAAA3J,GACjCmI,EAAkBG,oBAAoBkD,IAAIxL,GAC1CmI,EAAkBE,QAAQmD,IAAIxL,KAElCmI,EAAkBC,WAAWqD,QAC7BC,KAGJnB,IACAvD,EAAgBE,eAAiB+B,YAAYsB,EJpPpB,KIsPzB,IAAMoB,EAAsG,IAA3E5D,EAAgBC,WAAW4D,mBAAmBC,2BAC/E3C,EAAwBhG,EAAOX,MAAM,0DAA4DoJ,EAA2B,QAE5HvF,EAAgBK,sBAAwBlB,WAAW,WAC/C2D,EAAwBhG,EAAOX,MAAM,sDAErCuG,KACD6C,GACL,MAAOjJ,GACLwG,EAAwBhG,EAAOR,MAAM,gDAAiDA,MA4DxFoJ,EAAmB,SAAS5B,GAC9BD,EAAoB,oBACpBf,EAAwBhG,EAAOR,MAAM,wCAAyCoC,KAAKC,UAAUmF,KAE7FpB,KAGEiD,EAAqB,SAAS7B,GAChC,IAAMR,EAAW5E,KAAKkH,MAAM9B,EAAM3I,MAElC,OAAQmI,EAAS1J,OAEb,KAAKzB,EAMD,GALA2K,EAAwBhG,EAAOX,MAAM,sDAAuD2H,EAAM3I,OAElGgH,EAAwBE,kBAAmB,EAC3CF,EAAwBK,6BAA+B,EAEvB,YAA5Bc,EAASzJ,QAAQC,OACjBqI,EAAwBI,mCAAqC,EAC7De,EAASzJ,QAAQE,OAAOwJ,QAAS,SAAAsC,GAC7B9D,EAAkBG,oBAAlB,OAA6C2D,GAC7C9D,EAAkBE,QAAlB,OAAiC4D,GACjC9D,EAAkBC,WAAWoD,IAAIS,KAEc,IAA/C9D,EAAkBG,oBAAoBgD,KAClClB,EAAgBnE,EAAUE,aAC1B+C,EAAwBhG,EAAOV,KAAK,mFAEpC+I,EAAuBtF,EAAUC,QAAS,0CAG9CwF,IAEJjC,EAAgBtC,EAAUI,mBAAoBmC,OAE3C,CAGH,GAFAc,cAAcjC,EAAwBG,yBACpCH,EAAwBI,mCJ9VK,II+V3BJ,EAAwBI,mCAGxB,OAFAc,EAAgBtC,EAAUK,oBAAqBkC,QAC/CnB,EAAwBI,mCAAqC,GAGjEJ,EAAwBG,sBAAwBO,YAAY,WACxDyC,KJtW4B,KIyWpC,MAEJ,KAAKnN,EACD2K,EAAwBhG,EAAOX,MAAM,gCAErCyE,EAAgBC,iBAAkB,EAClC,MAEJ,QACI,GAAIyC,EAAS1J,MAAO,CAGhB,GAFAkJ,EAAwBhG,EAAOX,MAAM,8BAAgCmH,EAAS1J,QAE1EoK,EAAgBnE,EAAUC,UAAYkE,EAAgBnE,EAAUE,YACd,IAA/CgC,EAAkBG,oBAAoBgD,MAAcvJ,OAASkE,EAAUC,QAQ1E,YAFAgD,EAAwBhG,EAAOT,KAAK,8BAAgCiH,EAAS1J,MAAQ,0BAKzF,GAAkC,IAA9BmH,EAAUO,WAAW4D,MAAuC,IAAzBnE,EAAUnH,MAAMsL,KAGnD,YAFApC,EAAwBhG,EAAOT,KAAK,4CAA6CiH,EAAS1J,QAI9FyJ,EAAgBtC,EAAUO,WAAYgC,GAClCvC,EAAUnH,MAAMkM,IAAIxC,EAAS1J,QAC7ByJ,EAAgBtC,EAAUnH,MAAM9C,IAAIwM,EAAS1J,OAAQ0J,QAGlDA,EAAS/K,QAChBuK,EAAwBhG,EAAOT,KAAK,iCAAkCiH,IAEtER,EAAwBhG,EAAOT,KAAK,2BAA4BiH,MAM1EgC,EAAyB,SAAzBA,IACF,GAAInD,EAAwBK,6BJlZwB,EIsZhD,OAHAM,EAAwBhG,EAAOT,KAAK,2GAEpCgH,EAAgBtC,EAAUK,oBAAqB/I,EAAMmB,wBAAwBrB,GAAqB,EAAOW,MAAMiN,KAAKhE,EAAkBE,WAGrIiC,IAKgD,IAAjDpL,MAAMiN,KAAKhE,EAAkBE,SAASpJ,SAI1CuL,cAAcjC,EAAwBC,yBAEtCY,IAAsBqB,KAAKC,EAAuBnM,EAAqB,CACnE4B,OAAUjB,MAAMiN,KAAKhE,EAAkBE,YAE3CE,EAAwBE,kBAAmB,EAG3CF,EAAwBC,wBAA0BS,YAAY,WACrDV,EAAwBE,qBACvBF,EAAwBK,6BAC1B8C,MJ7a6C,MI0ZjDxC,EAAwBhG,EAAOT,KAAK,8EAwBtC8I,EAAyB,SAASpC,EAAIhI,GACpCkI,EAAiBF,EAAIG,UAAUS,aAAeV,EAAiBF,EAAIG,UAAUU,MAC7Eb,EAAGiD,MAAM,IAAMjL,GAEf+H,EAAwBhG,EAAOT,KAAK,sDAAwDoH,EAAmBV,MAIjHkD,EAAiB,SAASlL,GAC5BoK,EAAuBtF,EAAUC,QAAS,uBAAyB/E,GACnEoK,EAAuBtF,EAAUE,UAAW,yBAA2BhF,IAGrEmL,EAA+B,WACjC1F,EAAQC,6BACR,IAAM0F,EAAW9N,EAAM6B,UAAU8F,EAAgBG,uBJ9blB,II+b3B0E,KAAKD,MAAQuB,GAAYxE,EAAgBC,WAAWwE,kBACpDtD,EAAwBhG,EAAOX,MAAM,sDAAwDgK,EAAW,QAExGnG,EAAgBI,yBAA2BjB,WAAW,kBAAMkH,KAAiBF,GAC7EnG,EAAgBG,wBAA0B,IAE1C2C,EAAwBhG,EAAOT,KAAK,yDAEpCqG,MAIF4D,EAA4B,SAAUhD,GACxCiB,IACAE,IACA3B,EAAwBhG,EAAOR,MAAM,oCAErC0D,EAAgBE,qBAAsB,EACtC+F,EAAe,iCACf7B,cAAcxB,GACdS,EAAgBtC,EAAUC,YAAa,CACnCP,2BAA4BD,EAAQC,2BACpCC,2BAA4BF,EAAQE,2BACpC3F,OAAQuI,IAEZoB,KAGEJ,EAAyB,SAAU9M,EAAKqC,GAC1C,OAAO6E,KAAKC,UAAU,CAClB/E,MAASpC,EACTqC,QAAWA,KAuCb0M,EAA2B,SAAU3E,GACzC,SAAIvJ,EAAM4B,SAAS2H,IAAevJ,EAAM4B,SAAS2H,EAAW4D,qBACnDnN,EAAMmO,iBAAiB5E,EAAW4D,mBAAmBiB,MACrDpO,EAAMgB,WAAWuI,EAAW4D,mBAAmBiB,MACS,IAA3D7E,EAAW4D,mBAAmBC,4BJjhBD,OIohBjC3C,EAAwBhG,EAAOR,MAAM,6CAA8CsF,KAE5E,IAGLc,EAAyB,WAC3B,GAAKrK,EAAMsC,kBAKX,GAAIqF,EAAgBE,oBAChB4C,EAAwBhG,EAAOX,MAAM,gFADzC,CAKA,GAAKwF,EAAgBG,iBAWrB,OANAyC,IACAzB,EAAwBhG,EAAOV,KAAK,oDAEpCoE,EAAQE,2BAA6BF,EAAQE,4BAA8BmE,KAAKD,MAChFjD,EAAgBG,kBAAmB,EACnCH,EAAgBE,cAAgBd,EAAUG,wBACnCS,EAAgBE,cAClB6E,KAAK,SAASpD,GAIP,OAHA3B,EAAgBG,kBAAmB,EACnCgB,EAAwBhG,EAAOX,MAAM,0DAA2DmH,IAE3FiD,EAAyBjD,IAI9B3B,EAAgBC,WAAa0B,EAE7B3B,EAAgBC,WAAWwE,iBAAmBvB,KAAKD,MJxjB5B,KI0jBvBnC,EAAmBkE,YACZN,MARHC,EAA0B,+CAAiDhD,GACpE,CAAEsD,2BAA2B,KAS5C,SAAS7L,GAYL,OAXA4G,EAAgBG,kBAAmB,EACnCgB,EAAwBhG,EAAOR,MAAM,qDAAsDvB,IAGvF1C,EAAMyC,iBAAiBC,IACzB+H,EAAwBhG,EAAOV,KAAK,6DACpCqG,EAAmBoE,SAGjBP,EAA0B,uDAAyD5H,KAAKC,UAAU5D,IAE/F,CAAE6L,2BAA2B,KAtC5C9D,EAAwBhG,EAAOX,MAAM,0FAVrC2G,EAAwBhG,EAAOV,KAAK,mEAoDtCiK,EAAgB,WAClB,GAAIrG,EAAgBE,oBAGhB,OAFA4C,EAAwBhG,EAAOV,KAAK,yDAE7B,CAAEwK,2BAA2B,GAExC,IAAKvO,EAAMsC,kBAGP,OAFAmI,EAAwBhG,EAAOT,KAAK,+CAE7B,CAAEuK,2BAA2B,GAExC9D,EAAwBhG,EAAOV,KAAK,mCAEpCyH,EAAoB,iBACpB,IACI,GAAI0C,EAAyB5E,EAAgBC,YAAa,CACtD,IAAImB,EAAK,KAyBT,OAxBIiB,EAAgBnE,EAAUC,UAC1BgD,EAAwBhG,EAAOX,MAAM,8CAEhC8G,EAAiBpD,EAAUE,UAAWmD,UAAUS,cACjDb,EAAwBhG,EAAOX,MAAM,mDAErC0D,EAAUE,UAAY+G,KAE1B/D,EAAKlD,EAAUE,YAEVkD,EAAiBpD,EAAUC,QAASoD,UAAUS,cAC/Cb,EAAwBhG,EAAOX,MAAM,iDAErC0D,EAAUC,QAAUgH,KAExB/D,EAAKlD,EAAUC,SAInBE,EAAgBM,8BAAgCnB,WAAW,WAClD6E,EAAgBjB,IACjBmD,KAEL,KACI,CAAEU,2BAA2B,IAE1C,MAAOtK,GAIL,OAHAwG,EAAwBhG,EAAOR,MAAM,wCAAyCA,IAE9EgK,EAA0B,uCAAyChK,EAAM/D,SAClE,CAAEqO,2BAA2B,KAItCE,EAAkB,WACpB,IAAI/D,EAAK,IAAIG,UAAUvB,EAAgBC,WAAW4D,mBAAmBiB,KAKrE,OAJA1D,EAAGgE,iBAAiB,OAAQpC,GAC5B5B,EAAGgE,iBAAiB,UAAWpB,GAC/B5C,EAAGgE,iBAAiB,QAASrB,GAC7B3C,EAAGgE,iBAAiB,QAAS,SAAAjD,GAAK,OAnYb,SAASA,EAAOf,GACrCD,EAAwBhG,EAAOV,KAAK,8BAA+BsC,KAAKC,UAAUmF,KAElFD,EAAoB,mCAEpBR,EAAgBtC,EAAUW,gBAAiB,CACvCuD,cAAelC,EAAGkC,cAClB+B,eAAgBnC,KAAKD,MACrBqC,mBAAoBpC,KAAKD,MAAQ7B,EAAGkC,cACpCiC,KAAMpD,EAAMoD,KACZnM,OAAQ+I,EAAM/I,SAGdkJ,EAAkBpE,EAAUC,WAC5BD,EAAUC,QAAU,MAEpBmE,EAAkBpE,EAAUE,aAC5BF,EAAUE,UAAY,MAErBC,EAAgBC,qBAGhB+D,EAAgBnE,EAAUC,UAAakE,EAAgBnE,EAAUE,WAyB3DkE,EAAkBpE,EAAUC,UAAYkE,EAAgBnE,EAAUE,aACzE+C,EAAwBhG,EAAOV,KAAK,uCAEpCyD,EAAUC,QAAUD,EAAUE,UAC9BF,EAAUE,UAAY,OA5BtB+C,EAAwBhG,EAAOT,KAAK,uHAEhC2D,EAAgBO,YAAcnI,EAS9B0K,EAAwBhG,EAAOV,KAAK,iDAEpCiH,EAAgBtC,EAAUS,eAAgB,CACtCyD,cAAelC,EAAGkC,cAClB+B,eAAgBnC,KAAKD,MACrBqC,mBAAoBpC,KAAKD,MAAQ7B,EAAGkC,cACpCiC,KAAMpD,EAAMoD,KACZnM,OAAQ+I,EAAM/I,SAElByF,EAAQG,2BAA6BkE,KAAKD,OAE9C5E,EAAgBO,UAAYnI,EAC5BsK,KAOJmB,EAAoB,mCA8UkBsD,CAAiBrD,EAAOf,KACvDA,GAmFLD,EAA0B,SAAUsE,GAItC,OAHIA,GAAwD,mBAArCA,EAAStE,yBAC5BsE,EAAStE,0BAENsE,GAGXzL,KAAK0L,KAhDQ,SAASC,GAElB,GADAjP,EAAMI,WAAWJ,EAAMkG,WAAW+I,GAAkB,sCACZ,OAApCvG,EAAUG,sBAOd,OAFAH,EAAUG,sBAAwBoG,EAE3B5E,IANHI,EAAwBhG,EAAOT,KAAK,gDA8C5CV,KAAK4L,cA1DiB,SAASC,GAM3B,OALAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUC,YAAYoE,IAAIoC,GACtBxH,EAAgBE,qBAChBsH,IAEG,kBAAMzG,EAAUC,YAAV,OAA6BwG,KAqD9C7L,KAAK8L,iBAzFoB,SAASD,GAG9B,OAFAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUU,eAAe2D,IAAIoC,GACtB,kBAAMzG,EAAUU,eAAV,OAAgC+F,KAuFjD7L,KAAK+L,kBApFqB,SAASF,GAG/B,OAFAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUW,gBAAgB0D,IAAIoC,GACvB,kBAAMzG,EAAUW,gBAAV,OAAiC8F,KAkFlD7L,KAAKgM,iBA/EoB,SAASH,GAM9B,OALAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUQ,eAAe6D,IAAIoC,GACzBtD,KACAsD,IAEG,kBAAMzG,EAAUQ,eAAV,OAAgCiG,KA0EjD7L,KAAKiM,iBAvEoB,SAASJ,GAM9B,OALAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUS,eAAe4D,IAAIoC,GACzBxH,EAAgBO,YAAcnI,GAC9BoP,IAEG,kBAAMzG,EAAUS,eAAV,OAAgCgG,KAkEjD7L,KAAKkM,qBA1CwB,SAASL,GAGlC,OAFAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUI,mBAAmBiE,IAAIoC,GAC1B,kBAAMzG,EAAUI,mBAAV,OAAoCqG,KAwCrD7L,KAAKmM,sBArCyB,SAASN,GAGnC,OAFAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUK,oBAAoBgE,IAAIoC,GAC3B,kBAAMzG,EAAUK,oBAAV,OAAqCoG,KAmCtD7L,KAAKoM,UAhCa,SAASlC,EAAW2B,GAQlC,OAPAnP,EAAM2P,cAAcnC,EAAW,aAC/BxN,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACnCzG,EAAUnH,MAAMkM,IAAID,GACpB9E,EAAUnH,MAAM9C,IAAI+O,GAAWT,IAAIoC,GAEnCzG,EAAUnH,MAAMqO,IAAIpC,EAAW,IAAI5E,IAAI,CAACuG,KAErC,kBAAMzG,EAAUnH,MAAM9C,IAAI+O,GAApB,OAAsC2B,KAyBvD7L,KAAKuM,aAtBgB,SAAUV,GAG3B,OAFAnP,EAAMI,WAAWJ,EAAMkG,WAAWiJ,GAAK,yBACvCzG,EAAUO,WAAW8D,IAAIoC,GAClB,kBAAMzG,EAAUO,WAAV,OAA4BkG,KAoB7C7L,KAAKwM,gBA7OmB,SAASpO,GAC7B1B,EAAM2P,cAAcjO,EAAQ,UAC5B1B,EAAM+P,aAAarO,GAEnBA,EAAOwJ,QAAQ,SAAA3J,GACNmI,EAAkBC,WAAW8D,IAAIlM,IAClCmI,EAAkBE,QAAQmD,IAAIxL,KAItCuI,EAAwBK,6BAA+B,EACvD8C,KAmOJ3J,KAAK0M,YAnQe,SAASC,GAEzB,GADAjQ,EAAM2B,eAAesO,EAAS,gBACR5P,IAAlB4P,EAAQ1O,OAAuB+I,EAA4BmD,IAAIwC,EAAQ1O,OACvEkJ,EAAwBhG,EAAOT,KAAK,qCAAsCiM,QAD9E,CAKA,IACIA,EAAU5J,KAAKC,UAAU2J,GAC3B,MAAOhM,GAGL,YAFAwG,EAAwBhG,EAAOT,KAAK,0BAA2BiM,IAI/DpE,IACAlB,IAAsBqB,KAAKiE,GAE3BxF,EAAwBhG,EAAOT,KAAK,6DAoP5CV,KAAKsK,eAAiB,WAClB1B,IACAE,IACAzE,EAAgBC,oBAAqB,EACrCmE,cAAcxB,GACdqD,EAAe,oCAGnBtK,KAAK2K,0BAA4BA,GAY/B7G,EAAyB,CAC3BlI,OAVgC,WAChC,OAAO,IAAImI,GAUX6I,gBAPoB,SAAA1L,GACpB,IAAM2L,EAAe3L,EAAO2L,aAC5B3K,EAAWjC,mBAAmB4M,IAM9BpN,SAAUA,EACVF,OAAQA,I,gBC9wBZ,IAAAuN,GAEC,WACG,aAEA,IAAIC,EAAK,CACLC,WAAY,OACZC,SAAU,OACVC,SAAU,OACVC,cAAe,OACfC,OAAQ,UACRC,YAAa,eACbC,KAAM,MACNC,SAAU,OACVC,KAAM,YACNC,OAAQ,WACRC,YAAa,2FACb7R,IAAK,sBACL8R,WAAY,wBACZC,aAAc,aACd/O,KAAM,SAGV,SAAS5B,EAAQpB,GAEb,OAOJ,SAAwBgS,EAAYC,GAChC,IAAiDrL,EAAkBnI,EAAGyT,EAAGC,EAAIC,EAAKC,EAAeC,EAAYC,EAAavP,EAAtHwP,EAAS,EAAGC,EAAcT,EAAW3Q,OAAaqR,EAAS,GAC/D,IAAKjU,EAAI,EAAGA,EAAIgU,EAAahU,IACzB,GAA6B,iBAAlBuT,EAAWvT,GAClBiU,GAAUV,EAAWvT,QAEpB,GAA6B,iBAAlBuT,EAAWvT,GAAiB,CAExC,IADA0T,EAAKH,EAAWvT,IACTkU,KAEH,IADA/L,EAAMqL,EAAKO,GACNN,EAAI,EAAGA,EAAIC,EAAGQ,KAAKtR,OAAQ6Q,IAAK,CACjC,GAAWhR,MAAP0F,EACA,MAAM,IAAI5F,MAAMI,EAAQ,gEAAiE+Q,EAAGQ,KAAKT,GAAIC,EAAGQ,KAAKT,EAAE,KAEnHtL,EAAMA,EAAIuL,EAAGQ,KAAKT,SAItBtL,EADKuL,EAAGS,SACFX,EAAKE,EAAGS,UAGRX,EAAKO,KAOf,GAJItB,EAAGG,SAAStP,KAAKoQ,EAAG1O,OAASyN,EAAGI,cAAcvP,KAAKoQ,EAAG1O,OAASmD,aAAeiM,WAC9EjM,EAAMA,KAGNsK,EAAGM,YAAYzP,KAAKoQ,EAAG1O,OAAyB,iBAARmD,GAAoBkM,MAAMlM,GAClE,MAAM,IAAImM,UAAU3R,EAAQ,0CAA2CwF,IAO3E,OAJIsK,EAAGK,OAAOxP,KAAKoQ,EAAG1O,QAClB8O,EAAc3L,GAAO,GAGjBuL,EAAG1O,MACP,IAAK,IACDmD,EAAMoM,SAASpM,EAAK,IAAII,SAAS,GACjC,MACJ,IAAK,IACDJ,EAAMqM,OAAOC,aAAaF,SAASpM,EAAK,KACxC,MACJ,IAAK,IACL,IAAK,IACDA,EAAMoM,SAASpM,EAAK,IACpB,MACJ,IAAK,IACDA,EAAMM,KAAKC,UAAUP,EAAK,KAAMuL,EAAGgB,MAAQH,SAASb,EAAGgB,OAAS,GAChE,MACJ,IAAK,IACDvM,EAAMuL,EAAGiB,UAAYC,WAAWzM,GAAK0M,cAAcnB,EAAGiB,WAAaC,WAAWzM,GAAK0M,gBACnF,MACJ,IAAK,IACD1M,EAAMuL,EAAGiB,UAAYC,WAAWzM,GAAK2M,QAAQpB,EAAGiB,WAAaC,WAAWzM,GACxE,MACJ,IAAK,IACDA,EAAMuL,EAAGiB,UAAYH,OAAOO,OAAO5M,EAAI6M,YAAYtB,EAAGiB,aAAeC,WAAWzM,GAChF,MACJ,IAAK,IACDA,GAAOoM,SAASpM,EAAK,MAAQ,GAAGI,SAAS,GACzC,MACJ,IAAK,IACDJ,EAAMqM,OAAOrM,GACbA,EAAOuL,EAAGiB,UAAYxM,EAAI8M,UAAU,EAAGvB,EAAGiB,WAAaxM,EACvD,MACJ,IAAK,IACDA,EAAMqM,SAASrM,GACfA,EAAOuL,EAAGiB,UAAYxM,EAAI8M,UAAU,EAAGvB,EAAGiB,WAAaxM,EACvD,MACJ,IAAK,IACDA,EAAMzH,OAAOkB,UAAU2G,SAASpI,KAAKgI,GAAK+M,MAAM,GAAI,GAAGC,cACvDhN,EAAOuL,EAAGiB,UAAYxM,EAAI8M,UAAU,EAAGvB,EAAGiB,WAAaxM,EACvD,MACJ,IAAK,IACDA,EAAMoM,SAASpM,EAAK,MAAQ,EAC5B,MACJ,IAAK,IACDA,EAAMA,EAAIiN,UACVjN,EAAOuL,EAAGiB,UAAYxM,EAAI8M,UAAU,EAAGvB,EAAGiB,WAAaxM,EACvD,MACJ,IAAK,IACDA,GAAOoM,SAASpM,EAAK,MAAQ,GAAGI,SAAS,IACzC,MACJ,IAAK,IACDJ,GAAOoM,SAASpM,EAAK,MAAQ,GAAGI,SAAS,IAAI8M,cAGjD5C,EAAGO,KAAK1P,KAAKoQ,EAAG1O,MAChBiP,GAAU9L,IAGNsK,EAAGK,OAAOxP,KAAKoQ,EAAG1O,OAAW8O,IAAeJ,EAAGnP,KAK/CA,EAAO,IAJPA,EAAOuP,EAAc,IAAM,IAC3B3L,EAAMA,EAAII,WAAW+M,QAAQ7C,EAAGlO,KAAM,KAK1CqP,EAAgBF,EAAG6B,SAA2B,MAAhB7B,EAAG6B,SAAmB,IAAM7B,EAAG6B,SAASC,OAAO,GAAK,IAClF3B,EAAaH,EAAGgB,OAASnQ,EAAO4D,GAAKvF,OACrC+Q,EAAMD,EAAGgB,OAASb,EAAa,EAAID,EAAc6B,OAAO5B,GAAoB,GAC5EI,GAAUP,EAAGgC,MAAQnR,EAAO4D,EAAMwL,EAAyB,MAAlBC,EAAwBrP,EAAOoP,EAAMxL,EAAMwL,EAAMpP,EAAO4D,GAI7G,OAAO8L,EAjHA0B,CAsHX,SAAuBC,GACnB,GAAIC,EAAcD,GACd,OAAOC,EAAcD,GAGzB,IAAgBE,EAAZC,EAAOH,EAAYrC,EAAa,GAAIyC,EAAY,EACpD,KAAOD,GAAM,CACT,GAAqC,QAAhCD,EAAQrD,EAAGS,KAAK+C,KAAKF,IACtBxC,EAAW2C,KAAKJ,EAAM,SAErB,GAAuC,QAAlCA,EAAQrD,EAAGU,OAAO8C,KAAKF,IAC7BxC,EAAW2C,KAAK,SAEf,IAA4C,QAAvCJ,EAAQrD,EAAGW,YAAY6C,KAAKF,IA6ClC,MAAM,IAAII,YAAY,oCA5CtB,GAAIL,EAAM,GAAI,CACVE,GAAa,EACb,IAAII,EAAa,GAAIC,EAAoBP,EAAM,GAAIQ,EAAc,GACjE,GAAuD,QAAlDA,EAAc7D,EAAGlR,IAAI0U,KAAKI,IAe3B,MAAM,IAAIF,YAAY,gDAbtB,IADAC,EAAWF,KAAKI,EAAY,IACwD,MAA5ED,EAAoBA,EAAkBpB,UAAUqB,EAAY,GAAG1T,UACnE,GAA8D,QAAzD0T,EAAc7D,EAAGY,WAAW4C,KAAKI,IAClCD,EAAWF,KAAKI,EAAY,QAE3B,IAAgE,QAA3DA,EAAc7D,EAAGa,aAAa2C,KAAKI,IAIzC,MAAM,IAAIF,YAAY,gDAHtBC,EAAWF,KAAKI,EAAY,IAUxCR,EAAM,GAAKM,OAGXJ,GAAa,EAEjB,GAAkB,IAAdA,EACA,MAAM,IAAIzT,MAAM,6EAGpBgR,EAAW2C,KACP,CACI9C,YAAa0C,EAAM,GACnB3B,SAAa2B,EAAM,GACnB5B,KAAa4B,EAAM,GACnBvR,KAAauR,EAAM,GACnBP,SAAaO,EAAM,GACnBJ,MAAaI,EAAM,GACnBpB,MAAaoB,EAAM,GACnBnB,UAAamB,EAAM,GACnB9Q,KAAa8Q,EAAM,KAO/BC,EAAOA,EAAKd,UAAUa,EAAM,GAAGlT,QAEnC,OAAOiT,EAAcD,GAAOrC,EApLNgD,CAAchV,GAAM6C,WAG9C,SAASoS,EAASZ,EAAKpC,GACnB,OAAO7Q,EAAQM,MAAM,KAAM,CAAC2S,GAAKa,OAAOjD,GAAQ,KAgHpD,IAAIqC,EAAgBnV,OAAOY,OAAO,MAwE9BxB,EAAiB,QAAI6C,EACrB7C,EAAkB,SAAI0W,EAEJ,oBAAXE,SACPA,OAAgB,QAAI/T,EACpB+T,OAAiB,SAAIF,OAQhB/T,KALD+P,EAAA,WACI,MAAO,CACH7P,QAAWA,EACX6T,SAAYA,IAEnBrW,KAAAL,EAAAF,EAAAE,EAAAC,QAAAD,QAAA0S,IAhOZ,I,6BCFD5S,EAAAkB,EAAAyI,GAAA,SAAAoN,GAAA/W,EAAAU,EAAAiJ,EAAA,qCAAAE,IAAA,IAAAmN,EAAAhX,EAAA,GAGA+W,EAAOE,QAAUF,EAAOE,SAAW,GACnCA,QAAQpN,iBAAmBD,IAEpB,IAAMC,EAAmBD,K,+BCNhC,IAAIsN,EAGJA,EAAI,WACH,OAAOpR,KADJ,GAIJ,IAECoR,EAAIA,GAAK,IAAI1C,SAAS,cAAb,GACR,MAAO2C,GAEc,iBAAXL,SAAqBI,EAAIJ,QAOrC3W,EAAOD,QAAUgX","file":"amazon-connect-websocket-manager.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","\nexport const LOGS_DESTINATION = {\n NULL: \"NULL\",\n CLIENT_LOGGER: \"CLIENT_LOGGER\",\n DEBUG: \"DEBUG\"\n};\n\nexport const MIN_WEBSOCKET_LIFETIME_MS = 300000;\nexport const HEARTBEAT_INTERVAL_MS = 10000;\nexport const WEBSOCKET_URL_VALID_TIME_MS = 85000;\nexport const TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS = 500;\nexport const MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS = 5;\nexport const MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS = 1000;\nexport const MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE = 3;\nexport const NETWORK_CONN_CHECK_INTERVAL_MS = 250;\nexport const WEBSOCKET_REINIT_JITTER = 0.3;\nexport const WEBSOCKET_RETRY_RATE_MS = 2000;\nexport const MAX_WEBSOCKET_RETRY_RATE_MS = 30000;\n\nexport const NETWORK_FAILURE = 'NetworkingError';\n\nexport const ROUTE_KEY = {\n SUBSCRIBE: \"aws/subscribe\",\n UNSUBSCRIBE: \"aws/unsubscribe\",\n HEARTBEAT: \"aws/heartbeat\"\n};\n\nexport const CONN_STATE = {\n CONNECTED: \"connected\",\n DISCONNECTED: \"disconnected\"\n};\n","import { sprintf } from \"sprintf-js\";\nimport { NETWORK_FAILURE } from './constants';\n\nconst Utils = {};\n\n/**\n * Asserts that a premise is true.\n */\nUtils.assertTrue = function(premise, message) {\n if (!premise) {\n throw new Error(message);\n }\n};\n\n/**\n * Asserts that a value is not null or undefined.\n */\nUtils.assertNotNull = function(value, name) {\n Utils.assertTrue(\n value !== null && typeof value !== undefined,\n sprintf(\"%s must be provided\", name || \"A value\")\n );\n return value;\n};\n\nUtils.isNonEmptyString = function(value) {\n return typeof value === \"string\" && value.length > 0;\n};\n\nUtils.assertIsList = function(value, key) {\n if (!Array.isArray(value)) {\n throw new Error(key + \" is not an array\");\n }\n};\n\n/**\n * Determine if the given value is a callable function type.\n * Borrowed from Underscore.js.\n */\nUtils.isFunction = function(obj) {\n return !!(obj && obj.constructor && obj.call && obj.apply);\n};\n\nUtils.isObject = function(value) {\n return !(typeof value !== \"object\" || value === null);\n};\n\nUtils.isString = function(value) {\n return typeof value === \"string\";\n};\n\nUtils.isNumber = function(value) {\n return typeof value === \"number\";\n};\n\nconst wsRegex = new RegExp(\"^(wss://)\\\\w*\");\nUtils.validWSUrl = function (wsUrl) {\n return wsRegex.test(wsUrl);\n};\n\nUtils.getSubscriptionResponse = (routeKey, isSuccess, topicList) => {\n return {\n topic: routeKey,\n content : {\n status: isSuccess ? \"success\" : \"failure\",\n topics: topicList\n }\n };\n};\n\nUtils.assertIsObject = function(value, key) {\n if (!Utils.isObject(value)) {\n throw new Error(key + \" is not an object!\");\n }\n};\n\nUtils.addJitter = function (base, maxJitter = 1) {\n maxJitter = Math.min(maxJitter, 1.0);\n const sign = Math.random() > 0.5 ? 1 : -1;\n return Math.floor(base + sign * base * Math.random() * maxJitter);\n};\n\nUtils.isNetworkOnline = () => navigator.onLine;\n\nUtils.isNetworkFailure = (reason) => {\n if(reason._debug && reason._debug.type) {\n return reason._debug.type === NETWORK_FAILURE;\n }\n return false;\n};\n\nexport default Utils;\n","import Utils from \"./utils\";\nimport { LOGS_DESTINATION } from \"./constants\";\n\n/*eslint-disable no-unused-vars*/\nclass Logger {\n debug(data) {}\n\n info(data) {}\n\n warn(data) {}\n\n error(data) {}\n}\n/*eslint-enable no-unused-vars*/\n\nconst LogLevel = {\n DEBUG: 10,\n INFO: 20,\n WARN: 30,\n ERROR: 40\n};\n\nclass LogManagerImpl {\n constructor() {\n this.updateLoggerConfig();\n this.consoleLoggerWrapper = createConsoleLogger();\n }\n\n writeToClientLogger(level, logStatement) {\n if (!this.hasClientLogger()) {\n return;\n }\n switch (level) {\n case LogLevel.DEBUG:\n return this._clientLogger.debug(logStatement);\n case LogLevel.INFO:\n return this._clientLogger.info(logStatement);\n case LogLevel.WARN:\n return this._clientLogger.warn(logStatement);\n case LogLevel.ERROR:\n return this._clientLogger.error(logStatement);\n }\n }\n\n isLevelEnabled(level) {\n return level >= this._level;\n }\n\n hasClientLogger() {\n return this._clientLogger !== null;\n }\n\n getLogger(options) {\n var prefix = options.prefix || \"\";\n if (this._logsDestination === LOGS_DESTINATION.DEBUG) {\n return this.consoleLoggerWrapper;\n }\n return new LoggerWrapperImpl(prefix);\n }\n\n updateLoggerConfig(inputConfig) {\n var config = inputConfig || {};\n this._level = config.level || LogLevel.DEBUG;\n this._clientLogger = config.logger || null;\n this._logsDestination = LOGS_DESTINATION.NULL;\n if (config.debug) {\n this._logsDestination = LOGS_DESTINATION.DEBUG;\n }\n if (config.logger) {\n this._logsDestination = LOGS_DESTINATION.CLIENT_LOGGER;\n }\n }\n}\n\nclass LoggerWrapper {\n debug() {}\n\n info() {}\n\n warn() {}\n\n error() {}\n}\n\nclass LoggerWrapperImpl extends LoggerWrapper {\n constructor(prefix) {\n super();\n this.prefix = prefix || \"\";\n }\n\n debug(...args) {\n return this._log(LogLevel.DEBUG, args);\n }\n\n info(...args) {\n return this._log(LogLevel.INFO, args);\n }\n\n warn(...args) {\n return this._log(LogLevel.WARN, args);\n }\n\n error(...args) {\n return this._log(LogLevel.ERROR, args);\n }\n\n _shouldLog(level) {\n return LogManager.hasClientLogger() && LogManager.isLevelEnabled(level);\n }\n\n _writeToClientLogger(level, logStatement) {\n return LogManager.writeToClientLogger(level, logStatement);\n }\n\n _log(level, args) {\n if (this._shouldLog(level)) {\n var logStatement = this._convertToSingleStatement(args);\n return this._writeToClientLogger(level, logStatement);\n }\n }\n\n _convertToSingleStatement(args) {\n var logStatement = \"\";\n if (this.prefix) {\n logStatement += this.prefix + \" \";\n }\n for (var index = 0; index < args.length; index++) {\n var arg = args[index];\n logStatement += this._convertToString(arg) + \" \";\n }\n return logStatement;\n }\n\n _convertToString(arg) {\n try {\n if (!arg) {\n return \"\";\n }\n if (Utils.isString(arg)) {\n return arg;\n }\n if (Utils.isObject(arg) && Utils.isFunction(arg.toString)) {\n var toStringResult = arg.toString();\n if (toStringResult !== \"[object Object]\") {\n return toStringResult;\n }\n }\n return JSON.stringify(arg);\n } catch (error) {\n console.error(\"Error while converting argument to string\", arg, error);\n return \"\";\n }\n }\n}\n\nvar createConsoleLogger = () => {\n var logger = new LoggerWrapper();\n logger.debug = console.debug;\n logger.info = console.info;\n logger.warn = console.warn;\n logger.error = console.error;\n return logger;\n};\n\nconst LogManager = new LogManagerImpl();\n\nexport { LogManager, Logger, LogLevel };\n","import { WEBSOCKET_RETRY_RATE_MS, MAX_WEBSOCKET_RETRY_RATE_MS } from './constants';\n\nclass RetryProvider {\n constructor(executor, defaultRetry = WEBSOCKET_RETRY_RATE_MS) {\n this.numAttempts = 0;\n this.executor = executor;\n this.hasActiveReconnection = false;\n this.defaultRetry = defaultRetry;\n }\n\n retry() {\n // Don't kickoff another reconnection attempt if we have one pending\n if(!this.hasActiveReconnection) {\n this.hasActiveReconnection = true;\n setTimeout(() => {\n this._execute();\n }, this._getDelay());\n }\n }\n\n _execute() {\n this.hasActiveReconnection = false;\n this.executor();\n this.numAttempts++;\n }\n\n connected() {\n this.numAttempts = 0;\n }\n\n _getDelay() {\n const calculatedDelay = Math.pow(2, this.numAttempts) * this.defaultRetry;\n return calculatedDelay <= MAX_WEBSOCKET_RETRY_RATE_MS ? calculatedDelay : MAX_WEBSOCKET_RETRY_RATE_MS;\n }\n}\n\nexport { RetryProvider };","import Utils from \"./utils\";\nimport { LogManager, LogLevel, Logger } from \"./log\";\nimport {\n MIN_WEBSOCKET_LIFETIME_MS,\n WEBSOCKET_URL_VALID_TIME_MS,\n HEARTBEAT_INTERVAL_MS,\n ROUTE_KEY,\n CONN_STATE,\n MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS,\n TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS,\n MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS,\n MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE,\n NETWORK_CONN_CHECK_INTERVAL_MS,\n WEBSOCKET_REINIT_JITTER,\n} from \"./constants\";\nimport { RetryProvider } from './retryProvider';\n\nconst WebSocketManager = function() {\n\n const logger = LogManager.getLogger({});\n\n let online = Utils.isNetworkOnline();\n\n let webSocket = {\n primary: null,\n secondary: null\n };\n\n let reconnectConfig = {\n reconnectWebSocket: true,\n websocketInitFailed: false,\n exponentialBackOffTime: 1000,\n exponentialTimeoutHandle: null,\n lifeTimeTimeoutHandle: null,\n webSocketInitCheckerTimeoutId: null,\n connState: null\n };\n\n let metrics = {\n connectWebSocketRetryCount: 0,\n connectionAttemptStartTime: null,\n noOpenConnectionsTimestamp: null\n };\n\n let heartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let callbacks = {\n initFailure: new Set(),\n getWebSocketTransport: null,\n subscriptionUpdate: new Set(),\n subscriptionFailure: new Set(),\n topic: new Map(),\n allMessage: new Set(),\n connectionGain: new Set(),\n connectionLost: new Set(),\n connectionOpen: new Set(),\n connectionClose: new Set()\n };\n\n let webSocketConfig = {\n connConfig: null,\n promiseHandle: null,\n promiseCompleted: true\n };\n\n let topicSubscription = {\n subscribed: new Set(),\n pending: new Set(),\n subscriptionHistory: new Set()\n };\n\n let topicSubscriptionConfig = {\n responseCheckIntervalId: null,\n requestCompleted: true,\n reSubscribeIntervalId: null,\n consecutiveFailedSubscribeAttempts: 0,\n consecutiveNoResponseRequest: 0\n };\n\n const reconnectionClient = new RetryProvider(() => { getWebSocketConnConfig(); });\n\n const invalidSendMessageRouteKeys = new Set([ROUTE_KEY.SUBSCRIBE, ROUTE_KEY.UNSUBSCRIBE, ROUTE_KEY.HEARTBEAT]);\n\n const networkConnectivityChecker = setInterval(function () {\n if (online !== Utils.isNetworkOnline()) {\n online = Utils.isNetworkOnline();\n if (!online) {\n sendInternalLogToServer(logger.info(\"Network offline\"));\n\n return;\n }\n const ws = getDefaultWebSocket();\n if (online && (!ws || isWebSocketState(ws, WebSocket.CLOSING) || isWebSocketState(ws, WebSocket.CLOSED))) {\n sendInternalLogToServer(logger.info(\"Network online, connecting to WebSocket server\"));\n\n getWebSocketConnConfig();\n }\n }\n }, NETWORK_CONN_CHECK_INTERVAL_MS);\n\n const invokeCallbacks = function(callbacks, response) {\n callbacks.forEach(function (callback) {\n try {\n callback(response);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error executing callback\", error));\n }\n });\n };\n\n const getWebSocketStates = function(ws) {\n if (ws === null) return \"NULL\";\n switch (ws.readyState) {\n case WebSocket.CONNECTING:\n return \"CONNECTING\";\n case WebSocket.OPEN:\n return \"OPEN\";\n case WebSocket.CLOSING:\n return \"CLOSING\";\n case WebSocket.CLOSED:\n return \"CLOSED\";\n default:\n return \"UNDEFINED\";\n }\n };\n\n const printWebSocketState = function (event = \"\") {\n sendInternalLogToServer(logger.debug(\"[\" + event + \"] Primary WebSocket: \" + getWebSocketStates(webSocket.primary)\n + \" | \" + \"Secondary WebSocket: \" + getWebSocketStates(webSocket.secondary)));\n };\n\n const isWebSocketState = function(ws, webSocketStateCode) {\n return ws && ws.readyState === webSocketStateCode;\n };\n\n const isWebSocketOpen = function(ws) {\n return isWebSocketState(ws, WebSocket.OPEN);\n };\n\n const isWebSocketClosed = function(ws) {\n // undefined check is to address the limitation of testing framework\n return ws === null || ws.readyState === undefined || isWebSocketState(ws, WebSocket.CLOSED);\n };\n\n /**\n * This function is meant to handle the scenario when we have two web-sockets open\n * in such a scenario we always select secondary web-socket since all future operations\n * are supposed to be done by this secondary web-socket\n */\n const getDefaultWebSocket = function() {\n if (webSocket.secondary !== null) {\n return webSocket.secondary;\n }\n return webSocket.primary;\n };\n\n const isDefaultWebSocketOpen = function() {\n return isWebSocketOpen(getDefaultWebSocket());\n };\n\n const sendHeartBeat = function() {\n if (heartbeatConfig.pendingResponse) {\n sendInternalLogToServer(logger.warn(\"Heartbeat response not received\"));\n\n clearInterval(heartbeatConfig.intervalHandle);\n heartbeatConfig.pendingResponse = false;\n getWebSocketConnConfig();\n return;\n }\n if (isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.debug(\"Sending heartbeat\"));\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.HEARTBEAT));\n heartbeatConfig.pendingResponse = true;\n } else {\n sendInternalLogToServer(logger.warn(\"Failed to send heartbeat since WebSocket is not open\"));\n\n printWebSocketState(\"sendHeartBeat\");\n getWebSocketConnConfig();\n }\n };\n\n const resetWebSocketState = function() {\n reconnectConfig.exponentialBackOffTime = 1000;\n heartbeatConfig.pendingResponse = false;\n reconnectConfig.reconnectWebSocket = true;\n\n clearTimeout(reconnectConfig.lifeTimeTimeoutHandle);\n clearInterval(heartbeatConfig.intervalHandle);\n clearTimeout(reconnectConfig.exponentialTimeoutHandle);\n clearTimeout(reconnectConfig.webSocketInitCheckerTimeoutId);\n };\n\n const resetSubscriptions = function() {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n };\n\n const resetMetrics = function() {\n metrics.connectWebSocketRetryCount = 0;\n metrics.connectionAttemptStartTime = null;\n metrics.noOpenConnectionsTimestamp = null;\n };\n\n const webSocketOnOpen = function() {\n try {\n sendInternalLogToServer(logger.info(\"WebSocket connection established!\"));\n\n printWebSocketState(\"webSocketOnOpen\");\n if (reconnectConfig.connState === null || reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n invokeCallbacks(callbacks.connectionGain);\n }\n reconnectConfig.connState = CONN_STATE.CONNECTED;\n\n // Report number of retries to open and record ws open time\n const now = Date.now();\n invokeCallbacks(callbacks.connectionOpen, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n noOpenConnectionsTimestamp: metrics.noOpenConnectionsTimestamp,\n connectionEstablishedTime: now,\n timeToConnect: now - metrics.connectionAttemptStartTime,\n timeWithoutConnection:\n metrics.noOpenConnectionsTimestamp ? now - metrics.noOpenConnectionsTimestamp : null\n });\n\n resetMetrics();\n resetWebSocketState();\n getDefaultWebSocket().openTimestamp = Date.now(); // record open time\n\n // early closure of primary web socket\n if (topicSubscription.subscribed.size === 0 && isWebSocketOpen(webSocket.secondary)) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n if (topicSubscription.subscribed.size > 0 || topicSubscription.pending.size > 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Subscribing secondary websocket to topics of primary websocket\"));\n }\n topicSubscription.subscribed.forEach(topic => {\n topicSubscription.subscriptionHistory.add(topic);\n topicSubscription.pending.add(topic);\n });\n topicSubscription.subscribed.clear();\n subscribePendingTopics();\n }\n\n sendHeartBeat();\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n\n const webSocketLifetimeTimeout = webSocketConfig.connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000;\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket manager reconnection, after delay \" + webSocketLifetimeTimeout + \" ms\"));\n\n reconnectConfig.lifeTimeTimeoutHandle = setTimeout(function() {\n sendInternalLogToServer(logger.debug(\"Starting scheduled WebSocket manager reconnection\"));\n\n getWebSocketConnConfig();\n }, webSocketLifetimeTimeout);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error after establishing WebSocket connection\", error));\n }\n };\n\n const webSocketOnClose = function(event, ws) {\n sendInternalLogToServer(logger.info(\"Socket connection is closed\", JSON.stringify(event)));\n\n printWebSocketState(\"webSocketOnClose before-cleanup\");\n\n invokeCallbacks(callbacks.connectionClose, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n\n if (isWebSocketClosed(webSocket.primary)) {\n webSocket.primary = null;\n }\n if (isWebSocketClosed(webSocket.secondary)) {\n webSocket.secondary = null;\n }\n if (!reconnectConfig.reconnectWebSocket) {\n return;\n }\n if (!isWebSocketOpen(webSocket.primary) && !isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.warn(\"Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection\"));\n\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n /**\n * This check is required in the scenario where WS Server shuts-down and closes all active\n * WS Client connections and WS Server takes about a minute to become active again, in this\n * scenario WS Client's onClose is triggered and then WSM start reconnect logic immediately but all\n * connect request to WS Server would fail and WS Client's onError callback would be triggered\n * followed WS Client's onClose callback and hence \"connectionLost\" callback would be invoked several\n * times and this behavior is redundant\n */\n sendInternalLogToServer(logger.info(\"Ignoring connectionLost callback invocation\"));\n } else {\n invokeCallbacks(callbacks.connectionLost, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n metrics.noOpenConnectionsTimestamp = Date.now();\n }\n reconnectConfig.connState = CONN_STATE.DISCONNECTED;\n getWebSocketConnConfig();\n } else if (isWebSocketClosed(webSocket.primary) && isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"[Primary] WebSocket Cleanly Closed\"));\n\n webSocket.primary = webSocket.secondary;\n webSocket.secondary = null;\n }\n printWebSocketState(\"webSocketOnClose after-cleanup\");\n };\n\n const webSocketOnError = function(event) {\n printWebSocketState(\"webSocketOnError\");\n sendInternalLogToServer(logger.error(\"WebSocketManager Error, error_event: \", JSON.stringify(event)));\n\n getWebSocketConnConfig();\n };\n\n const webSocketOnMessage = function(event) {\n const response = JSON.parse(event.data);\n\n switch (response.topic) {\n\n case ROUTE_KEY.SUBSCRIBE: {\n sendInternalLogToServer(logger.debug(\"Subscription Message received from webSocket server\", event.data));\n\n topicSubscriptionConfig.requestCompleted = true;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n\n if (response.content.status === \"success\") {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n response.content.topics.forEach( topicName => {\n topicSubscription.subscriptionHistory.delete(topicName);\n topicSubscription.pending.delete(topicName);\n topicSubscription.subscribed.add(topicName);\n });\n if (topicSubscription.subscriptionHistory.size === 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Successfully subscribed secondary websocket to all topics of primary websocket\"));\n\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n } else {\n subscribePendingTopics();\n }\n invokeCallbacks(callbacks.subscriptionUpdate, response);\n\n } else {\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n ++topicSubscriptionConfig.consecutiveFailedSubscribeAttempts;\n if (topicSubscriptionConfig.consecutiveFailedSubscribeAttempts === MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS) {\n invokeCallbacks(callbacks.subscriptionFailure, response);\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n return;\n }\n topicSubscriptionConfig.reSubscribeIntervalId = setInterval(function () {\n subscribePendingTopics();\n }, TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.HEARTBEAT: {\n sendInternalLogToServer(logger.debug(\"Heartbeat response received\"));\n\n heartbeatConfig.pendingResponse = false;\n break;\n }\n default: {\n if (response.topic) {\n sendInternalLogToServer(logger.debug(\"Message received for topic \" + response.topic));\n\n if (isWebSocketOpen(webSocket.primary) && isWebSocketOpen(webSocket.secondary)\n && topicSubscription.subscriptionHistory.size === 0 && this === webSocket.primary) {\n /**\n * This block is to handle scenario when both primary and secondary socket have subscribed to\n * a common topic but we are facing difficulty in closing the primary socket, then in this\n * situation messages will be received by both primary and secondary web socket\n */\n sendInternalLogToServer(logger.warn(\"Ignoring Message for Topic \" + response.topic + \", to avoid duplicates\"));\n\n return;\n }\n\n if (callbacks.allMessage.size === 0 && callbacks.topic.size === 0) {\n sendInternalLogToServer(logger.warn('No registered callback listener for Topic', response.topic));\n\n return;\n }\n invokeCallbacks(callbacks.allMessage, response);\n if (callbacks.topic.has(response.topic)) {\n invokeCallbacks(callbacks.topic.get(response.topic), response);\n }\n\n } else if (response.message) {\n sendInternalLogToServer(logger.warn(\"WebSocketManager Message Error\", response));\n } else {\n sendInternalLogToServer(logger.warn(\"Invalid incoming message\", response));\n }\n }\n }\n };\n\n const subscribePendingTopics = function() {\n if (topicSubscriptionConfig.consecutiveNoResponseRequest > MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response\"));\n\n invokeCallbacks(callbacks.subscriptionFailure, Utils.getSubscriptionResponse(ROUTE_KEY.SUBSCRIBE, false, Array.from(topicSubscription.pending)));\n return;\n }\n if (!isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics call since Default WebSocket is not open\"));\n\n return;\n }\n if (Array.from(topicSubscription.pending).length === 0) {\n return;\n }\n\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.SUBSCRIBE, {\n \"topics\": Array.from(topicSubscription.pending)\n }));\n topicSubscriptionConfig.requestCompleted = false;\n\n // This callback ensure that some response was received for subscription request\n topicSubscriptionConfig.responseCheckIntervalId = setInterval(function () {\n if (!topicSubscriptionConfig.requestCompleted) {\n ++topicSubscriptionConfig.consecutiveNoResponseRequest;\n subscribePendingTopics();\n }\n }, MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS);\n };\n\n const closeSpecificWebSocket = function(ws, reason) {\n if (isWebSocketState(ws, WebSocket.CONNECTING) || isWebSocketState(ws, WebSocket.OPEN)) {\n ws.close(1000, reason);\n } else {\n sendInternalLogToServer(logger.warn(\"Ignoring WebSocket Close request, WebSocket State: \" + getWebSocketStates(ws)));\n }\n };\n\n const closeWebSocket = function(reason) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary] WebSocket \" + reason);\n closeSpecificWebSocket(webSocket.secondary, \"[Secondary] WebSocket \" + reason);\n };\n\n const retryWebSocketInitialization = function () {\n metrics.connectWebSocketRetryCount++;\n const waitTime = Utils.addJitter(reconnectConfig.exponentialBackOffTime, WEBSOCKET_REINIT_JITTER);\n if (Date.now() + waitTime <= webSocketConfig.connConfig.urlConnValidTime) {\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket reinitialization, after delay \" + waitTime + \" ms\"));\n\n reconnectConfig.exponentialTimeoutHandle = setTimeout(() => initWebSocket(), waitTime);\n reconnectConfig.exponentialBackOffTime *= 2;\n } else {\n sendInternalLogToServer(logger.warn(\"WebSocket URL cannot be used to establish connection\"));\n\n getWebSocketConnConfig();\n }\n };\n\n const terminateWebSocketManager = function (response) {\n resetWebSocketState();\n resetSubscriptions();\n sendInternalLogToServer(logger.error(\"WebSocket Initialization failed\"));\n\n reconnectConfig.websocketInitFailed = true;\n closeWebSocket(\"Terminating WebSocket Manager\");\n clearInterval(networkConnectivityChecker);\n invokeCallbacks(callbacks.initFailure, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n reason: response\n });\n resetMetrics();\n };\n\n const createWebSocketPayload = function (key, content) {\n return JSON.stringify({\n \"topic\": key,\n \"content\": content\n });\n };\n\n const sendMessage = function(payload) {\n Utils.assertIsObject(payload, \"payload\");\n if (payload.topic === undefined || invalidSendMessageRouteKeys.has(payload.topic)) {\n sendInternalLogToServer(logger.warn(\"Cannot send message, Invalid topic\", payload));\n\n return;\n }\n try {\n payload = JSON.stringify(payload);\n } catch (error) {\n sendInternalLogToServer(logger.warn(\"Error stringify message\", payload));\n\n return;\n }\n if (isDefaultWebSocketOpen()) {\n getDefaultWebSocket().send(payload);\n } else {\n sendInternalLogToServer(logger.warn(\"Cannot send message, web socket connection is not open\"));\n }\n };\n\n const subscribeTopics = function(topics) {\n Utils.assertNotNull(topics, 'topics');\n Utils.assertIsList(topics);\n\n topics.forEach(topic => {\n if (!topicSubscription.subscribed.has(topic)) {\n topicSubscription.pending.add(topic);\n }\n });\n // This ensure all participant-request to subscribe to topic chat are served at least once\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n subscribePendingTopics();\n };\n\n const validWebSocketConnConfig = function (connConfig) {\n if (Utils.isObject(connConfig) && Utils.isObject(connConfig.webSocketTransport)\n && Utils.isNonEmptyString(connConfig.webSocketTransport.url)\n && Utils.validWSUrl(connConfig.webSocketTransport.url) &&\n connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000 >= MIN_WEBSOCKET_LIFETIME_MS) {\n return true;\n }\n sendInternalLogToServer(logger.error(\"Invalid WebSocket Connection Configuration\", connConfig));\n\n return false;\n };\n\n const getWebSocketConnConfig = function () {\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.info(\"Network offline, ignoring this getWebSocketConnConfig request\"));\n\n return;\n }\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.debug(\"WebSocket Init had failed, ignoring this getWebSocketConnConfig request\"));\n\n return;\n }\n if (!webSocketConfig.promiseCompleted) {\n sendInternalLogToServer(logger.debug(\"There is an ongoing getWebSocketConnConfig request, this request will be ignored\"));\n\n return;\n }\n resetWebSocketState();\n sendInternalLogToServer(logger.info(\"Fetching new WebSocket connection configuration\"));\n\n metrics.connectionAttemptStartTime = metrics.connectionAttemptStartTime || Date.now();\n webSocketConfig.promiseCompleted = false;\n webSocketConfig.promiseHandle = callbacks.getWebSocketTransport();\n return webSocketConfig.promiseHandle\n .then(function(response) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.debug(\"Successfully fetched webSocket connection configuration\", response));\n\n if (!validWebSocketConnConfig(response)) {\n terminateWebSocketManager(\"Invalid WebSocket connection configuration: \" + response);\n return { webSocketConnectionFailed: true };\n }\n webSocketConfig.connConfig = response;\n // Ideally this URL validity time should be provided by server\n webSocketConfig.connConfig.urlConnValidTime = Date.now() + WEBSOCKET_URL_VALID_TIME_MS;\n // Mark as a successful connection, and reset number of reconnect attempts\n reconnectionClient.connected();\n return initWebSocket();\n },\n function(reason) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.error(\"Failed to fetch webSocket connection configuration\", reason));\n\n // If our connection fails because of network failure, we want to retry\n if (Utils.isNetworkFailure(reason)) {\n sendInternalLogToServer(logger.info(\"Retrying fetching new WebSocket connection configuration\"));\n reconnectionClient.retry();\n } else {\n // If we're not going to retry, we should terminate WSM\n terminateWebSocketManager(\"Failed to fetch webSocket connection configuration: \" + JSON.stringify(reason));\n }\n return { webSocketConnectionFailed: true };\n });\n };\n\n const initWebSocket = function() {\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.info(\"web-socket initializing had failed, aborting re-init\"));\n\n return { webSocketConnectionFailed: true };\n }\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.warn(\"System is offline aborting web-socket init\"));\n\n return { webSocketConnectionFailed: true };\n }\n sendInternalLogToServer(logger.info(\"Initializing Websocket Manager\"));\n\n printWebSocketState(\"initWebSocket\");\n try {\n if (validWebSocketConnConfig(webSocketConfig.connConfig)) {\n let ws = null;\n if (isWebSocketOpen(webSocket.primary)) {\n sendInternalLogToServer(logger.debug(\"Primary Socket connection is already open\"));\n \n if (!isWebSocketState(webSocket.secondary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a secondary web-socket connection\"));\n\n webSocket.secondary = getNewWebSocket();\n }\n ws = webSocket.secondary;\n } else {\n if (!isWebSocketState(webSocket.primary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a primary web-socket connection\"));\n\n webSocket.primary = getNewWebSocket();\n }\n ws = webSocket.primary;\n }\n\n // WebSocket creation is async task hence we Wait for 1sec before any potential retry\n reconnectConfig.webSocketInitCheckerTimeoutId = setTimeout(function() {\n if (!isWebSocketOpen(ws)) {\n retryWebSocketInitialization();\n }\n }, 1000);\n return { webSocketConnectionFailed: false };\n }\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error Initializing web-socket-manager\", error));\n \n terminateWebSocketManager(\"Failed to initialize new WebSocket: \" + error.message);\n return { webSocketConnectionFailed: true };\n }\n };\n\n const getNewWebSocket = function() {\n let ws = new WebSocket(webSocketConfig.connConfig.webSocketTransport.url);\n ws.addEventListener(\"open\", webSocketOnOpen);\n ws.addEventListener(\"message\", webSocketOnMessage);\n ws.addEventListener(\"error\", webSocketOnError);\n ws.addEventListener(\"close\", event => webSocketOnClose(event, ws));\n return ws;\n };\n\n const onConnectionOpen = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionOpen.add(cb);\n return () => callbacks.connectionOpen.delete(cb);\n };\n\n const onConnectionClose = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionClose.add(cb);\n return () => callbacks.connectionClose.delete(cb);\n };\n\n const onConnectionGain = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionGain.add(cb);\n if (isDefaultWebSocketOpen()) {\n cb();\n }\n return () => callbacks.connectionGain.delete(cb);\n };\n\n const onConnectionLost = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionLost.add(cb);\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n cb();\n }\n return () => callbacks.connectionLost.delete(cb);\n };\n\n const onInitFailure = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.initFailure.add(cb);\n if (reconnectConfig.websocketInitFailed) {\n cb();\n }\n return () => callbacks.initFailure.delete(cb);\n };\n\n const init = function(transportHandle) {\n Utils.assertTrue(Utils.isFunction(transportHandle), 'transportHandle must be a function');\n if (callbacks.getWebSocketTransport !== null) {\n sendInternalLogToServer(logger.warn(\"Web Socket Manager was already initialized\"));\n\n return;\n }\n callbacks.getWebSocketTransport = transportHandle;\n\n return getWebSocketConnConfig();\n };\n\n const onSubscriptionUpdate = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionUpdate.add(cb);\n return () => callbacks.subscriptionUpdate.delete(cb);\n };\n\n const onSubscriptionFailure = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionFailure.add(cb);\n return () => callbacks.subscriptionFailure.delete(cb);\n };\n\n const onMessage = function(topicName, cb) {\n Utils.assertNotNull(topicName, 'topicName');\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n if (callbacks.topic.has(topicName)) {\n callbacks.topic.get(topicName).add(cb);\n } else {\n callbacks.topic.set(topicName, new Set([cb]));\n }\n return () => callbacks.topic.get(topicName).delete(cb);\n };\n\n const onAllMessage = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.allMessage.add(cb);\n return () => callbacks.allMessage.delete(cb);\n };\n\n const sendInternalLogToServer = function (logEntry) {\n if (logEntry && typeof logEntry.sendInternalLogToServer === \"function\")\n logEntry.sendInternalLogToServer();\n\n return logEntry;\n };\n\n this.init = init;\n this.onInitFailure = onInitFailure;\n this.onConnectionOpen = onConnectionOpen;\n this.onConnectionClose = onConnectionClose;\n this.onConnectionGain = onConnectionGain;\n this.onConnectionLost = onConnectionLost;\n this.onSubscriptionUpdate = onSubscriptionUpdate;\n this.onSubscriptionFailure = onSubscriptionFailure;\n this.onMessage = onMessage;\n this.onAllMessage = onAllMessage;\n this.subscribeTopics = subscribeTopics;\n this.sendMessage = sendMessage;\n\n this.closeWebSocket = function() {\n resetWebSocketState();\n resetSubscriptions();\n reconnectConfig.reconnectWebSocket = false;\n clearInterval(networkConnectivityChecker);\n closeWebSocket(\"User request to close WebSocket\");\n };\n\n this.terminateWebSocketManager = terminateWebSocketManager;\n};\n\nconst WebSocketManagerConstructor = () => {\n return new WebSocketManager();\n};\n\nconst setGlobalConfig = config => {\n const loggerConfig = config.loggerConfig;\n LogManager.updateLoggerConfig(loggerConfig);\n};\n\nconst WebSocketManagerObject = {\n create: WebSocketManagerConstructor,\n setGlobalConfig: setGlobalConfig,\n LogLevel: LogLevel,\n Logger: Logger\n};\n\nexport { WebSocketManagerObject };\n","/* global window, exports, define */\n\n!function() {\n 'use strict'\n\n var re = {\n not_string: /[^s]/,\n not_bool: /[^t]/,\n not_type: /[^T]/,\n not_primitive: /[^v]/,\n number: /[diefg]/,\n numeric_arg: /[bcdiefguxX]/,\n json: /[j]/,\n not_json: /[^j]/,\n text: /^[^\\x25]+/,\n modulo: /^\\x25{2}/,\n placeholder: /^\\x25(?:([1-9]\\d*)\\$|\\(([^)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-gijostTuvxX])/,\n key: /^([a-z_][a-z_\\d]*)/i,\n key_access: /^\\.([a-z_][a-z_\\d]*)/i,\n index_access: /^\\[(\\d+)\\]/,\n sign: /^[+-]/\n }\n\n function sprintf(key) {\n // `arguments` is not an array, but should be fine for this call\n return sprintf_format(sprintf_parse(key), arguments)\n }\n\n function vsprintf(fmt, argv) {\n return sprintf.apply(null, [fmt].concat(argv || []))\n }\n\n function sprintf_format(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign\n for (i = 0; i < tree_length; i++) {\n if (typeof parse_tree[i] === 'string') {\n output += parse_tree[i]\n }\n else if (typeof parse_tree[i] === 'object') {\n ph = parse_tree[i] // convenience purposes only\n if (ph.keys) { // keyword argument\n arg = argv[cursor]\n for (k = 0; k < ph.keys.length; k++) {\n if (arg == undefined) {\n throw new Error(sprintf('[sprintf] Cannot access property \"%s\" of undefined value \"%s\"', ph.keys[k], ph.keys[k-1]))\n }\n arg = arg[ph.keys[k]]\n }\n }\n else if (ph.param_no) { // positional argument (explicit)\n arg = argv[ph.param_no]\n }\n else { // positional argument (implicit)\n arg = argv[cursor++]\n }\n\n if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {\n arg = arg()\n }\n\n if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {\n throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))\n }\n\n if (re.number.test(ph.type)) {\n is_positive = arg >= 0\n }\n\n switch (ph.type) {\n case 'b':\n arg = parseInt(arg, 10).toString(2)\n break\n case 'c':\n arg = String.fromCharCode(parseInt(arg, 10))\n break\n case 'd':\n case 'i':\n arg = parseInt(arg, 10)\n break\n case 'j':\n arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)\n break\n case 'e':\n arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()\n break\n case 'f':\n arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)\n break\n case 'g':\n arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)\n break\n case 'o':\n arg = (parseInt(arg, 10) >>> 0).toString(8)\n break\n case 's':\n arg = String(arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 't':\n arg = String(!!arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'T':\n arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'u':\n arg = parseInt(arg, 10) >>> 0\n break\n case 'v':\n arg = arg.valueOf()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'x':\n arg = (parseInt(arg, 10) >>> 0).toString(16)\n break\n case 'X':\n arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()\n break\n }\n if (re.json.test(ph.type)) {\n output += arg\n }\n else {\n if (re.number.test(ph.type) && (!is_positive || ph.sign)) {\n sign = is_positive ? '+' : '-'\n arg = arg.toString().replace(re.sign, '')\n }\n else {\n sign = ''\n }\n pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '\n pad_length = ph.width - (sign + arg).length\n pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''\n output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)\n }\n }\n }\n return output\n }\n\n var sprintf_cache = Object.create(null)\n\n function sprintf_parse(fmt) {\n if (sprintf_cache[fmt]) {\n return sprintf_cache[fmt]\n }\n\n var _fmt = fmt, match, parse_tree = [], arg_names = 0\n while (_fmt) {\n if ((match = re.text.exec(_fmt)) !== null) {\n parse_tree.push(match[0])\n }\n else if ((match = re.modulo.exec(_fmt)) !== null) {\n parse_tree.push('%')\n }\n else if ((match = re.placeholder.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1\n var field_list = [], replacement_field = match[2], field_match = []\n if ((field_match = re.key.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = re.key_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else if ((field_match = re.index_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n }\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n match[2] = field_list\n }\n else {\n arg_names |= 2\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')\n }\n\n parse_tree.push(\n {\n placeholder: match[0],\n param_no: match[1],\n keys: match[2],\n sign: match[3],\n pad_char: match[4],\n align: match[5],\n width: match[6],\n precision: match[7],\n type: match[8]\n }\n )\n }\n else {\n throw new SyntaxError('[sprintf] unexpected placeholder')\n }\n _fmt = _fmt.substring(match[0].length)\n }\n return sprintf_cache[fmt] = parse_tree\n }\n\n /**\n * export to either browser or node.js\n */\n /* eslint-disable quote-props */\n if (typeof exports !== 'undefined') {\n exports['sprintf'] = sprintf\n exports['vsprintf'] = vsprintf\n }\n if (typeof window !== 'undefined') {\n window['sprintf'] = sprintf\n window['vsprintf'] = vsprintf\n\n if (typeof define === 'function' && define['amd']) {\n define(function() {\n return {\n 'sprintf': sprintf,\n 'vsprintf': vsprintf\n }\n })\n }\n }\n /* eslint-enable quote-props */\n}(); // eslint-disable-line\n","/*eslint no-unused-vars: \"off\"*/\nimport { WebSocketManagerObject } from \"./webSocketManager\";\n\nglobal.connect = global.connect || {};\nconnect.WebSocketManager = WebSocketManagerObject;\n\nexport const WebSocketManager = WebSocketManagerObject;\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/constants.js","webpack:///./src/utils.js","webpack:///./src/log.js","webpack:///./src/retryProvider.js","webpack:///./src/webSocketManager.js","webpack:///./node_modules/sprintf-js/src/sprintf.js","webpack:///./src/index.js","webpack:///(webpack)/buildin/global.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","LOGS_DESTINATION","WEBSOCKET_RETRY_RATE_MS","LOG_MESSAGES","ROUTE_KEY","CONN_STATE","Utils","premise","message","Error","assertTrue","undefined","_typeof","sprintf","length","Array","isArray","obj","constructor","apply","wsRegex","RegExp","validWSUrl","wsUrl","test","getSubscriptionResponse","routeKey","isSuccess","topicList","topic","content","status","topics","assertIsObject","isObject","addJitter","base","maxJitter","arguments","Math","min","sign","random","floor","isNetworkOnline","navigator","onLine","isNetworkFailure","reason","_debug","type","Logger","data","DEFAULT_PREFIX","LogLevel","DEBUG","INFO","WARN","ERROR","ADVANCED_LOG","LogManagerImpl","_classCallCheck","this","updateLoggerConfig","consoleLoggerWrapper","createConsoleLogger","level","logStatement","hasClientLogger","_clientLogger","debug","info","warn","error","_advancedLogWriter","_level","options","prefix","_logsDestination","LoggerWrapperImpl","inputConfig","config","advancedLogWriter","customizedLogger","log_typeof","useClientLogger","logger","selectLogger","useDefaultLogger","LoggerWrapper","_this","_possibleConstructorReturn","_getPrototypeOf","_len","args","_key","_log","_len2","_key2","_len3","_key3","_len4","_key4","_len5","_key5","LogManager","isLevelEnabled","writeToClientLogger","_shouldLog","_convertToSingleStatement","_writeToClientLogger","logLevel","date","Date","now","toISOString","_getLogLevelByValue","concat","logMetaData","JSON","stringify","index","arg","_convertToString","isString","isFunction","toString","toStringResult","console","_len6","_key6","window","_len7","_key7","_len8","_key8","_len9","_key9","RetryProvider","executor","defaultRetry","retryProvider_classCallCheck","numAttempts","hasActiveReconnection","setTimeout","_execute","_getDelay","calculatedDelay","pow","__webpack_exports__","WebSocketManagerObject","WebSocketManager","getLogger","online","webSocket","primary","secondary","reconnectConfig","reconnectWebSocket","websocketInitFailed","exponentialBackOffTime","exponentialTimeoutHandle","lifeTimeTimeoutHandle","webSocketInitCheckerTimeoutId","connState","metrics","connectWebSocketRetryCount","connectionAttemptStartTime","noOpenConnectionsTimestamp","heartbeatConfig","pendingResponse","intervalHandle","callbacks","initFailure","Set","getWebSocketTransport","subscriptionUpdate","subscriptionFailure","Map","allMessage","connectionGain","connectionLost","connectionOpen","connectionClose","webSocketConfig","connConfig","promiseHandle","promiseCompleted","topicSubscription","subscribed","pending","subscriptionHistory","topicSubscriptionConfig","responseCheckIntervalId","requestCompleted","reSubscribeIntervalId","consecutiveFailedSubscribeAttempts","consecutiveNoResponseRequest","reconnectionClient","getWebSocketConnConfig","invalidSendMessageRouteKeys","networkConnectivityChecker","setInterval","advancedLog","sendInternalLogToServer","ws","getDefaultWebSocket","isWebSocketState","WebSocket","CLOSING","CLOSED","invokeCallbacks","response","forEach","callback","getWebSocketStates","readyState","CONNECTING","OPEN","printWebSocketState","event","webSocketStateCode","isWebSocketOpen","isWebSocketClosed","isDefaultWebSocketOpen","sendHeartBeat","clearInterval","send","createWebSocketPayload","resetWebSocketState","clearTimeout","resetSubscriptions","resetMetrics","webSocketOnOpen","connected","connectionEstablishedTime","timeToConnect","timeWithoutConnection","openTimestamp","size","closeSpecificWebSocket","add","clear","subscribePendingTopics","webSocketLifetimeTimeout","webSocketTransport","transportLifeTimeInSeconds","webSocketOnError","getIsConnected","retry","webSocketOnMessage","parse","topicName","has","from","close","closeWebSocket","retryWebSocketInitialization","waitTime","urlConnValidTime","initWebSocket","terminateWebSocketManager","validWebSocketConnConfig","isNonEmptyString","url","then","webSocketConnectionFailed","getNewWebSocket","addEventListener","closeTimestamp","connectionDuration","code","webSocketOnClose","logEntry","init","transportHandle","onInitFailure","cb","onConnectionOpen","onConnectionClose","onConnectionGain","onConnectionLost","onSubscriptionUpdate","onSubscriptionFailure","onMessage","assertNotNull","set","onAllMessage","subscribeTopics","assertIsList","sendMessage","payload","setGlobalConfig","loggerConfig","__WEBPACK_AMD_DEFINE_RESULT__","re","not_string","not_bool","not_type","not_primitive","number","numeric_arg","json","not_json","text","modulo","placeholder","key_access","index_access","parse_tree","argv","k","ph","pad","pad_character","pad_length","is_positive","cursor","tree_length","output","keys","param_no","Function","isNaN","TypeError","parseInt","String","fromCharCode","width","precision","parseFloat","toExponential","toFixed","Number","toPrecision","substring","slice","toLowerCase","valueOf","toUpperCase","replace","pad_char","charAt","repeat","align","sprintf_format","fmt","sprintf_cache","match","_fmt","arg_names","exec","push","SyntaxError","field_list","replacement_field","field_match","sprintf_parse","vsprintf","global","_webSocketManager__WEBPACK_IMPORTED_MODULE_0__","connect","g","e"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,KAQvDrB,EAAoBsB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQrB,EAAoBqB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFA1B,EAAoBkB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOrB,EAAoBU,EAAEe,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,GAIRzB,EAAoB6B,EAAI,SAAS1B,GAChC,IAAIS,EAAST,GAAUA,EAAOqB,WAC7B,WAAwB,OAAOrB,EAAgB,SAC/C,WAA8B,OAAOA,GAEtC,OADAH,EAAoBU,EAAEE,EAAQ,IAAKA,GAC5BA,GAIRZ,EAAoBa,EAAI,SAASiB,EAAQC,GAAY,OAAOjB,OAAOkB,UAAUC,eAAe1B,KAAKuB,EAAQC,IAGzG/B,EAAoBkC,EAAI,GAIjBlC,EAAoBA,EAAoBmC,EAAI,G,0CCjFxCC,EACL,OADKA,EAEI,gBAFJA,EAGJ,QAYIC,EAA0B,IAK1BC,EACK,0BADLA,EAEM,kBAFNA,EAGK,iDAHLA,EAIc,gEAJdA,EAKG,kCALHA,EAMS,8BANTA,EAOQ,oBAPRA,EAQO,uDARPA,EASuB,oCATvBA,EAUkB,iCAVlBA,EAWiB,wCAXjBA,EAYiB,sDAZjBA,EAayB,uDAbzBA,EAcsB,2EAdtBA,EAeW,gCAfXA,EAgBe,kDAhBfA,EAiBmB,0DAjBnBA,EAkBmB,qDAlBnBA,EAmBiB,2DAnBjBA,EAoBK,iCApBLA,EAqBa,yCArBbA,EAsBgB,4BAtBhBA,EAuBiB,6BAvBjBA,EAwBgB,4BAxBhBA,EAyBgB,4BAzBhBA,EA0BqB,iCA1BrBA,EA2BM,wBA3BNA,EA4Bc,iCA5BdA,EA6BiB,8BA7BjBA,EA8BgB,2BA9BhBA,EA+BgB,uDAGhBC,EACA,gBADAA,EAEE,kBAFFA,EAGA,gBAGAC,EACA,YADAA,EAEG,e,qOC5DhB,IAAMC,EAAQ,CAKdA,WAAmB,SAASC,EAASC,GACnC,IAAKD,EACH,MAAM,IAAIE,MAAMD,IAOpBF,cAAsB,SAASpB,EAAOV,GAKpC,OAJA8B,EAAMI,WACM,OAAVxB,QAAmCyB,IAAjBC,EAAO1B,GACzB2B,kBAAQ,sBAAuBrC,GAAQ,YAElCU,GAGToB,iBAAyB,SAASpB,GAChC,MAAwB,iBAAVA,GAAsBA,EAAM4B,OAAS,GAGrDR,aAAqB,SAASpB,EAAOM,GACnC,IAAKuB,MAAMC,QAAQ9B,GACjB,MAAM,IAAIuB,MAAMjB,EAAM,qBAQ1Bc,WAAmB,SAASW,GAC1B,SAAUA,GAAOA,EAAIC,aAAeD,EAAI7C,MAAQ6C,EAAIE,QAGtDb,SAAiB,SAASpB,GACxB,QAA0B,WAAjB0B,EAAO1B,IAAgC,OAAVA,IAGxCoB,SAAiB,SAASpB,GACxB,MAAwB,iBAAVA,GAGhBoB,SAAiB,SAASpB,GACxB,MAAwB,iBAAVA,IAGVkC,EAAU,IAAIC,OAAO,iBAC3Bf,EAAMgB,WAAa,SAAUC,GAC3B,OAAOH,EAAQI,KAAKD,IAGtBjB,EAAMmB,wBAA0B,SAACC,EAAUC,EAAWC,GACpD,MAAO,CACLC,MAAOH,EACPI,QAAU,CACRC,OAAQJ,EAAY,UAAY,UAChCK,OAAQJ,KAKdtB,EAAM2B,eAAiB,SAAS/C,EAAOM,GACrC,IAAKc,EAAM4B,SAAShD,GAClB,MAAM,IAAIuB,MAAMjB,EAAM,uBAI1Bc,EAAM6B,UAAY,SAAUC,GAAqB,IAAfC,EAAeC,UAAAxB,OAAA,QAAAH,IAAA2B,UAAA,GAAAA,UAAA,GAAH,EAC5CD,EAAYE,KAAKC,IAAIH,EAAW,GAChC,IAAMI,EAAOF,KAAKG,SAAW,GAAM,GAAK,EACxC,OAAOH,KAAKI,MAAMP,EAAOK,EAAOL,EAAOG,KAAKG,SAAWL,IAGzD/B,EAAMsC,gBAAkB,kBAAMC,UAAUC,QAExCxC,EAAMyC,iBAAmB,SAACC,GACxB,SAAGA,EAAOC,SAAUD,EAAOC,OAAOC,ODlEL,oBCmEpBF,EAAOC,OAAOC,MAKV5C,Q,m8BCvFT6C,G,2EACEC,M,2BAEDA,M,2BAEAA,M,4BAECA,M,kCAEMA,Q,KAIRC,GAAiBlD,EACjBmD,GAAW,CACfC,MAAO,GACPC,KAAM,GACNC,KAAM,GACNC,MAAO,GACPC,aAAc,IAGVC,G,WACJ,SAAAA,IAAcC,EAAAC,KAAAF,GACZE,KAAKC,qBACLD,KAAKE,qBAAuBC,K,uDAGVC,EAAOC,GACzB,GAAKL,KAAKM,kBAGV,OAAQF,GACN,KAAKZ,GAASC,MACZ,OAAOO,KAAKO,cAAcC,MAAMH,IAAiBA,EACnD,KAAKb,GAASE,KACZ,OAAOM,KAAKO,cAAcE,KAAKJ,IAAiBA,EAClD,KAAKb,GAASG,KACZ,OAAOK,KAAKO,cAAcG,KAAKL,IAAiBA,EAClD,KAAKb,GAASI,MACZ,OAAOI,KAAKO,cAAcI,MAAMN,IAAiBA,EACnD,KAAKb,GAASK,aACZ,OAAIG,KAAKY,mBACFZ,KAAKO,cAAcP,KAAKY,oBAAoBP,IAAiBA,EADhC,M,qCAK3BD,GACb,OAAOA,GAASJ,KAAKa,S,wCAIrB,OAA8B,OAAvBb,KAAKO,gB,gCAGJO,GACR,IAAIC,EAASD,EAAQC,QAAUxB,GAC/B,OAAIS,KAAKgB,mBAAqB7E,EACrB6D,KAAKE,qBAEP,IAAIe,GAAkBF,K,yCAGZG,GACjB,IAAIC,EAASD,GAAe,GAC5BlB,KAAKa,OAASM,EAAOf,OAASZ,GAASE,KAEvCM,KAAKY,mBAAqB,OACtBO,EAAOC,oBACTpB,KAAKY,mBAAqBO,EAAOC,mBAGhCD,EAAOE,kBAAuD,WAAnCC,EAAOH,EAAOE,oBAC1CrB,KAAKuB,iBAAkB,GAEzBvB,KAAKO,cAAgBY,EAAOK,QAAUxB,KAAKyB,aAAaN,GAExDnB,KAAKgB,iBAAmB7E,EACpBgF,EAAOX,QACTR,KAAKgB,iBAAmB7E,GAEtBgF,EAAOK,SACTxB,KAAKgB,iBAAmB7E,K,mCAIfgF,GACX,OAAGA,EAAOE,kBAAuD,WAAnCC,EAAOH,EAAOE,kBACnCF,EAAOE,iBAEbF,EAAOO,kBACR1B,KAAKE,qBAAuBC,KACrBH,KAAKE,sBAEP,S,KAILyB,G,+NAYAV,G,YACJ,SAAAA,EAAYF,GAAQ,IAAAa,EAAA,OAAA7B,EAAAC,KAAAiB,IAClBW,EAAAC,EAAA7B,KAAA8B,EAAAb,GAAA3G,KAAA0F,QACKe,OAASA,GAAUxB,GAFNqC,E,4OADUD,I,oCAMf,QAAAI,EAAAvD,UAAAxB,OAANgF,EAAM,IAAA/E,MAAA8E,GAAAE,EAAA,EAAAA,EAAAF,EAAAE,IAAND,EAAMC,GAAAzD,UAAAyD,GACb,OAAOjC,KAAKkC,KAAK1C,GAASC,MAAOuC,K,6BAGrB,QAAAG,EAAA3D,UAAAxB,OAANgF,EAAM,IAAA/E,MAAAkF,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANJ,EAAMI,GAAA5D,UAAA4D,GACZ,OAAOpC,KAAKkC,KAAK1C,GAASE,KAAMsC,K,6BAGpB,QAAAK,EAAA7D,UAAAxB,OAANgF,EAAM,IAAA/E,MAAAoF,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANN,EAAMM,GAAA9D,UAAA8D,GACZ,OAAOtC,KAAKkC,KAAK1C,GAASG,KAAMqC,K,8BAGnB,QAAAO,EAAA/D,UAAAxB,OAANgF,EAAM,IAAA/E,MAAAsF,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANR,EAAMQ,GAAAhE,UAAAgE,GACb,OAAOxC,KAAKkC,KAAK1C,GAASI,MAAOoC,K,oCAGd,QAAAS,EAAAjE,UAAAxB,OAANgF,EAAM,IAAA/E,MAAAwF,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAANV,EAAMU,GAAAlE,UAAAkE,GACnB,OAAO1C,KAAKkC,KAAK1C,GAASK,aAAcmC,K,iCAG/B5B,GACT,OAAOuC,GAAWrC,mBAAqBqC,GAAWC,eAAexC,K,2CAG9CA,EAAOC,GAC1B,OAAOsC,GAAWE,oBAAoBzC,EAAOC,K,2BAG1CD,EAAO4B,GACV,GAAIhC,KAAK8C,WAAW1C,GAAQ,CAC1B,IAAIC,EAAesC,GAAWpB,gBAAkBS,EAAOhC,KAAK+C,0BAA0Bf,EAAM5B,GAC5F,OAAOJ,KAAKgD,qBAAqB5C,EAAOC,M,gDAIlB2B,EAAMiB,GAC9B,IAAIC,EAAO,IAAIC,KAAKA,KAAKC,OAAOC,cAC5BjD,EAAQJ,KAAKsD,oBAAoBL,GACjC5C,EAAe,IAAHkD,OAAOL,EAAP,MAAAK,OAAgBnD,EAAhB,KACZJ,KAAKe,SACPV,GAAgBL,KAAKe,OAAS,KAE5Bf,KAAKc,UACPd,KAAKc,QAAQC,OAASV,GAAgB,IAAML,KAAKc,QAAQC,OAAS,IAAMV,GAAgB,GACxFL,KAAKc,QAAQ0C,YAAcnD,GAAgB,eAAiBoD,KAAKC,UAAU1D,KAAKc,QAAQ0C,aAAenD,GAAgB,IAEzH,IAAK,IAAIsD,EAAQ,EAAGA,EAAQ3B,EAAKhF,OAAQ2G,IAAS,CAChD,IAAIC,EAAM5B,EAAK2B,GACftD,GAAgBL,KAAK6D,iBAAiBD,GAAO,IAE/C,OAAOvD,I,0CAGWjF,GAClB,OAAOA,GACL,KAAK,GAAI,MAAO,QAChB,KAAK,GAAI,MAAO,OAChB,KAAK,GAAI,MAAO,OAChB,KAAK,GAAI,MAAO,QAChB,KAAK,GAAI,MAAO,kB,uCAIHwI,GACf,IACE,IAAKA,EACH,MAAO,GAET,GAAIpH,EAAMsH,SAASF,GACjB,OAAOA,EAET,GAAIpH,EAAM4B,SAASwF,IAAQpH,EAAMuH,WAAWH,EAAII,UAAW,CACzD,IAAIC,EAAiBL,EAAII,WACzB,GAAuB,oBAAnBC,EACF,OAAOA,EAGX,OAAOR,KAAKC,UAAUE,GACtB,MAAOjD,GAEP,OADAuD,QAAQvD,MAAM,4CAA6CiD,EAAKjD,GACzD,Q,KAKTR,GAAsB,WACxB,IAAIqB,EAAS,IAAIG,GAKjB,OAJAH,EAAOhB,MAAQ,mBAAA2D,EAAA3F,UAAAxB,OAAIgF,EAAJ,IAAA/E,MAAAkH,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAAIpC,EAAJoC,GAAA5F,UAAA4F,GAAA,OAAaF,QAAQ1D,MAAMnD,MAAMgH,OAAOH,QAAS,GAAGX,OAAOvB,KAC1ER,EAAOf,KAAO,mBAAA6D,EAAA9F,UAAAxB,OAAIgF,EAAJ,IAAA/E,MAAAqH,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAAIvC,EAAJuC,GAAA/F,UAAA+F,GAAA,OAAaL,QAAQzD,KAAKpD,MAAMgH,OAAOH,QAAS,GAAGX,OAAOvB,KACxER,EAAOd,KAAO,mBAAA8D,EAAAhG,UAAAxB,OAAIgF,EAAJ,IAAA/E,MAAAuH,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAAIzC,EAAJyC,GAAAjG,UAAAiG,GAAA,OAAaP,QAAQxD,KAAKrD,MAAMgH,OAAOH,QAAS,GAAGX,OAAOvB,KACxER,EAAOb,MAAQ,mBAAA+D,EAAAlG,UAAAxB,OAAIgF,EAAJ,IAAA/E,MAAAyH,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAAI3C,EAAJ2C,GAAAnG,UAAAmG,GAAA,OAAaT,QAAQvD,MAAMtD,MAAMgH,OAAOH,QAAS,GAAGX,OAAOvB,KACnER,GAGHmB,GAAa,IAAI7C,G,2KCpNjB8E,G,WACJ,SAAAA,EAAYC,GAAkD,IAAxCC,EAAwCtG,UAAAxB,OAAA,QAAAH,IAAA2B,UAAA,GAAAA,UAAA,GAAzBpC,G,4FAAyB2I,CAAA/E,KAAA4E,GAC5D5E,KAAKgF,YAAc,EACnBhF,KAAK6E,SAAWA,EAChB7E,KAAKiF,uBAAwB,EAC7BjF,KAAK8E,aAAeA,E,uDAGd,IAAAlD,EAAA5B,KAEDA,KAAKiF,wBACRjF,KAAKiF,uBAAwB,EAC7BC,WAAW,WACTtD,EAAKuD,YACJnF,KAAKoF,gB,iCAKVpF,KAAKiF,uBAAwB,EAC7BjF,KAAK6E,WACL7E,KAAKgF,gB,kCAILhF,KAAKgF,YAAc,I,kCAInB,IAAMK,EAAkB5G,KAAK6G,IAAI,EAAGtF,KAAKgF,aAAehF,KAAK8E,aAC7D,OAAOO,GHfgC,IGeiBA,EHfjB,M,uCGmBvC,OAAQrF,KAAKgF,iB,kCCpCjBjL,EAAAU,EAAA8K,EAAA,sBAAAC,KAkBA,IAAMC,GAAmB,WACrB,IAAMjE,EAASmB,GAAW+C,UAAU,CAAE3E,OAAQ1E,IAE1CsJ,EAASnJ,EAAMsC,kBAEf8G,EAAY,CACZC,QAAS,KACTC,UAAW,MAGXC,EAAkB,CAClBC,oBAAoB,EACpBC,qBAAqB,EACrBC,uBAAwB,IACxBC,yBAA0B,KAC1BC,sBAAuB,KACvBC,8BAA+B,KAC/BC,UAAW,MAGXC,EAAU,CACVC,2BAA4B,EAC5BC,2BAA4B,KAC5BC,2BAA4B,MAG5BC,EAAkB,CAClBC,iBAAiB,EACjBC,eAAgB,MAGhBC,EAAY,CACZC,YAAa,IAAIC,IACjBC,sBAAuB,KACvBC,mBAAoB,IAAIF,IACxBG,oBAAqB,IAAIH,IACzBjJ,MAAO,IAAIqJ,IACXC,WAAY,IAAIL,IAChBM,eAAgB,IAAIN,IACpBO,eAAgB,IAAIP,IACpBQ,eAAgB,IAAIR,IACpBS,gBAAiB,IAAIT,KAGrBU,EAAkB,CAClBC,WAAY,KACZC,cAAe,KACfC,kBAAkB,GAGlBC,EAAoB,CACpBC,WAAY,IAAIf,IAChBgB,QAAS,IAAIhB,IACbiB,oBAAqB,IAAIjB,KAGzBkB,EAA0B,CAC1BC,wBAAyB,KACzBC,kBAAkB,EAClBC,sBAAuB,KACvBC,mCAAoC,EACpCC,6BAA8B,GAG5BC,EAAqB,IAAI5D,GAAc,WAAQ6D,OAE/CC,EAA8B,IAAI1B,IAAI,CAAC1K,EAAqBA,EAAuBA,IAEnFqM,EAA6BC,YAAY,WAC7C,GAAIjD,IAAWnJ,EAAMsC,kBAAmB,CAElC,KADA6G,EAASnJ,EAAMsC,mBAKX,OAHA0C,EAAOqH,YAAYxM,QACnByM,GAAwBtH,EAAOf,KAAKpE,IAIxC,IAAM0M,EAAKC,KACPrD,KAAYoD,GAAME,EAAiBF,EAAIG,UAAUC,UAAYF,EAAiBF,EAAIG,UAAUE,WAC5F5H,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOf,KAAKpE,IAEpCoM,QJtF8B,KI2FpCY,EAAkB,SAASvC,EAAWwC,GACxCxC,EAAUyC,QAAQ,SAAUC,GACxB,IACIA,EAASF,GACX,MAAO3I,GACLmI,GAAwBtH,EAAOb,MAAM,2BAA4BA,QAKvE8I,EAAqB,SAASV,GAChC,GAAW,OAAPA,EAAa,MAAO,OACxB,OAAQA,EAAGW,YACP,KAAKR,UAAUS,WACX,MAAO,aACX,KAAKT,UAAUU,KACX,MAAO,OACX,KAAKV,UAAUC,QACX,MAAO,UACX,KAAKD,UAAUE,OACX,MAAO,SACX,QACI,MAAO,cAIbS,EAAsB,WAAsB,IAAZC,EAAYtL,UAAAxB,OAAA,QAAAH,IAAA2B,UAAA,GAAAA,UAAA,GAAJ,GAC1CsK,GAAwBtH,EAAOhB,MAAM,IAAMsJ,EAAQ,wBAA0BL,EAAmB7D,EAAUC,SACpG,2BAAkC4D,EAAmB7D,EAAUE,cAGnEmD,EAAmB,SAASF,EAAIgB,GAClC,OAAOhB,GAAMA,EAAGW,aAAeK,GAG7BC,GAAkB,SAASjB,GAC7B,OAAOE,EAAiBF,EAAIG,UAAUU,OAGpCK,GAAoB,SAASlB,GAE/B,OAAc,OAAPA,QAAiClM,IAAlBkM,EAAGW,YAA4BT,EAAiBF,EAAIG,UAAUE,SAQlFJ,GAAsB,WACxB,OAA4B,OAAxBpD,EAAUE,UACHF,EAAUE,UAEdF,EAAUC,SAGfqE,GAAyB,WAC3B,OAAOF,GAAgBhB,OAGrBmB,GAAgB,WAClB,GAAIxD,EAAgBC,gBAOhB,OANApF,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOd,KAAKrE,IAEpC+N,cAAczD,EAAgBE,gBAC9BF,EAAgBC,iBAAkB,OAClC6B,KAGAyB,MACApB,GAAwBtH,EAAOhB,MAAMnE,IAErC2M,KAAsBqB,KAAKC,GAAuBhO,IAClDqK,EAAgBC,iBAAkB,IAElCpF,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOd,KAAKrE,IAEpCwN,EAAoB,iBACpBpB,OAIF8B,GAAsB,WACxB/I,EAAOqH,YAAYxM,GACnB0J,EAAgBG,uBAAyB,IACzCS,EAAgBC,iBAAkB,EAClCb,EAAgBC,oBAAqB,EAErCwE,aAAazE,EAAgBK,uBAC7BgE,cAAczD,EAAgBE,gBAC9B2D,aAAazE,EAAgBI,0BAC7BqE,aAAazE,EAAgBM,gCAG3BoE,GAAqB,WACvBvC,EAAwBI,mCAAqC,EAC7DJ,EAAwBK,6BAA+B,EACvD6B,cAAclC,EAAwBC,yBACtCiC,cAAclC,EAAwBG,wBAGpCqC,GAAe,WACjBnE,EAAQC,2BAA6B,EACrCD,EAAQE,2BAA6B,KACrCF,EAAQG,2BAA6B,MAGnCiE,GAAkB,WAEpBnC,EAAmBoC,YAEnB,IACIpJ,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOf,KAAKpE,IAEpCwN,EAAoB,mBACc,OAA9B9D,EAAgBO,WAAsBP,EAAgBO,YAAc/J,GACpE8M,EAAgBvC,EAAUQ,gBAE9BvB,EAAgBO,UAAY/J,EAG5B,IAAM6G,EAAMD,KAAKC,MACjBiG,EAAgBvC,EAAUU,eAAgB,CACtChB,2BAA4BD,EAAQC,2BACpCC,2BAA4BF,EAAQE,2BACpCC,2BAA4BH,EAAQG,2BACpCmE,0BAA2BzH,EAC3B0H,cAAe1H,EAAMmD,EAAQE,2BAC7BsE,sBACIxE,EAAQG,2BAA6BtD,EAAMmD,EAAQG,2BAA6B,OAGxFgE,KACAH,KACAvB,KAAsBgC,cAAgB7H,KAAKC,MAGD,IAAtC0E,EAAkBC,WAAWkD,MAAcjB,GAAgBpE,EAAUE,YACrEoF,GAAuBtF,EAAUC,QAAS,0CAE1CiC,EAAkBC,WAAWkD,KAAO,GAAKnD,EAAkBE,QAAQiD,KAAO,KACtEjB,GAAgBpE,EAAUE,YAC1BgD,GAAwBtH,EAAOf,KAAK,mEAExCqH,EAAkBC,WAAWwB,QAAQ,SAAAxL,GACjC+J,EAAkBG,oBAAoBkD,IAAIpN,GAC1C+J,EAAkBE,QAAQmD,IAAIpN,KAElC+J,EAAkBC,WAAWqD,QAC7BC,MAGJlB,KACAxD,EAAgBE,eAAiB+B,YAAYuB,GJ7PpB,KI+PzB,IAAMmB,EAAsG,IAA3E5D,EAAgBC,WAAW4D,mBAAmBC,2BAC/E1C,GAAwBtH,EAAOhB,MAAM,0DAA4D8K,EAA2B,QAE5HvF,EAAgBK,sBAAwBlB,WAAW,WAC/C4D,GAAwBtH,EAAOhB,MAAM,sDAErCiI,MACD6C,GACL,MAAO3K,GACLmI,GAAwBtH,EAAOb,MAAM,gDAAiDA,MA6DxF8K,GAAmB,SAAS3B,GAC9BD,EAAoB,oBACpBrI,EAAOqH,YAAYxM,EAAyCoH,KAAKC,UAAUoG,IAC3EhB,GAAwBtH,EAAOb,MAAMtE,EAAyCoH,KAAKC,UAAUoG,KACzEtB,EAAmBkD,iBAGnCjD,KAEAD,EAAmBmD,SAIrBC,GAAqB,SAAS9B,GAChC,IAAMR,EAAW7F,KAAKoI,MAAM/B,EAAMxK,MAElC,OAAQgK,EAASvL,OAEb,KAAKzB,EAMD,GALAwM,GAAwBtH,EAAOhB,MAAM,sDAAuDsJ,EAAMxK,OAElG4I,EAAwBE,kBAAmB,EAC3CF,EAAwBK,6BAA+B,EAEvB,YAA5Be,EAAStL,QAAQC,OACjBiK,EAAwBI,mCAAqC,EAC7DgB,EAAStL,QAAQE,OAAOqL,QAAS,SAAAuC,GAC7BhE,EAAkBG,oBAAlB,OAA6C6D,GAC7ChE,EAAkBE,QAAlB,OAAiC8D,GACjChE,EAAkBC,WAAWoD,IAAIW,KAEc,IAA/ChE,EAAkBG,oBAAoBgD,KAClCjB,GAAgBpE,EAAUE,aAC1BgD,GAAwBtH,EAAOf,KAAK,mFAEpCyK,GAAuBtF,EAAUC,QAAS,0CAG9CwF,KAEJhC,EAAgBvC,EAAUI,mBAAoBoC,OAE3C,CAGH,GAFAc,cAAclC,EAAwBG,yBACpCH,EAAwBI,mCJ9WK,II+W3BJ,EAAwBI,mCAGxB,OAFAe,EAAgBvC,EAAUK,oBAAqBmC,QAC/CpB,EAAwBI,mCAAqC,GAGjEJ,EAAwBG,sBAAwBO,YAAY,WACxDyC,MJtX4B,KIyXpC,MAEJ,KAAK/O,EACDwM,GAAwBtH,EAAOhB,MAAMnE,IAErCsK,EAAgBC,iBAAkB,EAClC,MAEJ,QACI,GAAI0C,EAASvL,MAAO,CAIhB,GAHAyD,EAAOqH,YAAYxM,EAAyCiN,EAASvL,OACrE+K,GAAwBtH,EAAOhB,MAAMnE,EAA0CiN,EAASvL,QAEpFiM,GAAgBpE,EAAUC,UAAYmE,GAAgBpE,EAAUE,YACd,IAA/CgC,EAAkBG,oBAAoBgD,MAAcjL,OAAS4F,EAAUC,QAQ1E,YAFAiD,GAAwBtH,EAAOd,KAAK,8BAAgC4I,EAASvL,MAAQ,0BAKzF,GAAkC,IAA9B+I,EAAUO,WAAW4D,MAAuC,IAAzBnE,EAAU/I,MAAMkN,KAGnD,YAFAnC,GAAwBtH,EAAOd,KAAK,4CAA6C4I,EAASvL,QAI9FyD,EAAOqH,YAAYxM,EAAwCiN,EAASvL,OACpEsL,EAAgBvC,EAAUO,WAAYiC,GAClCxC,EAAU/I,MAAMgO,IAAIzC,EAASvL,QAC7BsL,EAAgBvC,EAAU/I,MAAM/C,IAAIsO,EAASvL,OAAQuL,QAGlDA,EAAS5M,SAChB8E,EAAOqH,YAAYxM,EAAsCiN,GACzDR,GAAwBtH,EAAOd,KAAKrE,EAAsCiN,MAE1E9H,EAAOqH,YAAYxM,EAAwCiN,GAC3DR,GAAwBtH,EAAOd,KAAKrE,EAAwCiN,OAMtF+B,GAAyB,SAAzBA,IACF,GAAInD,EAAwBK,6BJtawB,EI0ahD,OAHAO,GAAwBtH,EAAOd,KAAK,2GAEpC2I,EAAgBvC,EAAUK,oBAAqB3K,EAAMmB,wBAAwBrB,GAAqB,EAAOW,MAAM+O,KAAKlE,EAAkBE,WAGrIkC,KAKgD,IAAjDjN,MAAM+O,KAAKlE,EAAkBE,SAAShL,SAI1CoN,cAAclC,EAAwBC,yBAEtCa,KAAsBqB,KAAKC,GAAuBhO,EAAqB,CACnE4B,OAAUjB,MAAM+O,KAAKlE,EAAkBE,YAE3CE,EAAwBE,kBAAmB,EAG3CF,EAAwBC,wBAA0BS,YAAY,WACrDV,EAAwBE,qBACvBF,EAAwBK,6BAC1B8C,MJjc6C,MI8ajDvC,GAAwBtH,EAAOd,KAAK,8EAwBtCwK,GAAyB,SAASnC,EAAI7J,GACpC+J,EAAiBF,EAAIG,UAAUS,aAAeV,EAAiBF,EAAIG,UAAUU,MAC7Eb,EAAGkD,MAAM,IAAM/M,GAEf4J,GAAwBtH,EAAOd,KAAK,sDAAwD+I,EAAmBV,MAIjHmD,GAAiB,SAAShN,GAC5BgM,GAAuBtF,EAAUC,QAAS,uBAAyB3G,GACnEgM,GAAuBtF,EAAUE,UAAW,yBAA2B5G,IAGrEiN,GAA+B,WACjC5F,EAAQC,6BACR,IAAM4F,EAAW5P,EAAM6B,UAAU0H,EAAgBG,uBJldlB,IImd3B/C,KAAKC,MAAQgJ,GAAY1E,EAAgBC,WAAW0E,kBACpD7K,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOhB,MAAMnE,EAA0C+P,EAAW,QAE1FrG,EAAgBI,yBAA2BjB,WAAW,kBAAMoH,MAAiBF,GAC7ErG,EAAgBG,wBAA0B,IAE1C1E,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOd,KAAKrE,IAEpCoM,OAIF8D,GAA4B,SAAUjD,GACxCiB,KACAE,KACAjJ,EAAOqH,YAAYxM,EAA8CiN,GACjER,GAAwBtH,EAAOb,MAAMtE,IAErC0J,EAAgBE,qBAAsB,EACtCiG,GAAe7P,GACf+N,cAAczB,GACdU,EAAgBvC,EAAUC,YAAa,CACnCP,2BAA4BD,EAAQC,2BACpCC,2BAA4BF,EAAQE,2BACpCvH,OAAQoK,IAEZoB,MAGEJ,GAAyB,SAAU5O,EAAKsC,GAC1C,OAAOyF,KAAKC,UAAU,CAClB3F,MAASrC,EACTsC,QAAWA,KAuCbwO,GAA2B,SAAU7E,GACzC,SAAInL,EAAM4B,SAASuJ,IAAenL,EAAM4B,SAASuJ,EAAW4D,qBACnD/O,EAAMiQ,iBAAiB9E,EAAW4D,mBAAmBmB,MACrDlQ,EAAMgB,WAAWmK,EAAW4D,mBAAmBmB,MACS,IAA3D/E,EAAW4D,mBAAmBC,4BJxiBD,OI2iBjC1C,GAAwBtH,EAAOb,MAAM,6CAA8CgH,KAE5E,IAGLc,GAAyB,WAC3B,IAAKjM,EAAMsC,kBAIP,OAHA0C,EAAOqH,YAAYxM,QACnByM,GAAwBtH,EAAOf,KAAKpE,IAIxC,GAAI0J,EAAgBE,oBAChB6C,GAAwBtH,EAAOhB,MAAM,gFADzC,CAIA,GAAKkH,EAAgBG,iBAWrB,OAPA0C,KACA/I,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOf,KAAKpE,IAEpCkK,EAAQE,2BAA6BF,EAAQE,4BAA8BtD,KAAKC,MAChFsE,EAAgBG,kBAAmB,EACnCH,EAAgBE,cAAgBd,EAAUG,wBACnCS,EAAgBE,cAClB+E,KAAK,SAASrD,GAKP,OAJA5B,EAAgBG,kBAAmB,EACnCrG,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOhB,MAAMnE,EAA2CiN,IAE3EkD,GAAyBlD,IAI9B5B,EAAgBC,WAAa2B,EAE7B5B,EAAgBC,WAAW0E,iBAAmBlJ,KAAKC,MJhlB5B,KIilBhBkJ,OANHC,GAA0B,+CAAiDjD,GACpE,CAAEsD,2BAA2B,KAO5C,SAAS1N,GAcL,OAbAwI,EAAgBG,kBAAmB,EACnCrG,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOb,MAAMtE,EAA2C6C,IAG5E1C,EAAMyC,iBAAiBC,IACvBsC,EAAOqH,YAAYxM,EAA0CoH,KAAKC,UAAUxE,IAC5E4J,GAAwBtH,EAAOf,KAAKpE,EAA0CoH,KAAKC,UAAUxE,KAC7FsJ,EAAmBmD,SAGnBY,GAA0B,uDAAyD9I,KAAKC,UAAUxE,IAE/F,CAAE0N,2BAA2B,KAvC5C9D,GAAwBtH,EAAOhB,MAAM,uFA2CvC8L,GAAgB,WAClB,GAAIvG,EAAgBE,oBAGhB,OAFA6C,GAAwBtH,EAAOf,KAAK,yDAE7B,CAAEmM,2BAA2B,GAExC,IAAKpQ,EAAMsC,kBAGP,OAFAgK,GAAwBtH,EAAOd,KAAK,+CAE7B,CAAEkM,2BAA2B,GAExCpL,EAAOqH,YAAYxM,GACnByM,GAAwBtH,EAAOf,KAAKpE,IAEpCwN,EAAoB,iBACpB,IACI,GAAI2C,GAAyB9E,EAAgBC,YAAa,CACtD,IAAIoB,EAAK,KAyBT,OAxBIiB,GAAgBpE,EAAUC,UAC1BiD,GAAwBtH,EAAOhB,MAAM,8CAEhCyI,EAAiBrD,EAAUE,UAAWoD,UAAUS,cACjDb,GAAwBtH,EAAOhB,MAAM,mDACrCgI,EAAmBxD,YAAc,EACjCY,EAAUE,UAAY+G,MAE1B9D,EAAKnD,EAAUE,YAEVmD,EAAiBrD,EAAUC,QAASqD,UAAUS,cAC/Cb,GAAwBtH,EAAOhB,MAAM,iDAErCoF,EAAUC,QAAUgH,MAExB9D,EAAKnD,EAAUC,SAInBE,EAAgBM,8BAAgCnB,WAAW,WAClD8E,GAAgBjB,IACjBoD,MAEL,KACI,CAAES,2BAA2B,IAE1C,MAAOjM,GAIL,OAHAmI,GAAwBtH,EAAOb,MAAM,wCAAyCA,IAE9E4L,GAA0B,uCAAyC5L,EAAMjE,SAClE,CAAEkQ,2BAA2B,KAItCC,GAAkB,WACpB,IAAI9D,EAAK,IAAIG,UAAUxB,EAAgBC,WAAW4D,mBAAmBmB,KAKrE,OAJA3D,EAAG+D,iBAAiB,OAAQnC,IAC5B5B,EAAG+D,iBAAiB,UAAWlB,IAC/B7C,EAAG+D,iBAAiB,QAASrB,IAC7B1C,EAAG+D,iBAAiB,QAAS,SAAAhD,GAAK,OAnZb,SAASA,EAAOf,GACrCvH,EAAOqH,YAAYxM,EAA0CoH,KAAKC,UAAUoG,IAC5EhB,GAAwBtH,EAAOf,KAAKpE,EAA0CoH,KAAKC,UAAUoG,KAE7FD,EAAoB,mCAEpBR,EAAgBvC,EAAUW,gBAAiB,CACvCuD,cAAejC,EAAGiC,cAClB+B,eAAgB5J,KAAKC,MACrB4J,mBAAoB7J,KAAKC,MAAQ2F,EAAGiC,cACpCiC,KAAMnD,EAAMmD,KACZ/N,OAAQ4K,EAAM5K,SAGd+K,GAAkBrE,EAAUC,WAC5BD,EAAUC,QAAU,MAEpBoE,GAAkBrE,EAAUE,aAC5BF,EAAUE,UAAY,MAErBC,EAAgBC,qBAGhBgE,GAAgBpE,EAAUC,UAAamE,GAAgBpE,EAAUE,WAyB3DmE,GAAkBrE,EAAUC,UAAYmE,GAAgBpE,EAAUE,aACzEgD,GAAwBtH,EAAOf,KAAK,uCAEpCmF,EAAUC,QAAUD,EAAUE,UAC9BF,EAAUE,UAAY,OA5BtBgD,GAAwBtH,EAAOd,KAAK,uHAEhCqF,EAAgBO,YAAc/J,EAS9BuM,GAAwBtH,EAAOf,KAAK,iDAEpC4I,EAAgBvC,EAAUS,eAAgB,CACtCyD,cAAejC,EAAGiC,cAClB+B,eAAgB5J,KAAKC,MACrB4J,mBAAoB7J,KAAKC,MAAQ2F,EAAGiC,cACpCiC,KAAMnD,EAAMmD,KACZ/N,OAAQ4K,EAAM5K,SAElBqH,EAAQG,2BAA6BvD,KAAKC,OAE9C2C,EAAgBO,UAAY/J,EAC5BkM,MAOJoB,EAAoB,mCA6VkBqD,CAAiBpD,EAAOf,KACvDA,GAwFLD,GAA0B,SAAUqE,GAItC,OAHIA,GAAwD,mBAArCA,EAASrE,yBAC5BqE,EAASrE,0BAENqE,GAGXnN,KAAKoN,KAhDQ,SAASC,GAElB,GADA7Q,EAAMI,WAAWJ,EAAMuH,WAAWsJ,GAAkB,sCACZ,OAApCvG,EAAUG,sBAMd,OAFAH,EAAUG,sBAAwBoG,EAE3B5E,KALHK,GAAwBtH,EAAOd,KAAK,gDA8C5CV,KAAKsN,cA3DiB,SAASC,GAO3B,OANA/L,EAAOqH,YAAYxM,GACnBG,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUC,YAAYoE,IAAIoC,GACtBxH,EAAgBE,qBAChBsH,IAEG,kBAAMzG,EAAUC,YAAV,OAA6BwG,KAqD9CvN,KAAKwN,iBA9FoB,SAASD,GAI9B,OAHA/L,EAAOqH,YAAYxM,GACnBG,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUU,eAAe2D,IAAIoC,GACtB,kBAAMzG,EAAUU,eAAV,OAAgC+F,KA2FjDvN,KAAKyN,kBAxFqB,SAASF,GAI/B,OAHA/L,EAAOqH,YAAYxM,GACnBG,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUW,gBAAgB0D,IAAIoC,GACvB,kBAAMzG,EAAUW,gBAAV,OAAiC8F,KAqFlDvN,KAAK0N,iBAlFoB,SAASH,GAO9B,OANA/L,EAAOqH,YAAYxM,GACnBG,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUQ,eAAe6D,IAAIoC,GACzBrD,MACAqD,IAEG,kBAAMzG,EAAUQ,eAAV,OAAgCiG,KA4EjDvN,KAAK2N,iBAzEoB,SAASJ,GAO9B,OANA/L,EAAOqH,YAAYxM,GACnBG,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUS,eAAe4D,IAAIoC,GACzBxH,EAAgBO,YAAc/J,GAC9BgR,IAEG,kBAAMzG,EAAUS,eAAV,OAAgCgG,KAmEjDvN,KAAK4N,qBA3CwB,SAASL,GAGlC,OAFA/Q,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUI,mBAAmBiE,IAAIoC,GAC1B,kBAAMzG,EAAUI,mBAAV,OAAoCqG,KAyCrDvN,KAAK6N,sBAtCyB,SAASN,GAInC,OAHA/L,EAAOqH,YAAYxM,GACnBG,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUK,oBAAoBgE,IAAIoC,GAC3B,kBAAMzG,EAAUK,oBAAV,OAAqCoG,KAmCtDvN,KAAK8N,UAhCa,SAAShC,EAAWyB,GAQlC,OAPA/Q,EAAMuR,cAAcjC,EAAW,aAC/BtP,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACnCzG,EAAU/I,MAAMgO,IAAID,GACpBhF,EAAU/I,MAAM/C,IAAI8Q,GAAWX,IAAIoC,GAEnCzG,EAAU/I,MAAMiQ,IAAIlC,EAAW,IAAI9E,IAAI,CAACuG,KAErC,kBAAMzG,EAAU/I,MAAM/C,IAAI8Q,GAApB,OAAsCyB,KAyBvDvN,KAAKiO,aAtBgB,SAAUV,GAG3B,OAFA/Q,EAAMI,WAAWJ,EAAMuH,WAAWwJ,GAAK,yBACvCzG,EAAUO,WAAW8D,IAAIoC,GAClB,kBAAMzG,EAAUO,WAAV,OAA4BkG,KAoB7CvN,KAAKkO,gBApPmB,SAAShQ,GAC7B1B,EAAMuR,cAAc7P,EAAQ,UAC5B1B,EAAM2R,aAAajQ,GAEnBA,EAAOqL,QAAQ,SAAAxL,GACN+J,EAAkBC,WAAWgE,IAAIhO,IAClC+J,EAAkBE,QAAQmD,IAAIpN,KAItCmK,EAAwBK,6BAA+B,EACvD8C,MA0OJrL,KAAKoO,YA1Qe,SAASC,GAEzB,GADA7R,EAAM2B,eAAekQ,EAAS,gBACRxR,IAAlBwR,EAAQtQ,OAAuB2K,EAA4BqD,IAAIsC,EAAQtQ,OACvE+K,GAAwBtH,EAAOd,KAAK,qCAAsC2N,QAD9E,CAKA,IACIA,EAAU5K,KAAKC,UAAU2K,GAC3B,MAAO1N,GAGL,YAFAmI,GAAwBtH,EAAOd,KAAK,0BAA2B2N,IAI/DnE,KACAlB,KAAsBqB,KAAKgE,GAE3BvF,GAAwBtH,EAAOd,KAAK,6DA2P5CV,KAAKkM,eAAiB,WAClB3B,KACAE,KACA1E,EAAgBC,oBAAqB,EACrCoE,cAAczB,GACduD,GAAe,oCAGnBlM,KAAKuM,0BAA4BA,IAY/B/G,GAAyB,CAC3B/J,OAVgC,WAChC,OAAO,IAAIgK,IAUX6I,gBAPoB,SAAAnN,GACpB,IAAMoN,EAAepN,GAAUA,EAAOoN,aACtC5L,GAAW1C,mBAAmBsO,IAM9B/O,SAAUA,GACVH,OAAQA,K,gBC5yBZ,IAAAmP,GAEC,WACG,aAEA,IAAIC,EAAK,CACLC,WAAY,OACZC,SAAU,OACVC,SAAU,OACVC,cAAe,OACfC,OAAQ,UACRC,YAAa,eACbC,KAAM,MACNC,SAAU,OACVC,KAAM,YACNC,OAAQ,WACRC,YAAa,2FACb1T,IAAK,sBACL2T,WAAY,wBACZC,aAAc,aACd3Q,KAAM,SAGV,SAAS5B,EAAQrB,GAEb,OAOJ,SAAwB6T,EAAYC,GAChC,IAAiD5L,EAAkBzJ,EAAGsV,EAAGC,EAAIC,EAAKC,EAAeC,EAAYC,EAAanR,EAAtHoR,EAAS,EAAGC,EAAcT,EAAWvS,OAAaiT,EAAS,GAC/D,IAAK9V,EAAI,EAAGA,EAAI6V,EAAa7V,IACzB,GAA6B,iBAAlBoV,EAAWpV,GAClB8V,GAAUV,EAAWpV,QAEpB,GAA6B,iBAAlBoV,EAAWpV,GAAiB,CAExC,IADAuV,EAAKH,EAAWpV,IACT+V,KAEH,IADAtM,EAAM4L,EAAKO,GACNN,EAAI,EAAGA,EAAIC,EAAGQ,KAAKlT,OAAQyS,IAAK,CACjC,GAAW5S,MAAP+G,EACA,MAAM,IAAIjH,MAAMI,EAAQ,gEAAiE2S,EAAGQ,KAAKT,GAAIC,EAAGQ,KAAKT,EAAE,KAEnH7L,EAAMA,EAAI8L,EAAGQ,KAAKT,SAItB7L,EADK8L,EAAGS,SACFX,EAAKE,EAAGS,UAGRX,EAAKO,KAOf,GAJItB,EAAGG,SAASlR,KAAKgS,EAAGtQ,OAASqP,EAAGI,cAAcnR,KAAKgS,EAAGtQ,OAASwE,aAAewM,WAC9ExM,EAAMA,KAGN6K,EAAGM,YAAYrR,KAAKgS,EAAGtQ,OAAyB,iBAARwE,GAAoByM,MAAMzM,GAClE,MAAM,IAAI0M,UAAUvT,EAAQ,0CAA2C6G,IAO3E,OAJI6K,EAAGK,OAAOpR,KAAKgS,EAAGtQ,QAClB0Q,EAAclM,GAAO,GAGjB8L,EAAGtQ,MACP,IAAK,IACDwE,EAAM2M,SAAS3M,EAAK,IAAII,SAAS,GACjC,MACJ,IAAK,IACDJ,EAAM4M,OAAOC,aAAaF,SAAS3M,EAAK,KACxC,MACJ,IAAK,IACL,IAAK,IACDA,EAAM2M,SAAS3M,EAAK,IACpB,MACJ,IAAK,IACDA,EAAMH,KAAKC,UAAUE,EAAK,KAAM8L,EAAGgB,MAAQH,SAASb,EAAGgB,OAAS,GAChE,MACJ,IAAK,IACD9M,EAAM8L,EAAGiB,UAAYC,WAAWhN,GAAKiN,cAAcnB,EAAGiB,WAAaC,WAAWhN,GAAKiN,gBACnF,MACJ,IAAK,IACDjN,EAAM8L,EAAGiB,UAAYC,WAAWhN,GAAKkN,QAAQpB,EAAGiB,WAAaC,WAAWhN,GACxE,MACJ,IAAK,IACDA,EAAM8L,EAAGiB,UAAYH,OAAOO,OAAOnN,EAAIoN,YAAYtB,EAAGiB,aAAeC,WAAWhN,GAChF,MACJ,IAAK,IACDA,GAAO2M,SAAS3M,EAAK,MAAQ,GAAGI,SAAS,GACzC,MACJ,IAAK,IACDJ,EAAM4M,OAAO5M,GACbA,EAAO8L,EAAGiB,UAAY/M,EAAIqN,UAAU,EAAGvB,EAAGiB,WAAa/M,EACvD,MACJ,IAAK,IACDA,EAAM4M,SAAS5M,GACfA,EAAO8L,EAAGiB,UAAY/M,EAAIqN,UAAU,EAAGvB,EAAGiB,WAAa/M,EACvD,MACJ,IAAK,IACDA,EAAM/I,OAAOkB,UAAUiI,SAAS1J,KAAKsJ,GAAKsN,MAAM,GAAI,GAAGC,cACvDvN,EAAO8L,EAAGiB,UAAY/M,EAAIqN,UAAU,EAAGvB,EAAGiB,WAAa/M,EACvD,MACJ,IAAK,IACDA,EAAM2M,SAAS3M,EAAK,MAAQ,EAC5B,MACJ,IAAK,IACDA,EAAMA,EAAIwN,UACVxN,EAAO8L,EAAGiB,UAAY/M,EAAIqN,UAAU,EAAGvB,EAAGiB,WAAa/M,EACvD,MACJ,IAAK,IACDA,GAAO2M,SAAS3M,EAAK,MAAQ,GAAGI,SAAS,IACzC,MACJ,IAAK,IACDJ,GAAO2M,SAAS3M,EAAK,MAAQ,GAAGI,SAAS,IAAIqN,cAGjD5C,EAAGO,KAAKtR,KAAKgS,EAAGtQ,MAChB6Q,GAAUrM,IAGN6K,EAAGK,OAAOpR,KAAKgS,EAAGtQ,OAAW0Q,IAAeJ,EAAG/Q,KAK/CA,EAAO,IAJPA,EAAOmR,EAAc,IAAM,IAC3BlM,EAAMA,EAAII,WAAWsN,QAAQ7C,EAAG9P,KAAM,KAK1CiR,EAAgBF,EAAG6B,SAA2B,MAAhB7B,EAAG6B,SAAmB,IAAM7B,EAAG6B,SAASC,OAAO,GAAK,IAClF3B,EAAaH,EAAGgB,OAAS/R,EAAOiF,GAAK5G,OACrC2S,EAAMD,EAAGgB,OAASb,EAAa,EAAID,EAAc6B,OAAO5B,GAAoB,GAC5EI,GAAUP,EAAGgC,MAAQ/S,EAAOiF,EAAM+L,EAAyB,MAAlBC,EAAwBjR,EAAOgR,EAAM/L,EAAM+L,EAAMhR,EAAOiF,GAI7G,OAAOqM,EAjHA0B,CAsHX,SAAuBC,GACnB,GAAIC,EAAcD,GACd,OAAOC,EAAcD,GAGzB,IAAgBE,EAAZC,EAAOH,EAAYrC,EAAa,GAAIyC,EAAY,EACpD,KAAOD,GAAM,CACT,GAAqC,QAAhCD,EAAQrD,EAAGS,KAAK+C,KAAKF,IACtBxC,EAAW2C,KAAKJ,EAAM,SAErB,GAAuC,QAAlCA,EAAQrD,EAAGU,OAAO8C,KAAKF,IAC7BxC,EAAW2C,KAAK,SAEf,IAA4C,QAAvCJ,EAAQrD,EAAGW,YAAY6C,KAAKF,IA6ClC,MAAM,IAAII,YAAY,oCA5CtB,GAAIL,EAAM,GAAI,CACVE,GAAa,EACb,IAAII,EAAa,GAAIC,EAAoBP,EAAM,GAAIQ,EAAc,GACjE,GAAuD,QAAlDA,EAAc7D,EAAG/S,IAAIuW,KAAKI,IAe3B,MAAM,IAAIF,YAAY,gDAbtB,IADAC,EAAWF,KAAKI,EAAY,IACwD,MAA5ED,EAAoBA,EAAkBpB,UAAUqB,EAAY,GAAGtV,UACnE,GAA8D,QAAzDsV,EAAc7D,EAAGY,WAAW4C,KAAKI,IAClCD,EAAWF,KAAKI,EAAY,QAE3B,IAAgE,QAA3DA,EAAc7D,EAAGa,aAAa2C,KAAKI,IAIzC,MAAM,IAAIF,YAAY,gDAHtBC,EAAWF,KAAKI,EAAY,IAUxCR,EAAM,GAAKM,OAGXJ,GAAa,EAEjB,GAAkB,IAAdA,EACA,MAAM,IAAIrV,MAAM,6EAGpB4S,EAAW2C,KACP,CACI9C,YAAa0C,EAAM,GACnB3B,SAAa2B,EAAM,GACnB5B,KAAa4B,EAAM,GACnBnT,KAAamT,EAAM,GACnBP,SAAaO,EAAM,GACnBJ,MAAaI,EAAM,GACnBpB,MAAaoB,EAAM,GACnBnB,UAAamB,EAAM,GACnB1S,KAAa0S,EAAM,KAO/BC,EAAOA,EAAKd,UAAUa,EAAM,GAAG9U,QAEnC,OAAO6U,EAAcD,GAAOrC,EApLNgD,CAAc7W,GAAM8C,WAG9C,SAASgU,EAASZ,EAAKpC,GACnB,OAAOzS,EAAQM,MAAM,KAAM,CAACuU,GAAKrO,OAAOiM,GAAQ,KAgHpD,IAAIqC,EAAgBhX,OAAOY,OAAO,MAwE9BxB,EAAiB,QAAI8C,EACrB9C,EAAkB,SAAIuY,EAEJ,oBAAXnO,SACPA,OAAgB,QAAItH,EACpBsH,OAAiB,SAAImO,OAQhB3V,KALD2R,EAAA,WACI,MAAO,CACHzR,QAAWA,EACXyV,SAAYA,IAEnBlY,KAAAL,EAAAF,EAAAE,EAAAC,QAAAD,QAAAuU,IAhOZ,I,6BCFDzU,EAAAkB,EAAAsK,GAAA,SAAAkN,GAAA1Y,EAAAU,EAAA8K,EAAA,qCAAAE,IAAA,IAAAiN,EAAA3Y,EAAA,GAGA0Y,EAAOE,QAAUF,EAAOE,SAAW,GACnCA,QAAQlN,iBAAmBD,IAEpB,IAAMC,EAAmBD,K,+BCNhC,IAAIoN,EAGJA,EAAI,WACH,OAAO5S,KADJ,GAIJ,IAEC4S,EAAIA,GAAK,IAAIxC,SAAS,cAAb,GACR,MAAOyC,GAEc,iBAAXxO,SAAqBuO,EAAIvO,QAOrCnK,EAAOD,QAAU2Y","file":"amazon-connect-websocket-manager.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","\nexport const LOGS_DESTINATION = {\n NULL: \"NULL\",\n CLIENT_LOGGER: \"CLIENT_LOGGER\",\n DEBUG: \"DEBUG\"\n};\n\nexport const MIN_WEBSOCKET_LIFETIME_MS = 300000;\nexport const HEARTBEAT_INTERVAL_MS = 10000;\nexport const WEBSOCKET_URL_VALID_TIME_MS = 85000;\nexport const TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS = 500;\nexport const MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS = 5;\nexport const MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS = 1000;\nexport const MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE = 3;\nexport const NETWORK_CONN_CHECK_INTERVAL_MS = 250;\nexport const WEBSOCKET_REINIT_JITTER = 0.3;\nexport const WEBSOCKET_RETRY_RATE_MS = 2000;\nexport const MAX_WEBSOCKET_RETRY_RATE_MS = 30000;\n\nexport const NETWORK_FAILURE = 'NetworkingError';\n\nexport const LOG_MESSAGES = {\n DEFAULT_PREFIX: \"AMZ_WEB_SOCKET_MANAGER:\",\n NETWORK_OFFLINE: \"Network offline\",\n NETWORK_ONLINE: \"Network online, connecting to WebSocket server\",\n NETWORK_OFFLINE_WARNING: \"Network offline, ignoring this getWebSocketConnConfig request\",\n NO_HEARTBEAT: \"Heartbeat response not received\",\n HEARTBEAT_RECEIVED: \"Heartbeat response received\",\n SENDING_HEARTBEAT: \"Sending heartbeat\",\n FAILED_HEARTBEAT: \"Failed to send heartbeat since WebSocket is not open\",\n WEBSOCKET_CONNECTION_ESTABLISHED: \"WebSocket connection established!\",\n WEBSOCKET_CONNECTION_CLOSED: \"WebSocket connection is closed\",\n WEBSOCKET_CONNECTION_ERROR: \"WebSocketManager Error, error_event: \",\n WEBSOCKET_REINITIALIZATION: \"Scheduling WebSocket reinitialization, after delay \",\n WEBSOCKET_REINITIALIZATION_TIMEOUT: \"WebSocket URL cannot be used to establish connection\",\n WEBSOCKET_INITIALIZATION_FAILED: \"WebSocket Initialization failed - Terminating and cleaning subscriptions\",\n WEBSOCKET_TERMINATED: \"Terminating WebSocket Manager\",\n WEBSOCKET_NEW_CONNECTION: \"Fetching new WebSocket connection configuration\",\n WEBSOCKET_CONNECTION_SUCCESS: \"Successfully fetched webSocket connection configuration\",\n WEBSOCKET_CONNECTION_FAILURE: \"Failed to fetch webSocket connection configuration\",\n WEBSOCKET_CONNECTION_RETRY: \"Retrying fetching new WebSocket connection configuration\",\n WEBSOCKET_INIT: \"Initializing Websocket Manager\",\n WEBSOCKET_INIT_FAILURE: \"Initializing Websocket Manager Failed!\",\n WEBSOCKET_CONNECTION_OPEN: \"Websocket connection open\",\n WEBSOCKET_CONNECTION_CLOSE: \"Websocket connection close\",\n WEBSOCKET_CONNECTION_GAIN: \"Websocket connection gain\",\n WEBSOCKET_CONNECTION_LOST: \"Websocket connection lost\",\n WEBSOCKET_SUBSCRIPTION_FAILURE: \"Websocket subscription failure\",\n WEBSOCKET_RESET: \"Reset Websocket state\",\n WEBSOCKET_MESSAGE_ERROR: \"WebSocketManager Message Error\",\n WEBSOCKET_MESSAGE_RECEIVED: \"Message received for topic \",\n WEBSOCKET_MESSAGE_INVALID: \"Invalid incoming message\",\n WEBSOCKET_MESSAGE_SUCCESS: \"WebsocketManager invoke callbacks for topic success \",\n};\n\nexport const ROUTE_KEY = {\n SUBSCRIBE: \"aws/subscribe\",\n UNSUBSCRIBE: \"aws/unsubscribe\",\n HEARTBEAT: \"aws/heartbeat\"\n};\n\nexport const CONN_STATE = {\n CONNECTED: \"connected\",\n DISCONNECTED: \"disconnected\"\n};\n","import { sprintf } from \"sprintf-js\";\nimport { NETWORK_FAILURE } from './constants';\n\nconst Utils = {};\n\n/**\n * Asserts that a premise is true.\n */\nUtils.assertTrue = function(premise, message) {\n if (!premise) {\n throw new Error(message);\n }\n};\n\n/**\n * Asserts that a value is not null or undefined.\n */\nUtils.assertNotNull = function(value, name) {\n Utils.assertTrue(\n value !== null && typeof value !== undefined,\n sprintf(\"%s must be provided\", name || \"A value\")\n );\n return value;\n};\n\nUtils.isNonEmptyString = function(value) {\n return typeof value === \"string\" && value.length > 0;\n};\n\nUtils.assertIsList = function(value, key) {\n if (!Array.isArray(value)) {\n throw new Error(key + \" is not an array\");\n }\n};\n\n/**\n * Determine if the given value is a callable function type.\n * Borrowed from Underscore.js.\n */\nUtils.isFunction = function(obj) {\n return !!(obj && obj.constructor && obj.call && obj.apply);\n};\n\nUtils.isObject = function(value) {\n return !(typeof value !== \"object\" || value === null);\n};\n\nUtils.isString = function(value) {\n return typeof value === \"string\";\n};\n\nUtils.isNumber = function(value) {\n return typeof value === \"number\";\n};\n\nconst wsRegex = new RegExp(\"^(wss://)\\\\w*\");\nUtils.validWSUrl = function (wsUrl) {\n return wsRegex.test(wsUrl);\n};\n\nUtils.getSubscriptionResponse = (routeKey, isSuccess, topicList) => {\n return {\n topic: routeKey,\n content : {\n status: isSuccess ? \"success\" : \"failure\",\n topics: topicList\n }\n };\n};\n\nUtils.assertIsObject = function(value, key) {\n if (!Utils.isObject(value)) {\n throw new Error(key + \" is not an object!\");\n }\n};\n\nUtils.addJitter = function (base, maxJitter = 1) {\n maxJitter = Math.min(maxJitter, 1.0);\n const sign = Math.random() > 0.5 ? 1 : -1;\n return Math.floor(base + sign * base * Math.random() * maxJitter);\n};\n\nUtils.isNetworkOnline = () => navigator.onLine;\n\nUtils.isNetworkFailure = (reason) => {\n if(reason._debug && reason._debug.type) {\n return reason._debug.type === NETWORK_FAILURE;\n }\n return false;\n};\n\nexport default Utils;\n","import Utils from \"./utils\";\nimport { LOGS_DESTINATION, LOG_MESSAGES } from \"./constants\";\n\n/*eslint-disable no-unused-vars*/\nclass Logger {\n debug(data) {}\n\n info(data) {}\n\n warn(data) {}\n\n error(data) {}\n\n advancedLog(data) {}\n}\n/*eslint-enable no-unused-vars*/\n\nconst DEFAULT_PREFIX = LOG_MESSAGES.DEFAULT_PREFIX;\nconst LogLevel = {\n DEBUG: 10,\n INFO: 20,\n WARN: 30,\n ERROR: 40,\n ADVANCED_LOG: 50,\n};\n\nclass LogManagerImpl {\n constructor() {\n this.updateLoggerConfig();\n this.consoleLoggerWrapper = createConsoleLogger();\n }\n\n writeToClientLogger(level, logStatement) {\n if (!this.hasClientLogger()) {\n return;\n }\n switch (level) {\n case LogLevel.DEBUG:\n return this._clientLogger.debug(logStatement) || logStatement;\n case LogLevel.INFO:\n return this._clientLogger.info(logStatement) || logStatement;\n case LogLevel.WARN:\n return this._clientLogger.warn(logStatement) || logStatement;\n case LogLevel.ERROR:\n return this._clientLogger.error(logStatement) || logStatement;\n case LogLevel.ADVANCED_LOG:\n if(!this._advancedLogWriter) return '';\n return this._clientLogger[this._advancedLogWriter](logStatement) || logStatement;\n }\n }\n\n isLevelEnabled(level) {\n return level >= this._level;\n }\n\n hasClientLogger() {\n return this._clientLogger !== null;\n }\n\n getLogger(options) {\n var prefix = options.prefix || DEFAULT_PREFIX;\n if (this._logsDestination === LOGS_DESTINATION.DEBUG) {\n return this.consoleLoggerWrapper;\n }\n return new LoggerWrapperImpl(prefix);\n }\n\n updateLoggerConfig(inputConfig) {\n var config = inputConfig || {};\n this._level = config.level || LogLevel.INFO;\n //enabled advancedLogWriter\n this._advancedLogWriter = \"warn\";\n if (config.advancedLogWriter) {\n this._advancedLogWriter = config.advancedLogWriter;\n }\n\n if(config.customizedLogger && typeof config.customizedLogger === \"object\") {\n this.useClientLogger = true;\n }\n this._clientLogger = config.logger || this.selectLogger(config);\n\n this._logsDestination = LOGS_DESTINATION.NULL;\n if (config.debug) {\n this._logsDestination = LOGS_DESTINATION.DEBUG;\n }\n if (config.logger) {\n this._logsDestination = LOGS_DESTINATION.CLIENT_LOGGER;\n }\n }\n\n selectLogger(config) {\n if(config.customizedLogger && typeof config.customizedLogger === \"object\") {\n return config.customizedLogger;\n }\n if(config.useDefaultLogger) {\n this.consoleLoggerWrapper = createConsoleLogger();\n return this.consoleLoggerWrapper;\n }\n return null;\n }\n}\n\nclass LoggerWrapper {\n debug() {}\n\n info() {}\n\n warn() {}\n\n error() {}\n\n advancedLog() {}\n}\n\nclass LoggerWrapperImpl extends LoggerWrapper {\n constructor(prefix) {\n super();\n this.prefix = prefix || DEFAULT_PREFIX;\n }\n\n debug(...args) {\n return this._log(LogLevel.DEBUG, args);\n }\n\n info(...args) {\n return this._log(LogLevel.INFO, args);\n }\n\n warn(...args) {\n return this._log(LogLevel.WARN, args);\n }\n\n error(...args) {\n return this._log(LogLevel.ERROR, args);\n }\n\n advancedLog(...args) {\n return this._log(LogLevel.ADVANCED_LOG, args);\n }\n\n _shouldLog(level) {\n return LogManager.hasClientLogger() && LogManager.isLevelEnabled(level);\n }\n\n _writeToClientLogger(level, logStatement) {\n return LogManager.writeToClientLogger(level, logStatement);\n }\n\n _log(level, args) {\n if (this._shouldLog(level)) {\n var logStatement = LogManager.useClientLogger ? args : this._convertToSingleStatement(args, level);\n return this._writeToClientLogger(level, logStatement);\n }\n }\n\n _convertToSingleStatement(args, logLevel) {\n var date = new Date(Date.now()).toISOString();\n var level = this._getLogLevelByValue(logLevel);\n var logStatement = `[${date}][${level}]`;\n if (this.prefix) {\n logStatement += this.prefix + \" \";\n }\n if (this.options) {\n this.options.prefix ? logStatement += \" \" + this.options.prefix + \":\" : logStatement += \"\";\n this.options.logMetaData ? logStatement += \" Meta data: \" + JSON.stringify(this.options.logMetaData) : logStatement += \"\";\n }\n for (var index = 0; index < args.length; index++) {\n var arg = args[index];\n logStatement += this._convertToString(arg) + \" \";\n }\n return logStatement;\n }\n\n _getLogLevelByValue(value) {\n switch(value) {\n case 10: return \"DEBUG\";\n case 20: return \"INFO\";\n case 30: return \"WARN\";\n case 40: return \"ERROR\";\n case 50: return \"ADVANCED_LOG\";\n }\n }\n\n _convertToString(arg) {\n try {\n if (!arg) {\n return \"\";\n }\n if (Utils.isString(arg)) {\n return arg;\n }\n if (Utils.isObject(arg) && Utils.isFunction(arg.toString)) {\n var toStringResult = arg.toString();\n if (toStringResult !== \"[object Object]\") {\n return toStringResult;\n }\n }\n return JSON.stringify(arg);\n } catch (error) {\n console.error(\"Error while converting argument to string\", arg, error);\n return \"\";\n }\n }\n}\n\nvar createConsoleLogger = () => {\n var logger = new LoggerWrapper();\n logger.debug = (...args) => console.debug.apply(window.console, [].concat(args));\n logger.info = (...args) => console.info.apply(window.console, [].concat(args));\n logger.warn = (...args) => console.warn.apply(window.console, [].concat(args));\n logger.error = (...args) => console.error.apply(window.console, [].concat(args));\n return logger;\n};\n\nconst LogManager = new LogManagerImpl();\n\nexport { LogManager, Logger, LogLevel };\n","import { WEBSOCKET_RETRY_RATE_MS, MAX_WEBSOCKET_RETRY_RATE_MS } from './constants';\n\nclass RetryProvider {\n constructor(executor, defaultRetry = WEBSOCKET_RETRY_RATE_MS) {\n this.numAttempts = 0;\n this.executor = executor;\n this.hasActiveReconnection = false;\n this.defaultRetry = defaultRetry;\n }\n\n retry() {\n // Don't kickoff another reconnection attempt if we have one pending\n if (!this.hasActiveReconnection) {\n this.hasActiveReconnection = true;\n setTimeout(() => {\n this._execute();\n }, this._getDelay());\n }\n }\n\n _execute() {\n this.hasActiveReconnection = false;\n this.executor();\n this.numAttempts++;\n }\n\n connected() {\n this.numAttempts = 0;\n }\n\n _getDelay() {\n const calculatedDelay = Math.pow(2, this.numAttempts) * this.defaultRetry;\n return calculatedDelay <= MAX_WEBSOCKET_RETRY_RATE_MS ? calculatedDelay : MAX_WEBSOCKET_RETRY_RATE_MS;\n }\n\n getIsConnected() {\n return !this.numAttempts;\n }\n}\n\nexport { RetryProvider };","import Utils from \"./utils\";\nimport { LogManager, LogLevel, Logger } from \"./log\";\nimport {\n MIN_WEBSOCKET_LIFETIME_MS,\n WEBSOCKET_URL_VALID_TIME_MS,\n HEARTBEAT_INTERVAL_MS,\n ROUTE_KEY,\n CONN_STATE,\n MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS,\n TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS,\n MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS,\n MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE,\n NETWORK_CONN_CHECK_INTERVAL_MS,\n WEBSOCKET_REINIT_JITTER,\n LOG_MESSAGES,\n} from \"./constants\";\nimport { RetryProvider } from './retryProvider';\n\nconst WebSocketManager = function() {\n const logger = LogManager.getLogger({ prefix: LOG_MESSAGES.DEFAULT_PREFIX });\n\n let online = Utils.isNetworkOnline();\n\n let webSocket = {\n primary: null,\n secondary: null\n };\n\n let reconnectConfig = {\n reconnectWebSocket: true,\n websocketInitFailed: false,\n exponentialBackOffTime: 1000,\n exponentialTimeoutHandle: null,\n lifeTimeTimeoutHandle: null,\n webSocketInitCheckerTimeoutId: null,\n connState: null\n };\n\n let metrics = {\n connectWebSocketRetryCount: 0,\n connectionAttemptStartTime: null,\n noOpenConnectionsTimestamp: null\n };\n\n let heartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let callbacks = {\n initFailure: new Set(),\n getWebSocketTransport: null,\n subscriptionUpdate: new Set(),\n subscriptionFailure: new Set(),\n topic: new Map(),\n allMessage: new Set(),\n connectionGain: new Set(),\n connectionLost: new Set(),\n connectionOpen: new Set(),\n connectionClose: new Set()\n };\n\n let webSocketConfig = {\n connConfig: null,\n promiseHandle: null,\n promiseCompleted: true\n };\n\n let topicSubscription = {\n subscribed: new Set(),\n pending: new Set(),\n subscriptionHistory: new Set()\n };\n\n let topicSubscriptionConfig = {\n responseCheckIntervalId: null,\n requestCompleted: true,\n reSubscribeIntervalId: null,\n consecutiveFailedSubscribeAttempts: 0,\n consecutiveNoResponseRequest: 0\n };\n\n const reconnectionClient = new RetryProvider(() => { getWebSocketConnConfig(); });\n\n const invalidSendMessageRouteKeys = new Set([ROUTE_KEY.SUBSCRIBE, ROUTE_KEY.UNSUBSCRIBE, ROUTE_KEY.HEARTBEAT]);\n\n const networkConnectivityChecker = setInterval(function () {\n if (online !== Utils.isNetworkOnline()) {\n online = Utils.isNetworkOnline();\n if (!online) {\n logger.advancedLog(LOG_MESSAGES.NETWORK_OFFLINE);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.NETWORK_OFFLINE));\n\n return;\n }\n const ws = getDefaultWebSocket();\n if (online && (!ws || isWebSocketState(ws, WebSocket.CLOSING) || isWebSocketState(ws, WebSocket.CLOSED))) {\n logger.advancedLog(LOG_MESSAGES.NETWORK_ONLINE);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.NETWORK_ONLINE));\n\n getWebSocketConnConfig();\n }\n }\n }, NETWORK_CONN_CHECK_INTERVAL_MS);\n\n const invokeCallbacks = function(callbacks, response) {\n callbacks.forEach(function (callback) {\n try {\n callback(response);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error executing callback\", error));\n }\n });\n };\n\n const getWebSocketStates = function(ws) {\n if (ws === null) return \"NULL\";\n switch (ws.readyState) {\n case WebSocket.CONNECTING:\n return \"CONNECTING\";\n case WebSocket.OPEN:\n return \"OPEN\";\n case WebSocket.CLOSING:\n return \"CLOSING\";\n case WebSocket.CLOSED:\n return \"CLOSED\";\n default:\n return \"UNDEFINED\";\n }\n };\n\n const printWebSocketState = function (event = \"\") {\n sendInternalLogToServer(logger.debug(\"[\" + event + \"] Primary WebSocket: \" + getWebSocketStates(webSocket.primary)\n + \" | \" + \"Secondary WebSocket: \" + getWebSocketStates(webSocket.secondary)));\n };\n\n const isWebSocketState = function(ws, webSocketStateCode) {\n return ws && ws.readyState === webSocketStateCode;\n };\n\n const isWebSocketOpen = function(ws) {\n return isWebSocketState(ws, WebSocket.OPEN);\n };\n\n const isWebSocketClosed = function(ws) {\n // undefined check is to address the limitation of testing framework\n return ws === null || ws.readyState === undefined || isWebSocketState(ws, WebSocket.CLOSED);\n };\n\n /**\n * This function is meant to handle the scenario when we have two web-sockets open\n * in such a scenario we always select secondary web-socket since all future operations\n * are supposed to be done by this secondary web-socket\n */\n const getDefaultWebSocket = function() {\n if (webSocket.secondary !== null) {\n return webSocket.secondary;\n }\n return webSocket.primary;\n };\n\n const isDefaultWebSocketOpen = function() {\n return isWebSocketOpen(getDefaultWebSocket());\n };\n\n const sendHeartBeat = function() {\n if (heartbeatConfig.pendingResponse) {\n logger.advancedLog(LOG_MESSAGES.NO_HEARTBEAT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.NO_HEARTBEAT));\n\n clearInterval(heartbeatConfig.intervalHandle);\n heartbeatConfig.pendingResponse = false;\n getWebSocketConnConfig();\n return;\n }\n if (isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.SENDING_HEARTBEAT));\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.HEARTBEAT));\n heartbeatConfig.pendingResponse = true;\n } else {\n logger.advancedLog(LOG_MESSAGES.FAILED_HEARTBEAT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.FAILED_HEARTBEAT));\n\n printWebSocketState(\"sendHeartBeat\");\n getWebSocketConnConfig();\n }\n };\n\n const resetWebSocketState = function() {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_RESET);\n reconnectConfig.exponentialBackOffTime = 1000;\n heartbeatConfig.pendingResponse = false;\n reconnectConfig.reconnectWebSocket = true;\n\n clearTimeout(reconnectConfig.lifeTimeTimeoutHandle);\n clearInterval(heartbeatConfig.intervalHandle);\n clearTimeout(reconnectConfig.exponentialTimeoutHandle);\n clearTimeout(reconnectConfig.webSocketInitCheckerTimeoutId);\n };\n\n const resetSubscriptions = function() {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n };\n\n const resetMetrics = function() {\n metrics.connectWebSocketRetryCount = 0;\n metrics.connectionAttemptStartTime = null;\n metrics.noOpenConnectionsTimestamp = null;\n };\n\n const webSocketOnOpen = function() {\n // Mark connection as successful; reset the number of reconnect attempts to 0.\n reconnectionClient.connected();\n\n try {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_ESTABLISHED);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_CONNECTION_ESTABLISHED));\n\n printWebSocketState(\"webSocketOnOpen\");\n if (reconnectConfig.connState === null || reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n invokeCallbacks(callbacks.connectionGain);\n }\n reconnectConfig.connState = CONN_STATE.CONNECTED;\n\n // Report number of retries to open and record ws open time\n const now = Date.now();\n invokeCallbacks(callbacks.connectionOpen, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n noOpenConnectionsTimestamp: metrics.noOpenConnectionsTimestamp,\n connectionEstablishedTime: now,\n timeToConnect: now - metrics.connectionAttemptStartTime,\n timeWithoutConnection:\n metrics.noOpenConnectionsTimestamp ? now - metrics.noOpenConnectionsTimestamp : null\n });\n\n resetMetrics();\n resetWebSocketState();\n getDefaultWebSocket().openTimestamp = Date.now(); // record open time\n\n // early closure of primary web socket\n if (topicSubscription.subscribed.size === 0 && isWebSocketOpen(webSocket.secondary)) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n if (topicSubscription.subscribed.size > 0 || topicSubscription.pending.size > 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Subscribing secondary websocket to topics of primary websocket\"));\n }\n topicSubscription.subscribed.forEach(topic => {\n topicSubscription.subscriptionHistory.add(topic);\n topicSubscription.pending.add(topic);\n });\n topicSubscription.subscribed.clear();\n subscribePendingTopics();\n }\n\n sendHeartBeat();\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n\n const webSocketLifetimeTimeout = webSocketConfig.connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000;\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket manager reconnection, after delay \" + webSocketLifetimeTimeout + \" ms\"));\n\n reconnectConfig.lifeTimeTimeoutHandle = setTimeout(function() {\n sendInternalLogToServer(logger.debug(\"Starting scheduled WebSocket manager reconnection\"));\n\n getWebSocketConnConfig();\n }, webSocketLifetimeTimeout);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error after establishing WebSocket connection\", error));\n }\n };\n\n const webSocketOnClose = function(event, ws) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSED, JSON.stringify(event));\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSED, JSON.stringify(event)));\n\n printWebSocketState(\"webSocketOnClose before-cleanup\");\n\n invokeCallbacks(callbacks.connectionClose, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n\n if (isWebSocketClosed(webSocket.primary)) {\n webSocket.primary = null;\n }\n if (isWebSocketClosed(webSocket.secondary)) {\n webSocket.secondary = null;\n }\n if (!reconnectConfig.reconnectWebSocket) {\n return;\n }\n if (!isWebSocketOpen(webSocket.primary) && !isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.warn(\"Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection\"));\n\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n /**\n * This check is required in the scenario where WS Server shuts-down and closes all active\n * WS Client connections and WS Server takes about a minute to become active again, in this\n * scenario WS Client's onClose is triggered and then WSM start reconnect logic immediately but all\n * connect request to WS Server would fail and WS Client's onError callback would be triggered\n * followed WS Client's onClose callback and hence \"connectionLost\" callback would be invoked several\n * times and this behavior is redundant\n */\n sendInternalLogToServer(logger.info(\"Ignoring connectionLost callback invocation\"));\n } else {\n invokeCallbacks(callbacks.connectionLost, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n metrics.noOpenConnectionsTimestamp = Date.now();\n }\n reconnectConfig.connState = CONN_STATE.DISCONNECTED;\n getWebSocketConnConfig();\n } else if (isWebSocketClosed(webSocket.primary) && isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"[Primary] WebSocket Cleanly Closed\"));\n\n webSocket.primary = webSocket.secondary;\n webSocket.secondary = null;\n }\n printWebSocketState(\"webSocketOnClose after-cleanup\");\n };\n\n const webSocketOnError = function(event) {\n printWebSocketState(\"webSocketOnError\");\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_ERROR, JSON.stringify(event));\n sendInternalLogToServer(logger.error(LOG_MESSAGES.WEBSOCKET_CONNECTION_ERROR, JSON.stringify(event)));\n const isConnected = reconnectionClient.getIsConnected();\n\n if (isConnected) {\n getWebSocketConnConfig();\n } else {\n reconnectionClient.retry();\n }\n };\n\n const webSocketOnMessage = function(event) {\n const response = JSON.parse(event.data);\n\n switch (response.topic) {\n\n case ROUTE_KEY.SUBSCRIBE: {\n sendInternalLogToServer(logger.debug(\"Subscription Message received from webSocket server\", event.data));\n\n topicSubscriptionConfig.requestCompleted = true;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n\n if (response.content.status === \"success\") {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n response.content.topics.forEach( topicName => {\n topicSubscription.subscriptionHistory.delete(topicName);\n topicSubscription.pending.delete(topicName);\n topicSubscription.subscribed.add(topicName);\n });\n if (topicSubscription.subscriptionHistory.size === 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Successfully subscribed secondary websocket to all topics of primary websocket\"));\n\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n } else {\n subscribePendingTopics();\n }\n invokeCallbacks(callbacks.subscriptionUpdate, response);\n\n } else {\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n ++topicSubscriptionConfig.consecutiveFailedSubscribeAttempts;\n if (topicSubscriptionConfig.consecutiveFailedSubscribeAttempts === MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS) {\n invokeCallbacks(callbacks.subscriptionFailure, response);\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n return;\n }\n topicSubscriptionConfig.reSubscribeIntervalId = setInterval(function () {\n subscribePendingTopics();\n }, TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.HEARTBEAT: {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.HEARTBEAT_RECEIVED));\n\n heartbeatConfig.pendingResponse = false;\n break;\n }\n default: {\n if (response.topic) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_RECEIVED, response.topic);\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.WEBSOCKET_MESSAGE_RECEIVED + response.topic));\n\n if (isWebSocketOpen(webSocket.primary) && isWebSocketOpen(webSocket.secondary)\n && topicSubscription.subscriptionHistory.size === 0 && this === webSocket.primary) {\n /**\n * This block is to handle scenario when both primary and secondary socket have subscribed to\n * a common topic but we are facing difficulty in closing the primary socket, then in this\n * situation messages will be received by both primary and secondary web socket\n */\n sendInternalLogToServer(logger.warn(\"Ignoring Message for Topic \" + response.topic + \", to avoid duplicates\"));\n\n return;\n }\n\n if (callbacks.allMessage.size === 0 && callbacks.topic.size === 0) {\n sendInternalLogToServer(logger.warn('No registered callback listener for Topic', response.topic));\n\n return;\n }\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_SUCCESS, response.topic);\n invokeCallbacks(callbacks.allMessage, response);\n if (callbacks.topic.has(response.topic)) {\n invokeCallbacks(callbacks.topic.get(response.topic), response);\n }\n\n } else if (response.message) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_ERROR, response);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.WEBSOCKET_MESSAGE_ERROR, response));\n } else {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_INVALID, response);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.WEBSOCKET_MESSAGE_INVALID, response));\n }\n }\n }\n };\n\n const subscribePendingTopics = function() {\n if (topicSubscriptionConfig.consecutiveNoResponseRequest > MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response\"));\n\n invokeCallbacks(callbacks.subscriptionFailure, Utils.getSubscriptionResponse(ROUTE_KEY.SUBSCRIBE, false, Array.from(topicSubscription.pending)));\n return;\n }\n if (!isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics call since Default WebSocket is not open\"));\n\n return;\n }\n if (Array.from(topicSubscription.pending).length === 0) {\n return;\n }\n\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.SUBSCRIBE, {\n \"topics\": Array.from(topicSubscription.pending)\n }));\n topicSubscriptionConfig.requestCompleted = false;\n\n // This callback ensure that some response was received for subscription request\n topicSubscriptionConfig.responseCheckIntervalId = setInterval(function () {\n if (!topicSubscriptionConfig.requestCompleted) {\n ++topicSubscriptionConfig.consecutiveNoResponseRequest;\n subscribePendingTopics();\n }\n }, MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS);\n };\n\n const closeSpecificWebSocket = function(ws, reason) {\n if (isWebSocketState(ws, WebSocket.CONNECTING) || isWebSocketState(ws, WebSocket.OPEN)) {\n ws.close(1000, reason);\n } else {\n sendInternalLogToServer(logger.warn(\"Ignoring WebSocket Close request, WebSocket State: \" + getWebSocketStates(ws)));\n }\n };\n\n const closeWebSocket = function(reason) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary] WebSocket \" + reason);\n closeSpecificWebSocket(webSocket.secondary, \"[Secondary] WebSocket \" + reason);\n };\n\n const retryWebSocketInitialization = function () {\n metrics.connectWebSocketRetryCount++;\n const waitTime = Utils.addJitter(reconnectConfig.exponentialBackOffTime, WEBSOCKET_REINIT_JITTER);\n if (Date.now() + waitTime <= webSocketConfig.connConfig.urlConnValidTime) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION);\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION + waitTime + \" ms\"));\n\n reconnectConfig.exponentialTimeoutHandle = setTimeout(() => initWebSocket(), waitTime);\n reconnectConfig.exponentialBackOffTime *= 2;\n } else {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION_TIMEOUT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION_TIMEOUT));\n\n getWebSocketConnConfig();\n }\n };\n\n const terminateWebSocketManager = function (response) {\n resetWebSocketState();\n resetSubscriptions();\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INITIALIZATION_FAILED, response);\n sendInternalLogToServer(logger.error(LOG_MESSAGES.WEBSOCKET_INITIALIZATION_FAILED));\n\n reconnectConfig.websocketInitFailed = true;\n closeWebSocket(LOG_MESSAGES.WEBSOCKET_TERMINATED);\n clearInterval(networkConnectivityChecker);\n invokeCallbacks(callbacks.initFailure, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n reason: response\n });\n resetMetrics();\n };\n\n const createWebSocketPayload = function (key, content) {\n return JSON.stringify({\n \"topic\": key,\n \"content\": content\n });\n };\n\n const sendMessage = function(payload) {\n Utils.assertIsObject(payload, \"payload\");\n if (payload.topic === undefined || invalidSendMessageRouteKeys.has(payload.topic)) {\n sendInternalLogToServer(logger.warn(\"Cannot send message, Invalid topic\", payload));\n\n return;\n }\n try {\n payload = JSON.stringify(payload);\n } catch (error) {\n sendInternalLogToServer(logger.warn(\"Error stringify message\", payload));\n\n return;\n }\n if (isDefaultWebSocketOpen()) {\n getDefaultWebSocket().send(payload);\n } else {\n sendInternalLogToServer(logger.warn(\"Cannot send message, web socket connection is not open\"));\n }\n };\n\n const subscribeTopics = function(topics) {\n Utils.assertNotNull(topics, 'topics');\n Utils.assertIsList(topics);\n\n topics.forEach(topic => {\n if (!topicSubscription.subscribed.has(topic)) {\n topicSubscription.pending.add(topic);\n }\n });\n // This ensure all participant-request to subscribe to topic chat are served at least once\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n subscribePendingTopics();\n };\n\n const validWebSocketConnConfig = function (connConfig) {\n if (Utils.isObject(connConfig) && Utils.isObject(connConfig.webSocketTransport)\n && Utils.isNonEmptyString(connConfig.webSocketTransport.url)\n && Utils.validWSUrl(connConfig.webSocketTransport.url) &&\n connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000 >= MIN_WEBSOCKET_LIFETIME_MS) {\n return true;\n }\n sendInternalLogToServer(logger.error(\"Invalid WebSocket Connection Configuration\", connConfig));\n\n return false;\n };\n\n const getWebSocketConnConfig = function () {\n if (!Utils.isNetworkOnline()) {\n logger.advancedLog(LOG_MESSAGES.NETWORK_OFFLINE_WARNING);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.NETWORK_OFFLINE_WARNING));\n\n return;\n }\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.debug(\"WebSocket Init had failed, ignoring this getWebSocketConnConfig request\"));\n return;\n }\n if (!webSocketConfig.promiseCompleted) {\n sendInternalLogToServer(logger.debug(\"There is an ongoing getWebSocketConnConfig request, this request will be ignored\"));\n return;\n }\n resetWebSocketState();\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_NEW_CONNECTION);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_NEW_CONNECTION));\n\n metrics.connectionAttemptStartTime = metrics.connectionAttemptStartTime || Date.now();\n webSocketConfig.promiseCompleted = false;\n webSocketConfig.promiseHandle = callbacks.getWebSocketTransport();\n return webSocketConfig.promiseHandle\n .then(function(response) {\n webSocketConfig.promiseCompleted = true;\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_SUCCESS);\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.WEBSOCKET_CONNECTION_SUCCESS, response));\n\n if (!validWebSocketConnConfig(response)) {\n terminateWebSocketManager(\"Invalid WebSocket connection configuration: \" + response);\n return { webSocketConnectionFailed: true };\n }\n webSocketConfig.connConfig = response;\n // Ideally this URL validity time should be provided by server\n webSocketConfig.connConfig.urlConnValidTime = Date.now() + WEBSOCKET_URL_VALID_TIME_MS;\n return initWebSocket();\n },\n function(reason) {\n webSocketConfig.promiseCompleted = true;\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_FAILURE);\n sendInternalLogToServer(logger.error(LOG_MESSAGES.WEBSOCKET_CONNECTION_FAILURE, reason));\n\n // If our connection fails because of network failure, we want to retry\n if (Utils.isNetworkFailure(reason)) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_RETRY + JSON.stringify(reason));\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_CONNECTION_RETRY + JSON.stringify(reason)));\n reconnectionClient.retry();\n } else {\n // If we're not going to retry, we should terminate WSM\n terminateWebSocketManager(\"Failed to fetch webSocket connection configuration: \" + JSON.stringify(reason));\n }\n return { webSocketConnectionFailed: true };\n });\n };\n\n const initWebSocket = function() {\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.info(\"web-socket initializing had failed, aborting re-init\"));\n\n return { webSocketConnectionFailed: true };\n }\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.warn(\"System is offline aborting web-socket init\"));\n\n return { webSocketConnectionFailed: true };\n }\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INIT);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_INIT));\n\n printWebSocketState(\"initWebSocket\");\n try {\n if (validWebSocketConnConfig(webSocketConfig.connConfig)) {\n let ws = null;\n if (isWebSocketOpen(webSocket.primary)) {\n sendInternalLogToServer(logger.debug(\"Primary Socket connection is already open\"));\n\n if (!isWebSocketState(webSocket.secondary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a secondary web-socket connection\"));\n reconnectionClient.numAttempts = 0;\n webSocket.secondary = getNewWebSocket();\n }\n ws = webSocket.secondary;\n } else {\n if (!isWebSocketState(webSocket.primary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a primary web-socket connection\"));\n\n webSocket.primary = getNewWebSocket();\n }\n ws = webSocket.primary;\n }\n\n // WebSocket creation is async task hence we Wait for 1sec before any potential retry\n reconnectConfig.webSocketInitCheckerTimeoutId = setTimeout(function() {\n if (!isWebSocketOpen(ws)) {\n retryWebSocketInitialization();\n }\n }, 1000);\n return { webSocketConnectionFailed: false };\n }\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error Initializing web-socket-manager\", error));\n\n terminateWebSocketManager(\"Failed to initialize new WebSocket: \" + error.message);\n return { webSocketConnectionFailed: true };\n }\n };\n\n const getNewWebSocket = function() {\n let ws = new WebSocket(webSocketConfig.connConfig.webSocketTransport.url);\n ws.addEventListener(\"open\", webSocketOnOpen);\n ws.addEventListener(\"message\", webSocketOnMessage);\n ws.addEventListener(\"error\", webSocketOnError);\n ws.addEventListener(\"close\", event => webSocketOnClose(event, ws));\n return ws;\n };\n\n const onConnectionOpen = function(cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_OPEN);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionOpen.add(cb);\n return () => callbacks.connectionOpen.delete(cb);\n };\n\n const onConnectionClose = function(cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionClose.add(cb);\n return () => callbacks.connectionClose.delete(cb);\n };\n\n const onConnectionGain = function(cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_GAIN);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionGain.add(cb);\n if (isDefaultWebSocketOpen()) {\n cb();\n }\n return () => callbacks.connectionGain.delete(cb);\n };\n\n const onConnectionLost = function(cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_LOST);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionLost.add(cb);\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n cb();\n }\n return () => callbacks.connectionLost.delete(cb);\n };\n\n const onInitFailure = function(cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INIT_FAILURE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.initFailure.add(cb);\n if (reconnectConfig.websocketInitFailed) {\n cb();\n }\n return () => callbacks.initFailure.delete(cb);\n };\n\n const init = function(transportHandle) {\n Utils.assertTrue(Utils.isFunction(transportHandle), 'transportHandle must be a function');\n if (callbacks.getWebSocketTransport !== null) {\n sendInternalLogToServer(logger.warn(\"Web Socket Manager was already initialized\"));\n return;\n }\n callbacks.getWebSocketTransport = transportHandle;\n\n return getWebSocketConnConfig();\n };\n\n const onSubscriptionUpdate = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionUpdate.add(cb);\n return () => callbacks.subscriptionUpdate.delete(cb);\n };\n\n const onSubscriptionFailure = function(cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_SUBSCRIPTION_FAILURE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionFailure.add(cb);\n return () => callbacks.subscriptionFailure.delete(cb);\n };\n\n const onMessage = function(topicName, cb) {\n Utils.assertNotNull(topicName, 'topicName');\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n if (callbacks.topic.has(topicName)) {\n callbacks.topic.get(topicName).add(cb);\n } else {\n callbacks.topic.set(topicName, new Set([cb]));\n }\n return () => callbacks.topic.get(topicName).delete(cb);\n };\n\n const onAllMessage = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.allMessage.add(cb);\n return () => callbacks.allMessage.delete(cb);\n };\n\n const sendInternalLogToServer = function (logEntry) {\n if (logEntry && typeof logEntry.sendInternalLogToServer === \"function\")\n logEntry.sendInternalLogToServer();\n\n return logEntry;\n };\n\n this.init = init;\n this.onInitFailure = onInitFailure;\n this.onConnectionOpen = onConnectionOpen;\n this.onConnectionClose = onConnectionClose;\n this.onConnectionGain = onConnectionGain;\n this.onConnectionLost = onConnectionLost;\n this.onSubscriptionUpdate = onSubscriptionUpdate;\n this.onSubscriptionFailure = onSubscriptionFailure;\n this.onMessage = onMessage;\n this.onAllMessage = onAllMessage;\n this.subscribeTopics = subscribeTopics;\n this.sendMessage = sendMessage;\n\n this.closeWebSocket = function() {\n resetWebSocketState();\n resetSubscriptions();\n reconnectConfig.reconnectWebSocket = false;\n clearInterval(networkConnectivityChecker);\n closeWebSocket(\"User request to close WebSocket\");\n };\n\n this.terminateWebSocketManager = terminateWebSocketManager;\n};\n\nconst WebSocketManagerConstructor = () => {\n return new WebSocketManager();\n};\n\nconst setGlobalConfig = config => {\n const loggerConfig = config && config.loggerConfig;\n LogManager.updateLoggerConfig(loggerConfig);\n};\n\nconst WebSocketManagerObject = {\n create: WebSocketManagerConstructor,\n setGlobalConfig: setGlobalConfig,\n LogLevel: LogLevel,\n Logger: Logger\n};\n\nexport { WebSocketManagerObject };\n","/* global window, exports, define */\n\n!function() {\n 'use strict'\n\n var re = {\n not_string: /[^s]/,\n not_bool: /[^t]/,\n not_type: /[^T]/,\n not_primitive: /[^v]/,\n number: /[diefg]/,\n numeric_arg: /[bcdiefguxX]/,\n json: /[j]/,\n not_json: /[^j]/,\n text: /^[^\\x25]+/,\n modulo: /^\\x25{2}/,\n placeholder: /^\\x25(?:([1-9]\\d*)\\$|\\(([^)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-gijostTuvxX])/,\n key: /^([a-z_][a-z_\\d]*)/i,\n key_access: /^\\.([a-z_][a-z_\\d]*)/i,\n index_access: /^\\[(\\d+)\\]/,\n sign: /^[+-]/\n }\n\n function sprintf(key) {\n // `arguments` is not an array, but should be fine for this call\n return sprintf_format(sprintf_parse(key), arguments)\n }\n\n function vsprintf(fmt, argv) {\n return sprintf.apply(null, [fmt].concat(argv || []))\n }\n\n function sprintf_format(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign\n for (i = 0; i < tree_length; i++) {\n if (typeof parse_tree[i] === 'string') {\n output += parse_tree[i]\n }\n else if (typeof parse_tree[i] === 'object') {\n ph = parse_tree[i] // convenience purposes only\n if (ph.keys) { // keyword argument\n arg = argv[cursor]\n for (k = 0; k < ph.keys.length; k++) {\n if (arg == undefined) {\n throw new Error(sprintf('[sprintf] Cannot access property \"%s\" of undefined value \"%s\"', ph.keys[k], ph.keys[k-1]))\n }\n arg = arg[ph.keys[k]]\n }\n }\n else if (ph.param_no) { // positional argument (explicit)\n arg = argv[ph.param_no]\n }\n else { // positional argument (implicit)\n arg = argv[cursor++]\n }\n\n if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {\n arg = arg()\n }\n\n if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {\n throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))\n }\n\n if (re.number.test(ph.type)) {\n is_positive = arg >= 0\n }\n\n switch (ph.type) {\n case 'b':\n arg = parseInt(arg, 10).toString(2)\n break\n case 'c':\n arg = String.fromCharCode(parseInt(arg, 10))\n break\n case 'd':\n case 'i':\n arg = parseInt(arg, 10)\n break\n case 'j':\n arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)\n break\n case 'e':\n arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()\n break\n case 'f':\n arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)\n break\n case 'g':\n arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)\n break\n case 'o':\n arg = (parseInt(arg, 10) >>> 0).toString(8)\n break\n case 's':\n arg = String(arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 't':\n arg = String(!!arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'T':\n arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'u':\n arg = parseInt(arg, 10) >>> 0\n break\n case 'v':\n arg = arg.valueOf()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'x':\n arg = (parseInt(arg, 10) >>> 0).toString(16)\n break\n case 'X':\n arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()\n break\n }\n if (re.json.test(ph.type)) {\n output += arg\n }\n else {\n if (re.number.test(ph.type) && (!is_positive || ph.sign)) {\n sign = is_positive ? '+' : '-'\n arg = arg.toString().replace(re.sign, '')\n }\n else {\n sign = ''\n }\n pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '\n pad_length = ph.width - (sign + arg).length\n pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''\n output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)\n }\n }\n }\n return output\n }\n\n var sprintf_cache = Object.create(null)\n\n function sprintf_parse(fmt) {\n if (sprintf_cache[fmt]) {\n return sprintf_cache[fmt]\n }\n\n var _fmt = fmt, match, parse_tree = [], arg_names = 0\n while (_fmt) {\n if ((match = re.text.exec(_fmt)) !== null) {\n parse_tree.push(match[0])\n }\n else if ((match = re.modulo.exec(_fmt)) !== null) {\n parse_tree.push('%')\n }\n else if ((match = re.placeholder.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1\n var field_list = [], replacement_field = match[2], field_match = []\n if ((field_match = re.key.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = re.key_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else if ((field_match = re.index_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n }\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n match[2] = field_list\n }\n else {\n arg_names |= 2\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')\n }\n\n parse_tree.push(\n {\n placeholder: match[0],\n param_no: match[1],\n keys: match[2],\n sign: match[3],\n pad_char: match[4],\n align: match[5],\n width: match[6],\n precision: match[7],\n type: match[8]\n }\n )\n }\n else {\n throw new SyntaxError('[sprintf] unexpected placeholder')\n }\n _fmt = _fmt.substring(match[0].length)\n }\n return sprintf_cache[fmt] = parse_tree\n }\n\n /**\n * export to either browser or node.js\n */\n /* eslint-disable quote-props */\n if (typeof exports !== 'undefined') {\n exports['sprintf'] = sprintf\n exports['vsprintf'] = vsprintf\n }\n if (typeof window !== 'undefined') {\n window['sprintf'] = sprintf\n window['vsprintf'] = vsprintf\n\n if (typeof define === 'function' && define['amd']) {\n define(function() {\n return {\n 'sprintf': sprintf,\n 'vsprintf': vsprintf\n }\n })\n }\n }\n /* eslint-enable quote-props */\n}(); // eslint-disable-line\n","/*eslint no-unused-vars: \"off\"*/\nimport { WebSocketManagerObject } from \"./webSocketManager\";\n\nglobal.connect = global.connect || {};\nconnect.WebSocketManager = WebSocketManagerObject;\n\nexport const WebSocketManager = WebSocketManagerObject;\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"],"sourceRoot":""} \ No newline at end of file diff --git a/src/log.js b/src/log.js index 07a21f8b..bd59ae66 100644 --- a/src/log.js +++ b/src/log.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/mediaControllers/chat.js b/src/mediaControllers/chat.js index 931d98e3..0c2c9788 100644 --- a/src/mediaControllers/chat.js +++ b/src/mediaControllers/chat.js @@ -14,7 +14,7 @@ */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; diff --git a/src/mediaControllers/factory.js b/src/mediaControllers/factory.js index 0e41bba0..caab0a4b 100644 --- a/src/mediaControllers/factory.js +++ b/src/mediaControllers/factory.js @@ -14,7 +14,7 @@ */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; diff --git a/src/mediaControllers/softphone.js b/src/mediaControllers/softphone.js index 5659a59a..f4e8f528 100644 --- a/src/mediaControllers/softphone.js +++ b/src/mediaControllers/softphone.js @@ -14,7 +14,7 @@ */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; diff --git a/src/mediaControllers/task.js b/src/mediaControllers/task.js index 5a5517cf..7812f793 100644 --- a/src/mediaControllers/task.js +++ b/src/mediaControllers/task.js @@ -14,7 +14,7 @@ */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; diff --git a/src/ringtone.js b/src/ringtone.js index 0aabab9d..756837e3 100644 --- a/src/ringtone.js +++ b/src/ringtone.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/softphone.js b/src/softphone.js index 49a940ac..fb503f24 100644 --- a/src/softphone.js +++ b/src/softphone.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/sprintf.js b/src/sprintf.js index 4e8a8917..d76dc56e 100644 --- a/src/sprintf.js +++ b/src/sprintf.js @@ -1,7 +1,7 @@ /*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ (function() { - var ctx = this || window; + var ctx = this || globalThis; var sprintf = function() { if (!sprintf.cache.hasOwnProperty(arguments[0])) { diff --git a/src/streams.js b/src/streams.js index c8041dd1..6d290258 100644 --- a/src/streams.js +++ b/src/streams.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function() { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/transitions.js b/src/transitions.js index a0d1bfad..4eb2f22c 100644 --- a/src/transitions.js +++ b/src/transitions.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function() { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/src/util.js b/src/util.js index f5cd4868..b4043143 100644 --- a/src/util.js +++ b/src/util.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; @@ -500,6 +500,13 @@ }); }; + connect.publishClickStreamData = function(report) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.CLICK_STREAM_DATA, + data: report + }); + }; + connect.publishClientSideLogs = function(logs) { var bus = connect.core.getEventBus(); bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); @@ -656,35 +663,40 @@ 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); + var instance = new Error(connect.vsprintf(format, args)); + Object.setPrototypeOf(instance, connect.ValueError.prototype); + return instance; }; - connect.ValueError.prototype = Object.create(connect.BaseError.prototype); - connect.ValueError.prototype.constructor = connect.ValueError; + Object.setPrototypeOf(connect.ValueError.prototype, Error.prototype); + Object.setPrototypeOf(connect.ValueError, Error); + connect.ValueError.prototype.name = 'ValueError'; connect.NotImplementedError = function () { var args = Array.prototype.slice.call(arguments, 0); var format = args.shift(); - connect.BaseError.call(this, format, args); + var instance = new Error(connect.vsprintf(format, args)); + Object.setPrototypeOf(instance, connect.NotImplementedError.prototype); + return instance; }; - connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype); - connect.NotImplementedError.prototype.constructor = connect.NotImplementedError; + Object.setPrototypeOf(connect.NotImplementedError.prototype, Error.prototype); + Object.setPrototypeOf(connect.NotImplementedError, Error); + connect.NotImplementedError.prototype.name = '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; + var instance = new Error(connect.vsprintf(format, args)); + Object.setPrototypeOf(instance, connect.StateError.prototype); + return instance; + } + Object.setPrototypeOf(connect.StateError.prototype, Error.prototype); + Object.setPrototypeOf(connect.StateError, Error); + connect.StateError.prototype.name = 'StateError'; + + connect.VoiceIdError = function(type, message, err){ var error = {}; diff --git a/src/worker.js b/src/worker.js index 745b54b3..22587b7a 100644 --- a/src/worker.js +++ b/src/worker.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ (function () { - var global = this || window; + var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; diff --git a/test/unit/connections.spec.js b/test/unit/connections.spec.js index c5d45588..b02b2c3f 100644 --- a/test/unit/connections.spec.js +++ b/test/unit/connections.spec.js @@ -105,7 +105,7 @@ describe('Connections API', function () { assert.equal(voiceConnection.contactId, contactId); assert.equal(voiceConnection.getMediaType(), connect.MediaType.SOFTPHONE); assert.equal(typeof(voiceConnection.getVoiceIdSpeakerId), 'function'); - assert.equal(typeof(voiceConnection.getVoiceIdSpeakerStatus), 'function'); + assert.equal(typeof(voiceConnection.getVoiceIdSpeakerStatus), 'function') }); describe('getVoiceIdSpeakerId', function() { diff --git a/test/unit/core.spec.js b/test/unit/core.spec.js index 909882a4..974979dc 100644 --- a/test/unit/core.spec.js +++ b/test/unit/core.spec.js @@ -74,7 +74,20 @@ describe('Core', function () { expect(connect.core.portStreamId).to.equal('portId'); connect.core.initialized = false; }); - it.skip("Replicates logs received upstream while ignoring duplicates", function () { + it("should update the number of connected CCPs in the tab and total on UPDATE_CONNECTED_CCPS event", function () { + expect(connect.numberOfConnectedCCPs).to.equal(0); + expect(connect.numberOfConnectedCCPsInThisTab).to.equal(0); + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.UPDATE_CONNECTED_CCPS, { length: 1 , 'id': { length: 1}}); + expect(connect.numberOfConnectedCCPs).to.equal(1); + expect(connect.numberOfConnectedCCPsInThisTab).to.equal(1); + }); + it("should not emit ccp tabs across browser count if no data.tabId or data.streamsTabsAcrossBrowser", function () { + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.UPDATE_CONNECTED_CCPS, { length: 1 }); + sandbox.assert.notCalled(connect.ifMaster); + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.UPDATE_CONNECTED_CCPS, { length: 1, tabId: 'id', streamsTabsAcrossBrowser: 1 }); + sandbox.assert.calledOnce(connect.ifMaster); + }); + it("Replicates logs received upstream while ignoring duplicates", function () { var logger = connect.getLog(); var loggerId = logger.getLoggerId(); var originalLoggerLength = logger._logs.length; @@ -1286,4 +1299,48 @@ describe('Core', function () { expect(connect.core.taskTemplatesClient.endpointUrl).to.equal("https://abc.com/task-templates/api/ccp"); }); }); + + describe('connect.core.activateChannelWithViewType', function () { + jsdom({ url: "http://localhost" }); + const viewType = "create_task", mediaType = "task"; + let sendUpstream; + before(() => { + connect.core.upstream = { sendUpstream: () => {} }; + sendUpstream = sandbox.stub(connect.core.upstream, "sendUpstream"); + }) + beforeEach(() => { + sandbox.reset(); + }); + after(() => { + sandbox.restore(); + connect.core.upstream = null; + }); + it('call activateChannelWithViewType with base parameters "viewType", "mediaType"', function () { + connect.core.activateChannelWithViewType(viewType, mediaType); + sandbox.assert.calledOnceWithMatch(sendUpstream, connect.EventType.BROADCAST, + { + event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, + data: { viewType, mediaType } + } + ); + }); + it('call activateChannelWithViewType with an optional parameter "source"', function () { + connect.core.activateChannelWithViewType(viewType, mediaType, "agentapp"); + sandbox.assert.calledOnceWithMatch(sendUpstream, connect.EventType.BROADCAST, + { + event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, + data: { viewType, mediaType, source: "agentapp" } + } + ); + }); + it('call activateChannelWithViewType with optional parameters "source", "caseId"', function () { + connect.core.activateChannelWithViewType(viewType, mediaType, "keystone", "1234567890"); + sandbox.assert.calledOnceWithMatch(sendUpstream, connect.EventType.BROADCAST, + { + event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, + data: { viewType, mediaType, source: "keystone", caseId: "1234567890" } + } + ); + }); + }); });