diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f1bb59d6f..9271d7728 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,3 +1,2 @@ -* @parfeon @mohitpubnub @MikeDobrzan -.github/* @parfeon @mohitpubnub @MikeDobrzan -README.md @techwritermat @kazydek +* @mohitpubnub @parfeon @seba-aln +README.md @techwritermat @kazydek @mohitpubnub @parfeon diff --git a/.github/workflows/commands-handler.yml b/.github/workflows/commands-handler.yml index 312a2226b..0b5d4702b 100644 --- a/.github/workflows/commands-handler.yml +++ b/.github/workflows/commands-handler.yml @@ -15,7 +15,7 @@ jobs: steps: - name: Check referred user id: user-check - env: + env: CLEN_BOT: ${{ secrets.CLEN_BOT }} run: echo "expected-user=${{ startsWith(github.event.comment.body, format('@{0} ', env.CLEN_BOT)) }}" >> $GITHUB_OUTPUT - name: Regular comment @@ -40,4 +40,4 @@ jobs: with: token: ${{ secrets.GH_TOKEN }} listener: ${{ secrets.CLEN_BOT }} - jira-api-key: ${{ secrets.JIRA_API_KEY }} \ No newline at end of file + jira-api-key: ${{ secrets.JIRA_API_KEY }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bbb6aa84b..1d2cc36ba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,16 +43,13 @@ jobs: ref: v1 token: ${{ secrets.GH_TOKEN }} path: .github/.release/actions - - name: configure aws credentials - uses: aws-actions/configure-aws-credentials@v2 - with: - role-to-assume: ${{ secrets.AWS_ROLE_ARN }} - role-session-name: javascript-sdk-s3-upload - aws-region: us-east-1 - name: Publish to S3 uses: ./.github/.release/actions/actions/services/aws with: token: ${{ secrets.GH_TOKEN }} + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + auth-method: access-key content-type: application/javascript content-encoding: gzip acl: public-read diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index b19533801..7e8adc3f0 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -19,11 +19,11 @@ jobs: strategy: fail-fast: true matrix: - node: [12, 14, 16] - env: ["ci:node"] + node: [14, 16] + env: ['ci:node'] include: - node: 16 - env: "ci:web" + env: 'ci:web' steps: - name: Checkout repository uses: actions/checkout@v3 diff --git a/.github/workflows/run-validations.yml b/.github/workflows/run-validations.yml index 3ade808dd..7936cc669 100644 --- a/.github/workflows/run-validations.yml +++ b/.github/workflows/run-validations.yml @@ -12,7 +12,7 @@ defaults: jobs: pubnub-yml: - name: "Validate .pubnub.yml" + name: 'Validate .pubnub.yml' runs-on: ubuntu-latest steps: - name: Checkout project @@ -37,4 +37,4 @@ jobs: needs: [pubnub-yml] steps: - name: Validations summary - run: echo -e "\033[38;2;95;215;0m\033[1mAll validations passed" \ No newline at end of file + run: echo -e "\033[38;2;95;215;0m\033[1mAll validations passed" diff --git a/.pubnub.yml b/.pubnub.yml index 709e04529..eb4701846 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,59 @@ --- changelog: + - date: 2023-11-28 + version: v7.4.5 + changes: + - type: bug + text: "Handle unencrypted messages in subscribe with cryptoModule configured." + - type: bug + text: "Fixe for missing parameters to request or filter optional fields for App Context memberships api." + - date: 2023-11-14 + version: v7.4.4 + changes: + - type: bug + text: "Fixes issue of getChannelMembers call not returning status field." + - date: 2023-11-08 + version: v7.4.3 + changes: + - type: bug + text: "Fixes issue of not able to encrypt Blob file content in web." + - date: 2023-10-30 + version: v7.4.2 + changes: + - type: improvement + text: "Changed license type from MIT to PubNub Software Development Kit License." + - date: 2023-10-17 + version: v7.4.1 + changes: + - type: bug + text: "Fixes issue of `pubnub.decrypt()` returning wrong data format." + - date: 2023-10-16 + version: v7.4.0 + changes: + - type: feature + text: "Add crypto module that allows configure SDK to encrypt and decrypt messages." + - type: bug + text: "Improved security of crypto implementation by adding enhanced AES-CBC cryptor." + - date: 2023-09-11 + version: v7.3.3 + changes: + - type: bug + text: "Fixes issue of getting misleading error message when sendFile fails." + - date: 2023-08-31 + version: v7.3.2 + changes: + - type: bug + text: "Fixes issue of having deprecated superagent version." + - date: 2023-08-21 + version: v7.3.1 + changes: + - type: bug + text: "Fixes issue of missing get and set methods for userId field of PubNub configuration." + - date: 2023-07-26 + version: v7.3.0 + changes: + - type: bug + text: "Fixes issue of severe vulnerability warnings for vm2 usage." - date: 2023-06-19 version: v7.2.3 changes: @@ -875,7 +929,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '7.2.3' +version: '7.4.5' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -891,7 +945,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v7.2.3.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v7.4.5.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1562,7 +1616,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v7.2.3/pubnub.7.2.3.js + location: https://github.com/pubnub/javascript/releases/download/v7.4.5/pubnub.7.4.5.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index a2ef724ed..0adfe22b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,69 @@ +## v7.4.5 +November 28 2023 + +#### Fixed +- Handle unencrypted messages in subscribe with cryptoModule configured. +- Fixe for missing parameters to request or filter optional fields for App Context memberships api. + +## v7.4.4 +November 14 2023 + +#### Fixed +- Fixes issue of getChannelMembers call not returning status field. + +## v7.4.3 +November 08 2023 + +#### Fixed +- Fixes issue of not able to encrypt Blob file content in web. + +## v7.4.2 +October 30 2023 + +#### Modified +- Changed license type from MIT to PubNub Software Development Kit License. + +## v7.4.1 +October 17 2023 + +#### Fixed +- Fixes issue of `pubnub.decrypt()` returning wrong data format. + +## v7.4.0 +October 16 2023 + +#### Added +- Add crypto module that allows configure SDK to encrypt and decrypt messages. + +#### Fixed +- Improved security of crypto implementation by adding enhanced AES-CBC cryptor. + +## v7.3.3 +September 11 2023 + +#### Fixed +- Fixes issue of getting misleading error message when sendFile fails. + +## v7.3.2 +August 31 2023 + +#### Fixed +- Fixes issue of having deprecated superagent version. Fixed the following issues reported by [@wimZ](https://github.com/wimZ): [#317](https://github.com/pubnub/javascript/issues/317). + +## v7.3.1 +August 21 2023 + +#### Fixed +- Fixes issue of missing get and set methods for userId field of PubNub configuration. + +## v7.3.0 +July 26 2023 + +#### Fixed +- Fixes issue of severe vulnerability warnings for vm2 usage. + + + ## v7.2.3 June 19 2023 diff --git a/LICENSE b/LICENSE index 3efa3922e..5e1ef1880 100644 --- a/LICENSE +++ b/LICENSE @@ -1,27 +1,29 @@ -PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks -Copyright (c) 2013 PubNub Inc. -http://www.pubnub.com/ -http://www.pubnub.com/terms +PubNub Software Development Kit License Agreement +Copyright © 2023 PubNub Inc. All rights reserved. -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: +Subject to the terms and conditions of the license, you are hereby granted +a non-exclusive, worldwide, royalty-free license to (a) copy and modify +the software in source code or binary form for use with the software services +and interfaces provided by PubNub, and (b) redistribute unmodified copies +of the software to third parties. The software may not be incorporated in +or used to provide any product or service competitive with the products +and services of PubNub. -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this license shall be included +in or with 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. +This license does not grant you permission to use the trade names, trademarks, +service marks, or product names of PubNub, except as required for reasonable +and customary use in describing the origin of the software and reproducing +the content of this license. -PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks -Copyright (c) 2013 PubNub Inc. -http://www.pubnub.com/ -http://www.pubnub.com/terms +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 PUBNUB OR THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE 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. + +https://www.pubnub.com/ +https://www.pubnub.com/terms diff --git a/README.md b/README.md index 7ffead572..fbfbd3864 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,12 @@ PubNub takes care of the infrastructure and APIs needed for the realtime communi You will need the publish and subscribe keys to authenticate your app. Get your keys from the [Admin Portal](https://dashboard.pubnub.com/login). +## Tutorial Video + +[![Getting Started with PubNub JS SDK](https://replayable-api-production.herokuapp.com/replay/64ee0d2ca4bc310061f566ca/gif?shareKey=8YQoHC40jdzYpYGpcJhQ)](https://app.dashcam.io/replay/64ee0d2ca4bc310061f566ca?share=8YQoHC40jdzYpYGpcJhQ) + +Watch [Getting Started with PubNub JS SDK](https://app.dashcam.io/replay/64ee0d2ca4bc310061f566ca?share=8YQoHC40jdzYpYGpcJhQ) on Dashcam + ## Configure PubNub 1. Integrate the JavaScript SDK into your project: @@ -22,8 +28,8 @@ You will need the publish and subscribe keys to authenticate your app. Get your npm install pubnub ``` * or download one of our builds from our CDN: - * https://cdn.pubnub.com/sdk/javascript/pubnub.7.2.3.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.7.2.3.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.5.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.5.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 1e2ee66dc..c26d9de00 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -137,6 +137,21 @@ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + var cbor = {exports: {}}; /* @@ -621,7 +636,7 @@ this.sdkFamily = setup.sdkFamily; this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); - this.setCipherKey(setup.cipherKey); + this.cryptoModule = setup.cryptoModule; this.setFilterExpression(setup.filterExpression); if (typeof setup.origin !== 'string' && !Array.isArray(setup.origin) && setup.origin !== undefined) { throw new Error('Origin must be either undefined, a string or a list of strings.'); @@ -683,6 +698,7 @@ } this.setUUID(setup.uuid); } + this.setCipherKey(setup.cipherKey, setup); } // exposed setters default_1.prototype.getAuthKey = function () { @@ -692,8 +708,15 @@ this.authKey = val; return this; }; - default_1.prototype.setCipherKey = function (val) { + default_1.prototype.setCipherKey = function (val, setup, modules) { + var _a; this.cipherKey = val; + if (this.cipherKey) { + this.cryptoModule = + (_a = setup.cryptoModule) !== null && _a !== void 0 ? _a : setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + if (modules) + modules.cryptoModule = this.cryptoModule; + } return this; }; default_1.prototype.getUUID = function () { @@ -771,7 +794,7 @@ return this; }; default_1.prototype.getVersion = function () { - return '7.2.3'; + return '7.4.5'; }; default_1.prototype.setRetryConfiguration = function (configuration) { if (configuration.minimumdelay < 2) { @@ -844,6 +867,45 @@ } return data; } + function encode$1(input) { + var base64 = ''; + var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var bytes = new Uint8Array(input); + var byteLength = bytes.byteLength; + var byteRemainder = byteLength % 3; + var mainLength = byteLength - byteRemainder; + var a, b, c, d; + var chunk; + // Main loop deals with bytes in chunks of 3 + for (var i = 0; i < mainLength; i = i + 3) { + // Combine the three bytes into a single integer + chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + // Use bitmasks to extract 6-bit segments from the triplet + a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 + b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 + c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 + d = chunk & 63; // 63 = 2^6 - 1 + // Convert the raw binary segments to the appropriate ASCII encoding + base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; + } + // Deal with the remaining bytes and padding + if (byteRemainder == 1) { + chunk = bytes[mainLength]; + a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 + // Set the 4 least significant bits to zero + b = (chunk & 3) << 4; // 3 = 2^2 - 1 + base64 += encodings[a] + encodings[b] + '=='; + } + else if (byteRemainder == 2) { + chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; + a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 + b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 + // Set the 2 least significant bits to zero + c = (chunk & 15) << 2; // 15 = 2^4 - 1 + base64 += encodings[a] + encodings[b] + encodings[c] + '='; + } + return base64; + } /*eslint-disable */ /* @@ -1767,11 +1829,20 @@ }); return { promise: promise, reject: failureResolve, fulfill: successResolve }; } + function stringToArrayBuffer(str) { + var buf = new ArrayBuffer(str.length * 2); + var bufView = new Uint16Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; + } var utils$5 = { signPamFromParams: signPamFromParams, endsWith: endsWith, createPromise: createPromise, encodeString: encodeString, + stringToArrayBuffer: stringToArrayBuffer, }; /* */ @@ -1801,7 +1872,7 @@ var default_1$7 = /** @class */ (function () { function default_1(_a) { - var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager; + var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule; this._listenerManager = listenerManager; this._config = config; this._leaveEndpoint = leaveEndpoint; @@ -1810,6 +1881,7 @@ this._subscribeEndpoint = subscribeEndpoint; this._getFileUrl = getFileUrl; this._crypto = crypto; + this._cryptoModule = cryptoModule; this._channels = {}; this._presenceChannels = {}; this._heartbeatChannels = {}; @@ -1825,6 +1897,8 @@ this._isOnline = true; this._reconnectionManager = new default_1$9({ timeEndpoint: timeEndpoint }); this._dedupingManager = new default_1$8({ config: config }); + if (this._cryptoModule) + this._decoder = new TextDecoder(); } default_1.prototype.adaptStateChange = function (args, callback) { var _this = this; @@ -2292,9 +2366,18 @@ announce.timetoken = publishMetaData.publishTimetoken; announce.publisher = message.issuingClientId; var msgPayload = message.payload; - if (_this._config.cipherKey) { - var decryptedPayload = _this._crypto.decrypt(message.payload); - if (typeof decryptedPayload === 'object' && decryptedPayload !== null) { + if (_this._cryptoModule) { + var decryptedPayload = void 0; + try { + var decryptedData = _this._cryptoModule.decrypt(message.payload); + decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; + } + catch (e) { + decryptedPayload = null; + announce.error = "Error while decrypting message content: ".concat(e.message); + } + if (decryptedPayload !== null) { msgPayload = decryptedPayload; } } @@ -2328,8 +2411,23 @@ if (message.userMetadata) { announce.userMetadata = message.userMetadata; } - if (_this._config.cipherKey) { - announce.message = _this._crypto.decrypt(message.payload); + if (_this._cryptoModule) { + var decryptedPayload = void 0; + try { + var decryptedData = _this._cryptoModule.decrypt(message.payload); + decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; + } + catch (e) { + decryptedPayload = null; + announce.error = "Error while decrypting message content: ".concat(e.message); + } + if (decryptedPayload != null) { + announce.message = decryptedPayload; + } + else { + announce.message = message.payload; + } } else { announce.message = message.payload; @@ -4630,11 +4728,11 @@ }; /** */ - var preparePayload = function (_a, payload) { - var crypto = _a.crypto, config = _a.config; + var preparePayload = function (modules, payload) { var stringifiedPayload = JSON.stringify(payload); - if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + if (modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$1(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; @@ -4687,26 +4785,15 @@ }); }, }; - var getErrorFromResponse = function (response) { - return new Promise(function (resolve) { - var result = ''; - response.on('data', function (data) { - result += data.toString('utf8'); - }); - response.on('end', function () { - resolve(result); - }); - }); - }; var sendFile = function (_a) { var _this = this; - var generateUploadUrl = _a.generateUploadUrl, publishFile = _a.publishFile, _b = _a.modules, PubNubFile = _b.PubNubFile, config = _b.config, cryptography = _b.cryptography, networking = _b.networking; + var generateUploadUrl = _a.generateUploadUrl, publishFile = _a.publishFile, _b = _a.modules, PubNubFile = _b.PubNubFile, config = _b.config, cryptography = _b.cryptography, cryptoModule = _b.cryptoModule, networking = _b.networking; return function (_a) { var channel = _a.channel, input = _a.file, message = _a.message, cipherKey = _a.cipherKey, meta = _a.meta, ttl = _a.ttl, storeInHistory = _a.storeInHistory; return __awaiter(_this, void 0, void 0, function () { - var file, _b, _c, url, formFields, _d, id, name, formFieldsWithMimeType, result, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, e_1, errorBody, reason, retries, wasSuccessful, publishResult; - return __generator(this, function (_s) { - switch (_s.label) { + var file, _b, _c, url, formFields, _d, id, name, _e, formFieldsWithMimeType, result, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, e_1, errorBody, reason, retries, wasSuccessful, publishResult; + return __generator(this, function (_t) { + switch (_t.label) { case 0: if (!channel) { throw new PubNubError('Validation failed, check status for details', createValidationError("channel can't be empty")); @@ -4717,13 +4804,21 @@ file = PubNubFile.create(input); return [4 /*yield*/, generateUploadUrl({ channel: channel, name: file.name })]; case 1: - _b = _s.sent(), _c = _b.file_upload_request, url = _c.url, formFields = _c.form_fields, _d = _b.data, id = _d.id, name = _d.name; - if (!(PubNubFile.supportsEncryptFile && (cipherKey !== null && cipherKey !== void 0 ? cipherKey : config.cipherKey))) return [3 /*break*/, 3]; - return [4 /*yield*/, cryptography.encryptFile(cipherKey !== null && cipherKey !== void 0 ? cipherKey : config.cipherKey, file, PubNubFile)]; + _b = _t.sent(), _c = _b.file_upload_request, url = _c.url, formFields = _c.form_fields, _d = _b.data, id = _d.id, name = _d.name; + if (!(PubNubFile.supportsEncryptFile && (cipherKey || cryptoModule))) return [3 /*break*/, 6]; + if (!(cipherKey == null)) return [3 /*break*/, 3]; + return [4 /*yield*/, cryptoModule.encryptFile(file, PubNubFile)]; case 2: - file = _s.sent(); - _s.label = 3; - case 3: + _e = _t.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, cryptography.encryptFile(cipherKey, file, PubNubFile)]; + case 4: + _e = _t.sent(); + _t.label = 5; + case 5: + file = _e; + _t.label = 6; + case 6: formFieldsWithMimeType = formFields; if (file.mimeType) { formFieldsWithMimeType = formFields.map(function (entry) { @@ -4732,56 +4827,56 @@ return entry; }); } - _s.label = 4; - case 4: - _s.trys.push([4, 18, , 22]); - if (!(PubNubFile.supportsFileUri && input.uri)) return [3 /*break*/, 7]; - _f = (_e = networking).POSTFILE; - _g = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toFileUri()]; - case 5: return [4 /*yield*/, _f.apply(_e, _g.concat([_s.sent()]))]; - case 6: - result = _s.sent(); - return [3 /*break*/, 17]; + _t.label = 7; case 7: - if (!PubNubFile.supportsFile) return [3 /*break*/, 10]; - _j = (_h = networking).POSTFILE; - _k = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toFile()]; - case 8: return [4 /*yield*/, _j.apply(_h, _k.concat([_s.sent()]))]; + _t.trys.push([7, 21, , 22]); + if (!(PubNubFile.supportsFileUri && input.uri)) return [3 /*break*/, 10]; + _g = (_f = networking).POSTFILE; + _h = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toFileUri()]; + case 8: return [4 /*yield*/, _g.apply(_f, _h.concat([_t.sent()]))]; case 9: - result = _s.sent(); - return [3 /*break*/, 17]; + result = _t.sent(); + return [3 /*break*/, 20]; case 10: - if (!PubNubFile.supportsBuffer) return [3 /*break*/, 13]; - _m = (_l = networking).POSTFILE; - _o = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toBuffer()]; - case 11: return [4 /*yield*/, _m.apply(_l, _o.concat([_s.sent()]))]; + if (!PubNubFile.supportsFile) return [3 /*break*/, 13]; + _k = (_j = networking).POSTFILE; + _l = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toFile()]; + case 11: return [4 /*yield*/, _k.apply(_j, _l.concat([_t.sent()]))]; case 12: - result = _s.sent(); - return [3 /*break*/, 17]; + result = _t.sent(); + return [3 /*break*/, 20]; case 13: - if (!PubNubFile.supportsBlob) return [3 /*break*/, 16]; - _q = (_p = networking).POSTFILE; - _r = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toBlob()]; - case 14: return [4 /*yield*/, _q.apply(_p, _r.concat([_s.sent()]))]; + if (!PubNubFile.supportsBuffer) return [3 /*break*/, 16]; + _o = (_m = networking).POSTFILE; + _p = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toBuffer()]; + case 14: return [4 /*yield*/, _o.apply(_m, _p.concat([_t.sent()]))]; case 15: - result = _s.sent(); - return [3 /*break*/, 17]; - case 16: throw new Error('Unsupported environment'); - case 17: return [3 /*break*/, 22]; + result = _t.sent(); + return [3 /*break*/, 20]; + case 16: + if (!PubNubFile.supportsBlob) return [3 /*break*/, 19]; + _r = (_q = networking).POSTFILE; + _s = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toBlob()]; + case 17: return [4 /*yield*/, _r.apply(_q, _s.concat([_t.sent()]))]; case 18: - e_1 = _s.sent(); - if (!e_1.response) return [3 /*break*/, 20]; - return [4 /*yield*/, getErrorFromResponse(e_1.response)]; - case 19: - errorBody = _s.sent(); - reason = /(.*)<\/Message>/gi.exec(errorBody); - throw new PubNubError(reason ? "Upload to bucket failed: ".concat(reason[1]) : 'Upload to bucket failed.', e_1); - case 20: throw new PubNubError('Upload to bucket failed.', e_1); - case 21: return [3 /*break*/, 22]; + result = _t.sent(); + return [3 /*break*/, 20]; + case 19: throw new Error('Unsupported environment'); + case 20: return [3 /*break*/, 22]; + case 21: + e_1 = _t.sent(); + if (e_1.response && typeof e_1.response.text === 'string') { + errorBody = e_1.response.text; + reason = /(.*)<\/Message>/gi.exec(errorBody); + throw new PubNubError(reason ? "Upload to bucket failed: ".concat(reason[1]) : 'Upload to bucket failed.', e_1); + } + else { + throw new PubNubError('Upload to bucket failed.', e_1); + } case 22: if (result.status !== 204) { throw new PubNubError('Upload to bucket was unsuccessful', result); @@ -4789,9 +4884,9 @@ retries = config.fileUploadPublishRetryLimit; wasSuccessful = false; publishResult = { timetoken: '0' }; - _s.label = 23; + _t.label = 23; case 23: - _s.trys.push([23, 25, , 26]); + _t.trys.push([23, 25, , 26]); return [4 /*yield*/, publishFile({ channel: channel, message: message, @@ -4803,16 +4898,16 @@ })]; case 24: /* eslint-disable-next-line no-await-in-loop */ - publishResult = _s.sent(); + publishResult = _t.sent(); wasSuccessful = true; return [3 /*break*/, 26]; case 25: - _s.sent(); + _t.sent(); retries -= 1; return [3 /*break*/, 26]; case 26: if (!wasSuccessful && retries > 0) return [3 /*break*/, 23]; - _s.label = 27; + _t.label = 27; case 27: if (!wasSuccessful) { throw new PubNubError('Publish failed. You may want to execute that operation manually using pubnub.publishFile', { @@ -4880,7 +4975,7 @@ return "".concat(networking.getStandardOrigin()).concat(url); }); - /** */ + // Download_file.js var endpoint$g = { getOperation: function () { return OPERATIONS.PNDownloadFileOperation; }, validateParams: function (_, params) { @@ -4908,20 +5003,28 @@ forceBuffered: function () { return true; }, prepareParams: function () { return ({}); }, handleResponse: function (_a, res, params) { - var PubNubFile = _a.PubNubFile, config = _a.config, cryptography = _a.cryptography; + var PubNubFile = _a.PubNubFile, config = _a.config, cryptography = _a.cryptography, cryptoModule = _a.cryptoModule; return __awaiter(void 0, void 0, void 0, function () { - var body; - var _b, _c, _d; + var body, _b; + var _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: body = res.response.body; - if (!(PubNubFile.supportsEncryptFile && ((_b = params.cipherKey) !== null && _b !== void 0 ? _b : config.cipherKey))) return [3 /*break*/, 2]; - return [4 /*yield*/, cryptography.decrypt((_c = params.cipherKey) !== null && _c !== void 0 ? _c : config.cipherKey, body)]; + if (!(PubNubFile.supportsEncryptFile && (params.cipherKey || cryptoModule))) return [3 /*break*/, 5]; + if (!(params.cipherKey == null)) return [3 /*break*/, 2]; + return [4 /*yield*/, cryptoModule.decryptFile(PubNubFile.create({ data: body, name: params.name }), PubNubFile)]; case 1: - body = _e.sent(); - _e.label = 2; - case 2: return [2 /*return*/, PubNubFile.create({ + _b = (_e.sent()).data; + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, cryptography.decrypt((_c = params.cipherKey) !== null && _c !== void 0 ? _c : config.cipherKey, body)]; + case 3: + _b = _e.sent(); + _e.label = 4; + case 4: + body = _b; + _e.label = 5; + case 5: return [2 /*return*/, PubNubFile.create({ data: body, name: (_d = res.response.name) !== null && _d !== void 0 ? _d : params.name, mimeType: res.response.type, @@ -5286,7 +5389,7 @@ getOperation: function () { return OPERATIONS.PNGetMembersOperation; }, validateParams: function (_, params) { if (!(params === null || params === void 0 ? void 0 : params.channel)) { - return 'UUID cannot be empty'; + return 'channel cannot be empty'; } }, getURL: function (_a, params) { @@ -5299,36 +5402,45 @@ }, isAuthSupported: function () { return true; }, prepareParams: function (_modules, params) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var queryParams = {}; - queryParams.include = ['uuid.status', 'uuid.type', 'type']; + queryParams.include = []; if (params === null || params === void 0 ? void 0 : params.include) { - if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.customFields) { + if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.statusField) { + queryParams.include.push('status'); + } + if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customFields) { queryParams.include.push('custom'); } - if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customUUIDFields) { + if ((_c = params.include) === null || _c === void 0 ? void 0 : _c.UUIDFields) { + queryParams.include.push('uuid'); + } + if ((_d = params.include) === null || _d === void 0 ? void 0 : _d.customUUIDFields) { queryParams.include.push('uuid.custom'); } - if ((_d = (_c = params.include) === null || _c === void 0 ? void 0 : _c.UUIDFields) !== null && _d !== void 0 ? _d : true) { - queryParams.include.push('uuid'); + if ((_e = params.include) === null || _e === void 0 ? void 0 : _e.UUIDStatusField) { + queryParams.include.push('uuid.status'); + } + if ((_f = params.include) === null || _f === void 0 ? void 0 : _f.UUIDTypeField) { + queryParams.include.push('uuid.type'); } } queryParams.include = queryParams.include.join(','); - if ((_e = params === null || params === void 0 ? void 0 : params.include) === null || _e === void 0 ? void 0 : _e.totalCount) { - queryParams.count = (_f = params.include) === null || _f === void 0 ? void 0 : _f.totalCount; + if ((_g = params === null || params === void 0 ? void 0 : params.include) === null || _g === void 0 ? void 0 : _g.totalCount) { + queryParams.count = (_h = params.include) === null || _h === void 0 ? void 0 : _h.totalCount; } - if ((_g = params === null || params === void 0 ? void 0 : params.page) === null || _g === void 0 ? void 0 : _g.next) { - queryParams.start = (_h = params.page) === null || _h === void 0 ? void 0 : _h.next; + if ((_j = params === null || params === void 0 ? void 0 : params.page) === null || _j === void 0 ? void 0 : _j.next) { + queryParams.start = (_k = params.page) === null || _k === void 0 ? void 0 : _k.next; } - if ((_j = params === null || params === void 0 ? void 0 : params.page) === null || _j === void 0 ? void 0 : _j.prev) { - queryParams.end = (_k = params.page) === null || _k === void 0 ? void 0 : _k.prev; + if ((_l = params === null || params === void 0 ? void 0 : params.page) === null || _l === void 0 ? void 0 : _l.prev) { + queryParams.end = (_m = params.page) === null || _m === void 0 ? void 0 : _m.prev; } if (params === null || params === void 0 ? void 0 : params.filter) { queryParams.filter = params.filter; } - queryParams.limit = (_l = params === null || params === void 0 ? void 0 : params.limit) !== null && _l !== void 0 ? _l : 100; + queryParams.limit = (_o = params === null || params === void 0 ? void 0 : params.limit) !== null && _o !== void 0 ? _o : 100; if (params === null || params === void 0 ? void 0 : params.sort) { - queryParams.sort = Object.entries((_m = params.sort) !== null && _m !== void 0 ? _m : {}).map(function (_a) { + queryParams.sort = Object.entries((_p = params.sort) !== null && _p !== void 0 ? _p : {}).map(function (_a) { var _b = __read(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); @@ -5456,36 +5568,45 @@ }, isAuthSupported: function () { return true; }, prepareParams: function (_modules, params) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var queryParams = {}; - queryParams.include = ['channel.status', 'channel.type', 'status']; + queryParams.include = []; if (params === null || params === void 0 ? void 0 : params.include) { - if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.customFields) { - queryParams.include.push('custom'); + if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.statusField) { + queryParams.include.push('status'); } - if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customChannelFields) { - queryParams.include.push('channel.custom'); + if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customFields) { + queryParams.include.push('custom'); } if ((_c = params.include) === null || _c === void 0 ? void 0 : _c.channelFields) { queryParams.include.push('channel'); } + if ((_d = params.include) === null || _d === void 0 ? void 0 : _d.customChannelFields) { + queryParams.include.push('channel.custom'); + } + if ((_e = params.include) === null || _e === void 0 ? void 0 : _e.channelStatusField) { + queryParams.include.push('channel.status'); + } + if ((_f = params.include) === null || _f === void 0 ? void 0 : _f.channelTypeField) { + queryParams.include.push('channel.type'); + } } queryParams.include = queryParams.include.join(','); - if ((_d = params === null || params === void 0 ? void 0 : params.include) === null || _d === void 0 ? void 0 : _d.totalCount) { - queryParams.count = (_e = params.include) === null || _e === void 0 ? void 0 : _e.totalCount; + if ((_g = params === null || params === void 0 ? void 0 : params.include) === null || _g === void 0 ? void 0 : _g.totalCount) { + queryParams.count = (_h = params.include) === null || _h === void 0 ? void 0 : _h.totalCount; } - if ((_f = params === null || params === void 0 ? void 0 : params.page) === null || _f === void 0 ? void 0 : _f.next) { - queryParams.start = (_g = params.page) === null || _g === void 0 ? void 0 : _g.next; + if ((_j = params === null || params === void 0 ? void 0 : params.page) === null || _j === void 0 ? void 0 : _j.next) { + queryParams.start = (_k = params.page) === null || _k === void 0 ? void 0 : _k.next; } - if ((_h = params === null || params === void 0 ? void 0 : params.page) === null || _h === void 0 ? void 0 : _h.prev) { - queryParams.end = (_j = params.page) === null || _j === void 0 ? void 0 : _j.prev; + if ((_l = params === null || params === void 0 ? void 0 : params.page) === null || _l === void 0 ? void 0 : _l.prev) { + queryParams.end = (_m = params.page) === null || _m === void 0 ? void 0 : _m.prev; } if (params === null || params === void 0 ? void 0 : params.filter) { queryParams.filter = params.filter; } - queryParams.limit = (_k = params === null || params === void 0 ? void 0 : params.limit) !== null && _k !== void 0 ? _k : 100; + queryParams.limit = (_o = params === null || params === void 0 ? void 0 : params.limit) !== null && _o !== void 0 ? _o : 100; if (params === null || params === void 0 ? void 0 : params.sort) { - queryParams.sort = Object.entries((_l = params.sort) !== null && _l !== void 0 ? _l : {}).map(function (_a) { + queryParams.sort = Object.entries((_p = params.sort) !== null && _p !== void 0 ? _p : {}).map(function (_a) { var _b = __read(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); @@ -6015,13 +6136,13 @@ /* */ function prepareMessagePayload$1(modules, messagePayload) { - var crypto = modules.crypto, config = modules.config; var stringifiedPayload = JSON.stringify(messagePayload); - if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + if (modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$1(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } - return stringifiedPayload; + return stringifiedPayload || ''; } function getOperation$7() { return OPERATIONS.PNPublishOperation; @@ -6154,15 +6275,24 @@ /* */ function __processMessage$1(modules, message) { - var config = modules.config, crypto = modules.crypto; - if (!config.cipherKey) - return message; + var result = {}; + if (!modules.cryptoModule) { + result.payload = message; + return result; + } try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + result.payload = decryptedPayload; + return result; } catch (e) { - return message; + if (modules.config.logVerbosity && console && console.log) + console.log('decryption error', e.message); + result.payload = message; + result.error = "Error while decrypting message content: ".concat(e.message); } + return result; } function getOperation$5() { return OPERATIONS.PNHistoryOperation; @@ -6213,13 +6343,16 @@ }; if (Array.isArray(serverResponse[0])) { serverResponse[0].forEach(function (serverHistoryItem) { + var processedMessgeResult = __processMessage$1(modules, serverHistoryItem.message); var item = { timetoken: serverHistoryItem.timetoken, - entry: __processMessage$1(modules, serverHistoryItem.message), + entry: processedMessgeResult.payload, }; if (serverHistoryItem.meta) { item.meta = serverHistoryItem.meta; } + if (processedMessgeResult.error) + item.error = processedMessgeResult.error; response.messages.push(item); }); } @@ -6289,7 +6422,6 @@ handleResponse: handleResponse$4 }); - /* */ function getOperation$3() { return OPERATIONS.PNMessageCounts; } @@ -6300,7 +6432,7 @@ return 'Missing channel'; if (timetoken && channelTimetokens) return 'timetoken and channelTimetokens are incompatible together'; - if (timetoken && channelTimetokens && channelTimetokens.length > 1 && channels.length !== channelTimetokens.length) { + if (channelTimetokens && channelTimetokens.length > 1 && channels.length !== channelTimetokens.length) { return 'Length of channelTimetokens and channels do not match'; } if (!config.subscribeKey) @@ -6351,15 +6483,24 @@ /* */ function __processMessage(modules, message) { - var config = modules.config, crypto = modules.crypto; - if (!config.cipherKey) - return message; + var result = {}; + if (!modules.cryptoModule) { + result.payload = message; + return result; + } try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + result.payload = decryptedPayload; + return result; } catch (e) { - return message; + if (modules.config.logVerbosity && console && console.log) + console.log('decryption error', e.message); + result.payload = message; + result.error = "Error while decrypting message content: ".concat(e.message); } + return result; } function getOperation$2() { return OPERATIONS.PNFetchMessagesOperation; @@ -6421,9 +6562,10 @@ response.channels[channelName] = []; (serverResponse.channels[channelName] || []).forEach(function (messageEnvelope) { var announce = {}; + var processedMessgeResult = __processMessage(modules, messageEnvelope.message); announce.channel = channelName; announce.timetoken = messageEnvelope.timetoken; - announce.message = __processMessage(modules, messageEnvelope.message); + announce.message = processedMessgeResult.payload; announce.messageType = messageEnvelope.message_type; announce.uuid = messageEnvelope.uuid; if (messageEnvelope.actions) { @@ -6434,6 +6576,8 @@ if (messageEnvelope.meta) { announce.meta = messageEnvelope.meta; } + if (processedMessgeResult.error) + announce.error = processedMessgeResult.error; response.channels[channelName].push(announce); }); }); @@ -7989,6 +8133,7 @@ maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; + var cryptoModule = this._config.cryptoModule; var modules = { config: config, networking: networking, @@ -7997,10 +8142,23 @@ tokenManager: tokenManager, telemetryManager: telemetryManager, PubNubFile: setup.PubNubFile, + cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; - this.encryptFile = function (key, file) { return cryptography.encryptFile(key, file, _this.File); }; - this.decryptFile = function (key, file) { return cryptography.decryptFile(key, file, _this.File); }; + this.encryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { + file = key; + return modules.cryptoModule.encryptFile(file, this.File); + } + return cryptography.encryptFile(key, file, this.File); + }; + this.decryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { + file = key; + return modules.cryptoModule.decryptFile(file, this.File); + } + return cryptography.decryptFile(key, file, this.File); + }; var timeEndpoint = endpointCreator.bind(this, modules, timeEndpointConfig); var leaveEndpoint = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig); var heartbeatEndpoint = endpointCreator.bind(this, modules, presenceHeartbeatEndpointConfig); @@ -8091,6 +8249,7 @@ config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, + cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -8319,6 +8478,9 @@ customFields: params.include.customFields, UUIDFields: params.include.userFields, customUUIDFields: params.include.customUserFields, + statusField: params.include.statusField, + UUIDStatusField: params.include.userStatusField, + UUIDTypeField: params.include.userTypeField, totalCount: params.include.totalCount, }, sort: params.sort != null @@ -8352,6 +8514,9 @@ customFields: params.include.customFields, channelFields: params.include.spaceFields, customChannelFields: params.include.customSpaceFields, + statusField: params.include.statusField, + channelStatusField: params.include.spaceStatusField, + channelTypeField: params.include.spaceTypeField, totalCount: params.include.totalCount, }, sort: params.sort != null @@ -8380,16 +8545,35 @@ this.stop = this.destroy; // -------- // --- deprecated ------------------ // mount crypto - this.encrypt = crypto.encrypt.bind(crypto); - this.decrypt = crypto.decrypt.bind(crypto); + this.encrypt = function (data, key) { + if (typeof key === 'undefined' && modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(data); + return typeof encrypted === 'string' ? encrypted : encode$1(encrypted); + } + else { + return crypto.encrypt(data, key); + } + }; + this.decrypt = function (data, key) { + if (typeof key === 'undefined' && cryptoModule) { + var decrypted = modules.cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decrypted)) : decrypted; + } + else { + return crypto.decrypt(data, key); + } + }; /* config */ this.getAuthKey = modules.config.getAuthKey.bind(modules.config); this.setAuthKey = modules.config.setAuthKey.bind(modules.config); - this.setCipherKey = modules.config.setCipherKey.bind(modules.config); this.getUUID = modules.config.getUUID.bind(modules.config); this.setUUID = modules.config.setUUID.bind(modules.config); + this.getUserId = modules.config.getUserId.bind(modules.config); + this.setUserId = modules.config.setUserId.bind(modules.config); this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config); this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config); + // this.setCipherKey = modules.config.setCipherKey.bind(modules.config); + this.setCipherKey = function (key) { return modules.config.setCipherKey(key, setup, modules); }; this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { this.setProxy = function (proxy) { @@ -8987,202 +9171,1357 @@ } } - var replace = String.prototype.replace; - var percentTwenties = /%20/g; + /* eslint complexity: [2, 18], max-statements: [2, 33] */ + var shams = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } - var Format = { - RFC1738: 'RFC1738', - RFC3986: 'RFC3986' - }; + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } - var formats$3 = { - 'default': Format.RFC3986, - formatters: { - RFC1738: function (value) { - return replace.call(value, percentTwenties, '+'); - }, - RFC3986: function (value) { - return String(value); - } - }, - RFC1738: Format.RFC1738, - RFC3986: Format.RFC3986 - }; + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - var formats$2 = formats$3; + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } - var has$2 = Object.prototype.hasOwnProperty; - var isArray$2 = Array.isArray; + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - var hexTable = (function () { - var array = []; - for (var i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - return array; - }()); + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - var compactQueue = function compactQueue(queue) { - while (queue.length > 1) { - var item = queue.pop(); - var obj = item.obj[item.prop]; + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } - if (isArray$2(obj)) { - var compacted = []; + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - for (var j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } - } + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } - item.obj[item.prop] = compacted; - } - } + return true; }; - var arrayToObject = function arrayToObject(source, options) { - var obj = options && options.plainObjects ? Object.create(null) : {}; - for (var i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } + var origSymbol = typeof Symbol !== 'undefined' && Symbol; + var hasSymbolSham = shams; - return obj; + var hasSymbols$1 = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); }; - var merge = function merge(target, source, options) { - /* eslint no-param-reassign: 0 */ - if (!source) { - return target; + /* eslint no-invalid-this: 1 */ + + var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; + var slice = Array.prototype.slice; + var toStr$1 = Object.prototype.toString; + var funcType = '[object Function]'; + + var implementation$1 = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr$1.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); } + var args = slice.call(arguments, 1); - if (typeof source !== 'object') { - if (isArray$2(target)) { - target.push(source); - } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has$2.call(Object.prototype, source)) { - target[source] = true; + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; } + return this; } else { - return [target, source]; + return target.apply( + that, + args.concat(slice.call(arguments)) + ); } + }; - return target; + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); } - if (!target || typeof target !== 'object') { - return [target].concat(source); - } + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - var mergeTarget = target; - if (isArray$2(target) && !isArray$2(source)) { - mergeTarget = arrayToObject(target, options); + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; } - if (isArray$2(target) && isArray$2(source)) { - source.forEach(function (item, i) { - if (has$2.call(target, i)) { - var targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = merge(targetItem, item, options); - } else { - target.push(item); - } - } else { - target[i] = item; - } - }); - return target; - } + return bound; + }; - return Object.keys(source).reduce(function (acc, key) { - var value = source[key]; + var implementation = implementation$1; - if (has$2.call(acc, key)) { - acc[key] = merge(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); + var functionBind = Function.prototype.bind || implementation; + + var bind$1 = functionBind; + + var src = bind$1.call(Function.call, Object.prototype.hasOwnProperty); + + var undefined$1; + + var $SyntaxError = SyntaxError; + var $Function = Function; + var $TypeError$1 = TypeError; + + // eslint-disable-next-line consistent-return + var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} }; - var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); + var $gOPD = Object.getOwnPropertyDescriptor; + if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } + } + + var throwTypeError = function () { + throw new $TypeError$1(); + }; + var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + + var hasSymbols = hasSymbols$1(); + + var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + + var needsEval = {}; + + var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array); + + var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined$1, + '%AsyncFromSyncIteratorPrototype%': undefined$1, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined$1, + '%JSON%': typeof JSON === 'object' ? JSON : undefined$1, + '%Map%': typeof Map === 'undefined' ? undefined$1 : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined$1 : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined$1, + '%Symbol%': hasSymbols ? Symbol : undefined$1, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError$1, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet }; - var decode = function (str, decoder, charset) { - var strWithoutPlus = str.replace(/\+/g, ' '); - if (charset === 'iso-8859-1') { - // unescape never throws, no try...catch needed: - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - // utf-8 - try { - return decodeURIComponent(strWithoutPlus); - } catch (e) { - return strWithoutPlus; - } + var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; }; - var encode = function encode(str, defaultEncoder, charset, kind, format) { - // This code was originally written by Brian White (mscdex) for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } + var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] + }; - var string = str; - if (typeof str === 'symbol') { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== 'string') { - string = String(str); - } + var bind = functionBind; + var hasOwn$2 = src; + var $concat$1 = bind.call(Function.call, Array.prototype.concat); + var $spliceApply = bind.call(Function.apply, Array.prototype.splice); + var $replace$1 = bind.call(Function.call, String.prototype.replace); + var $strSlice = bind.call(Function.call, String.prototype.slice); + + /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ + var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace$1(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace$1(subString, reEscapeChar, '$1') : number || match; + }); + return result; + }; + /* end adaptation */ + + var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn$2(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn$2(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError$1('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); + }; - if (charset === 'iso-8859-1') { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { - return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; - }); - } + var getIntrinsic = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError$1('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError$1('"allowMissing" argument must be a boolean'); + } + + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat$1([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn$2(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError$1('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined$1; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn$2(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; - var out = ''; - for (var i = 0; i < string.length; ++i) { - var c = string.charCodeAt(i); + var callBind$1 = {exports: {}}; - if ( - c === 0x2D // - - || c === 0x2E // . - || c === 0x5F // _ - || c === 0x7E // ~ - || (c >= 0x30 && c <= 0x39) // 0-9 - || (c >= 0x41 && c <= 0x5A) // a-z - || (c >= 0x61 && c <= 0x7A) // A-Z - || (format === formats$2.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) - ) { - out += string.charAt(i); - continue; - } + (function (module) { - if (c < 0x80) { - out = out + hexTable[c]; - continue; - } + var bind = functionBind; + var GetIntrinsic = getIntrinsic; + + var $apply = GetIntrinsic('%Function.prototype.apply%'); + var $call = GetIntrinsic('%Function.prototype.call%'); + var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + + var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); + var $max = GetIntrinsic('%Math.max%'); + + if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } + } + + module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; + }; - if (c < 0x800) { - out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } + var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); + }; - if (c < 0xD800 || c >= 0xE000) { - out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } + if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); + } else { + module.exports.apply = applyBind; + } + }(callBind$1)); + + var GetIntrinsic$1 = getIntrinsic; + + var callBind = callBind$1.exports; + + var $indexOf = callBind(GetIntrinsic$1('String.prototype.indexOf')); + + var callBound$1 = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic$1(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; + }; + + var _nodeResolve_empty = {}; + + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + + var hasMap = typeof Map === 'function' && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === 'function' && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; + // ie, `has-tostringtag/shams + var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + + var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null + ); + + function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); + } + + var utilInspect = require$$0; + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + + var objectInspect = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has$3(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has$3(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has$3(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has$3(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has$3(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray$3(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has$3(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp$1(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray$3(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (!isDate(obj) && !isRegExp$1(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); + }; + + function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; + } + + function quote(s) { + return $replace.call(String(s), /"/g, '"'); + } + + function isArray$3(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + function isRegExp$1(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + + // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; + } + + function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; + } + + var hasOwn$1 = Object.prototype.hasOwnProperty || function (key) { return key in this; }; + function has$3(obj, key) { + return hasOwn$1.call(obj, key); + } + + function toStr(obj) { + return objectToString.call(obj); + } + + function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; + } + + function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; + } + + function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; + } + + function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; + } + + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); + } + + function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); + } + + function markBoxed(str) { + return 'Object(' + str + ')'; + } + + function weakCollectionOf(type) { + return type + ' { ? }'; + } + + function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; + } + + function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; + } + + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + + function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; + } + + function arrObjKeys(obj, inspect) { + var isArr = isArray$3(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has$3(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has$3(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; + } + + var GetIntrinsic = getIntrinsic; + var callBound = callBound$1; + var inspect = objectInspect; + + var $TypeError = GetIntrinsic('%TypeError%'); + var $WeakMap = GetIntrinsic('%WeakMap%', true); + var $Map = GetIntrinsic('%Map%', true); + + var $weakMapGet = callBound('WeakMap.prototype.get', true); + var $weakMapSet = callBound('WeakMap.prototype.set', true); + var $weakMapHas = callBound('WeakMap.prototype.has', true); + var $mapGet = callBound('Map.prototype.get', true); + var $mapSet = callBound('Map.prototype.set', true); + var $mapHas = callBound('Map.prototype.has', true); + + /* + * This function traverses the list returning the node corresponding to the + * given key. + * + * That node is also moved to the head of the list, so that if it's accessed + * again we don't need to traverse the whole list. By doing so, all the recently + * used nodes can be accessed relatively quickly. + */ + var listGetNode = function (list, key) { // eslint-disable-line consistent-return + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } + }; + + var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; + }; + var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = { // eslint-disable-line no-param-reassign + key: key, + next: objects.next, + value: value + }; + } + }; + var listHas = function (objects, key) { + return !!listGetNode(objects, key); + }; + + var sideChannel = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + /* + * Initialize the linked list as an empty node, so that we don't have + * to special-case handling of the first node: we can always refer to + * it as (previous node).next, instead of something like (list).head + */ + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; + }; + + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + + var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' + }; + + var formats$3 = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + + var formats$2 = formats$3; + + var has$2 = Object.prototype.hasOwnProperty; + var isArray$2 = Array.isArray; + + var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; + }()); + + var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray$2(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } + }; + + var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; + }; + + var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray$2(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has$2.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray$2(target) && !isArray$2(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray$2(target) && isArray$2(source)) { + source.forEach(function (item, i) { + if (has$2.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has$2.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); + }; + + var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); + }; + + var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } + }; + + var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats$2.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); @@ -9260,6 +10599,7 @@ merge: merge }; + var getSideChannel = sideChannel; var utils$3 = utils$4; var formats$1 = formats$3; var has$1 = Object.prototype.hasOwnProperty; @@ -9278,7 +10618,6 @@ }; var isArray$1 = Array.isArray; - var split = String.prototype.split; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray$1(valueOrArray) ? valueOrArray : [valueOrArray]); @@ -9315,10 +10654,13 @@ || typeof v === 'bigint'; }; + var sentinel = {}; + var stringify$1 = function stringify( object, prefix, generateArrayPrefix, + commaRoundTrip, strictNullHandling, skipNulls, encoder, @@ -9329,9 +10671,30 @@ format, formatter, encodeValuesOnly, - charset + charset, + sideChannel ) { var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { @@ -9356,14 +10719,6 @@ if (isNonNullishPrimitive(obj) || utils$3.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder, charset, 'key', format); - if (generateArrayPrefix === 'comma' && encodeValuesOnly) { - var valuesArray = split.call(String(obj), ','); - var valuesJoined = ''; - for (var i = 0; i < valuesArray.length; ++i) { - valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults$1.encoder, charset, 'value', format)); - } - return [formatter(keyValue) + '=' + valuesJoined]; - } return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder, charset, 'value', format))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; @@ -9378,6 +10733,9 @@ var objKeys; if (generateArrayPrefix === 'comma' && isArray$1(obj)) { // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils$3.maybeMap(obj, encoder); + } objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } else if (isArray$1(filter)) { objKeys = filter; @@ -9386,6 +10744,8 @@ objKeys = sort ? keys.sort(sort) : keys; } + var adjustedPrefix = commaRoundTrip && isArray$1(obj) && obj.length === 1 ? prefix + '[]' : prefix; + for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; @@ -9395,16 +10755,20 @@ } var keyPrefix = isArray$1(obj) - ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix - : prefix + (allowDots ? '.' + key : '[' + key + ']'); + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); pushToArray(values, stringify( value, keyPrefix, generateArrayPrefix, + commaRoundTrip, strictNullHandling, skipNulls, - encoder, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray$1(obj) ? null : encoder, filter, sort, allowDots, @@ -9412,7 +10776,8 @@ format, formatter, encodeValuesOnly, - charset + charset, + valueSideChannel )); } @@ -9497,6 +10862,10 @@ } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; if (!objKeys) { objKeys = Object.keys(obj); @@ -9506,6 +10875,7 @@ objKeys.sort(options.sort); } + var sideChannel = getSideChannel(); for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; @@ -9516,6 +10886,7 @@ obj[key], key, generateArrayPrefix, + commaRoundTrip, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, @@ -9526,7 +10897,8 @@ options.format, options.formatter, options.encodeValuesOnly, - options.charset + options.charset, + sideChannel )); } @@ -9554,6 +10926,7 @@ var defaults = { allowDots: false, allowPrototypes: false, + allowSparse: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, @@ -9594,7 +10967,8 @@ var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') var parseValues = function parseQueryStringValues(str, options) { - var obj = {}; + var obj = { __proto__: null }; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); @@ -9763,6 +11137,7 @@ return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, @@ -9799,6 +11174,10 @@ obj = utils$2.merge(obj, newObj, options); } + if (options.allowSparse === true) { + return obj; + } + return utils$2.compact(obj); }; @@ -9812,58 +11191,156 @@ stringify: stringify }; - function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); } + var utils$1 = {}; + + (function (exports) { + function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /** - * Check if `obj` is an object. + * Return the mime type for the given `str`. * - * @param {Object} obj - * @return {Boolean} + * @param {String} str + * @return {String} * @api private */ - function isObject$1(obj) { - return obj !== null && _typeof$1(obj) === 'object'; - } - var isObject_1 = isObject$1; + exports.type = string_ => string_.split(/ *; */).shift(); + + /** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ - function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + exports.params = value => { + const object = {}; + var _iterator = _createForOfIteratorHelper(value.split(/ *; */)), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const string_ = _step.value; + const parts = string_.split(/ *= */); + const key = parts.shift(); + const value = parts.shift(); + if (key && value) object[key] = value; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return object; + }; /** - * Module of mixed-in functions shared between node and client code + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private */ - var isObject = isObject_1; + + exports.parseLinks = value => { + const object = {}; + var _iterator2 = _createForOfIteratorHelper(value.split(/ *, */)), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + const string_ = _step2.value; + const parts = string_.split(/ *; */); + const url = parts[0].slice(1, -1); + const rel = parts[1].split(/ *= */)[1].slice(1, -1); + object[rel] = url; + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + return object; + }; + /** - * Expose `RequestBase`. + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private */ + exports.cleanHeader = (header, changesOrigin) => { + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header.host; + // secuirty + if (changesOrigin) { + delete header.authorization; + delete header.cookie; + } + return header; + }; - var requestBase = RequestBase; /** - * Initialize a new `RequestBase`. + * Check if `obj` is an object. * - * @api public + * @param {Object} object + * @return {Boolean} + * @api private */ + exports.isObject = object => { + return object !== null && typeof object === 'object'; + }; - function RequestBase(object) { - if (object) return mixin$1(object); - } /** - * Mixin the prototype properties. + * Object.hasOwn fallback/polyfill. * - * @param {Object} obj - * @return {Object} + * @type {(object: object, property: string) => boolean} object * @api private */ + exports.hasOwn = Object.hasOwn || function (object, property) { + if (object == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + return Object.prototype.hasOwnProperty.call(new Object(object), property); + }; + exports.mixin = (target, source) => { + for (const key in source) { + if (exports.hasOwn(source, key)) { + target[key] = source[key]; + } + } + }; + }(utils$1)); - function mixin$1(object) { - for (var key in RequestBase.prototype) { - if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) object[key] = RequestBase.prototype[key]; - } + const semver = require$$0; + + /** + * Module of mixed-in functions shared between node and client code + */ + const _require = utils$1, + isObject = _require.isObject, + hasOwn = _require.hasOwn; + + /** + * Expose `RequestBase`. + */ + + var requestBase = RequestBase; + + /** + * Initialize a new `RequestBase`. + * + * @api public + */ + + function RequestBase() {} - return object; - } /** * Clear previous timeout. * @@ -9871,7 +11348,6 @@ * @api public */ - RequestBase.prototype.clearTimeout = function () { clearTimeout(this._timer); clearTimeout(this._responseTimeoutTimer); @@ -9881,6 +11357,7 @@ delete this._uploadTimeoutTimer; return this; }; + /** * Override default response body parser * @@ -9890,11 +11367,11 @@ * @api public */ - RequestBase.prototype.parse = function (fn) { this._parser = fn; return this; }; + /** * Set format of binary response body. * In browser valid formats are 'blob' and 'arraybuffer', @@ -9913,11 +11390,11 @@ * @api public */ - RequestBase.prototype.responseType = function (value) { this._responseType = value; return this; }; + /** * Override default request body serializer * @@ -9927,11 +11404,11 @@ * @api public */ - RequestBase.prototype.serialize = function (fn) { this._serializer = fn; return this; }; + /** * Set timeouts. * @@ -9946,38 +11423,33 @@ * @api public */ - RequestBase.prototype.timeout = function (options) { - if (!options || _typeof(options) !== 'object') { + if (!options || typeof options !== 'object') { this._timeout = options; this._responseTimeout = 0; this._uploadTimeout = 0; return this; } - - for (var option in options) { - if (Object.prototype.hasOwnProperty.call(options, option)) { + for (const option in options) { + if (hasOwn(options, option)) { switch (option) { case 'deadline': this._timeout = options.deadline; break; - case 'response': this._responseTimeout = options.response; break; - case 'upload': this._uploadTimeout = options.upload; break; - default: console.warn('Unknown timeout option', option); } } } - return this; }; + /** * Set number of retry attempts on error. * @@ -9989,7 +11461,6 @@ * @api public */ - RequestBase.prototype.retry = function (count, fn) { // Default to 1 if no count passed or true if (arguments.length === 0 || count === true) count = 1; @@ -9998,7 +11469,9 @@ this._retries = 0; this._retryCallback = fn; return this; - }; // + }; + + // // NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package // // @@ -10009,10 +11482,10 @@ // // TODO: expose these as configurable defaults // + const ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); + const STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); - - var ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); - var STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) + // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) // const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']); /** @@ -10023,23 +11496,22 @@ * @param {Response} [res] response * @returns {Boolean} if segment should be retried */ - - RequestBase.prototype._shouldRetry = function (err, res) { + RequestBase.prototype._shouldRetry = function (error, res) { if (!this._maxRetries || this._retries++ >= this._maxRetries) { return false; } - if (this._retryCallback) { try { - var override = this._retryCallback(err, res); - + const override = this._retryCallback(error, res); if (override === true) return true; - if (override === false) return false; // undefined falls back to defaults - } catch (err_) { - console.error(err_); + if (override === false) return false; + // undefined falls back to defaults + } catch (err) { + console.error(err); } - } // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) + } + // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) /* if ( this.req && @@ -10048,19 +11520,16 @@ ) return false; */ - - if (res && res.status && STATUS_CODES.has(res.status)) return true; - - if (err) { - if (err.code && ERROR_CODES.has(err.code)) return true; // Superagent timeout - - if (err.timeout && err.code === 'ECONNABORTED') return true; - if (err.crossDomain) return true; + if (error) { + if (error.code && ERROR_CODES.has(error.code)) return true; + // Superagent timeout + if (error.timeout && error.code === 'ECONNABORTED') return true; + if (error.crossDomain) return true; } - return false; }; + /** * Retry request * @@ -10068,20 +11537,20 @@ * @api private */ - RequestBase.prototype._retry = function () { - this.clearTimeout(); // node + this.clearTimeout(); + // node if (this.req) { this.req = null; this.req = this.request(); } - this._aborted = false; this.timedout = false; this.timedoutError = null; return this._end(); }; + /** * Promise support * @@ -10090,74 +11559,62 @@ * @return {Request} */ - RequestBase.prototype.then = function (resolve, reject) { - var _this = this; - if (!this._fullfilledPromise) { - var self = this; - + const self = this; if (this._endCalled) { console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); } - - this._fullfilledPromise = new Promise(function (resolve, reject) { - self.on('abort', function () { - if (_this._maxRetries && _this._maxRetries > _this._retries) { + this._fullfilledPromise = new Promise((resolve, reject) => { + self.on('abort', () => { + if (this._maxRetries && this._maxRetries > this._retries) { return; } - - if (_this.timedout && _this.timedoutError) { - reject(_this.timedoutError); + if (this.timedout && this.timedoutError) { + reject(this.timedoutError); return; } - - var err = new Error('Aborted'); - err.code = 'ABORTED'; - err.status = _this.status; - err.method = _this.method; - err.url = _this.url; - reject(err); + const error = new Error('Aborted'); + error.code = 'ABORTED'; + error.status = this.status; + error.method = this.method; + error.url = this.url; + reject(error); }); - self.end(function (err, res) { - if (err) reject(err);else resolve(res); + self.end((error, res) => { + if (error) reject(error);else resolve(res); }); }); } - return this._fullfilledPromise.then(resolve, reject); }; - - RequestBase.prototype.catch = function (cb) { - return this.then(undefined, cb); + RequestBase.prototype.catch = function (callback) { + return this.then(undefined, callback); }; + /** * Allow for extension */ - RequestBase.prototype.use = function (fn) { fn(this); return this; }; - - RequestBase.prototype.ok = function (cb) { - if (typeof cb !== 'function') throw new Error('Callback required'); - this._okCallback = cb; + RequestBase.prototype.ok = function (callback) { + if (typeof callback !== 'function') throw new Error('Callback required'); + this._okCallback = callback; return this; }; - RequestBase.prototype._isResponseOK = function (res) { if (!res) { return false; } - if (this._okCallback) { return this._okCallback(res); } - return res.status >= 200 && res.status < 300; }; + /** * Get request header `field`. * Case-insensitive. @@ -10167,10 +11624,10 @@ * @api public */ - RequestBase.prototype.get = function (field) { return this._header[field.toLowerCase()]; }; + /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. @@ -10183,8 +11640,8 @@ * @deprecated */ - RequestBase.prototype.getHeader = RequestBase.prototype.get; + /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. @@ -10208,17 +11665,16 @@ RequestBase.prototype.set = function (field, value) { if (isObject(field)) { - for (var key in field) { - if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]); + for (const key in field) { + if (hasOwn(field, key)) this.set(key, field[key]); } - return this; } - this._header[field.toLowerCase()] = value; this.header[field] = value; return this; }; + /** * Remove header `field`. * Case-insensitive. @@ -10231,13 +11687,12 @@ * * @param {String} field field name */ - - RequestBase.prototype.unset = function (field) { delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; + /** * Write the field `name` and `val`, or multiple fields with one object * for "multipart/form-data" request bodies. @@ -10254,92 +11709,97 @@ * * @param {String|Object} name name of field * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field + * @param {String} options extra options, e.g. 'blob' * @return {Request} for chaining * @api public */ - - - RequestBase.prototype.field = function (name, value) { + RequestBase.prototype.field = function (name, value, options) { // name should be either a string or an object. if (name === null || undefined === name) { throw new Error('.field(name, val) name can not be empty'); } - if (this._data) { throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); } - if (isObject(name)) { - for (var key in name) { - if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]); + for (const key in name) { + if (hasOwn(name, key)) this.field(key, name[key]); } - return this; } - if (Array.isArray(value)) { - for (var i in value) { - if (Object.prototype.hasOwnProperty.call(value, i)) this.field(name, value[i]); + for (const i in value) { + if (hasOwn(value, i)) this.field(name, value[i]); } - return this; - } // val should be defined now - + } + // val should be defined now if (value === null || undefined === value) { throw new Error('.field(name, val) val can not be empty'); } - if (typeof value === 'boolean') { value = String(value); } - this._getFormData().append(name, value); - + // fix https://github.com/ladjs/superagent/issues/1680 + if (options) this._getFormData().append(name, value, options);else this._getFormData().append(name, value); return this; }; + /** * Abort the request, and clear potential timeout. * * @return {Request} request * @api public */ - - RequestBase.prototype.abort = function () { if (this._aborted) { return this; } - this._aborted = true; if (this.xhr) this.xhr.abort(); // browser - - if (this.req) this.req.abort(); // node + if (this.req) { + // Node v13 has major differences in `abort()` + // https://github.com/nodejs/node/blob/v12.x/lib/internal/streams/end-of-stream.js + // https://github.com/nodejs/node/blob/v13.x/lib/internal/streams/end-of-stream.js + // https://github.com/nodejs/node/blob/v14.x/lib/internal/streams/end-of-stream.js + // (if you run a diff across these you will see the differences) + // + // References: + // + // + // + // Thanks to @shadowgate15 and @niftylettuce + if (semver.gte(process.version, 'v13.0.0') && semver.lt(process.version, 'v14.0.0')) { + // Note that the reason this doesn't work is because in v13 as compared to v14 + // there is no `callback = nop` set in end-of-stream.js above + throw new Error('Superagent does not work in v13 properly with abort() due to Node.js core changes'); + } + this.req.abort(); // node + } this.clearTimeout(); this.emit('abort'); return this; }; - RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { switch (options.type) { case 'basic': - this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass)))); + this.set('Authorization', `Basic ${base64Encoder(`${user}:${pass}`)}`); break; - case 'auto': this.username = user; this.password = pass; break; - case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) - this.set('Authorization', "Bearer ".concat(user)); + this.set('Authorization', `Bearer ${user}`); break; } - return this; }; + /** * Enable transmission of cookies with x-domain requests. * @@ -10347,17 +11807,18 @@ * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". - * + * @param {Boolean} [on=true] - Set 'withCredentials' state + * @return {Request} for chaining * @api public */ - RequestBase.prototype.withCredentials = function (on) { // This is browser-only functionality. Node side is no-op. if (on === undefined) on = true; this._withCredentials = on; return this; }; + /** * Set the max redirects to `n`. Does nothing in browser XHR implementation. * @@ -10366,11 +11827,11 @@ * @api public */ - RequestBase.prototype.redirects = function (n) { this._maxRedirects = n; return this; }; + /** * Maximum size of buffered response body, in bytes. Counts uncompressed size. * Default 200MB. @@ -10378,16 +11839,14 @@ * @param {Number} n number of bytes * @return {Request} for chaining */ - - RequestBase.prototype.maxResponseSize = function (n) { if (typeof n !== 'number') { throw new TypeError('Invalid argument'); } - this._maxResponseSize = n; return this; }; + /** * Convert to a plain javascript object (not JSON string) of scalar properties. * Note as this method is designed to return a useful non-this value, @@ -10397,7 +11856,6 @@ * @api public */ - RequestBase.prototype.toJSON = function () { return { method: this.method, @@ -10406,6 +11864,7 @@ headers: this._header }; }; + /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. @@ -10445,17 +11904,14 @@ * @return {Request} for chaining * @api public */ - // eslint-disable-next-line complexity - + // eslint-disable-next-line complexity RequestBase.prototype.send = function (data) { - var isObject_ = isObject(data); - var type = this._header['content-type']; - + const isObject_ = isObject(data); + let type = this._header['content-type']; if (this._formData) { throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); } - if (isObject_ && !this._data) { if (Array.isArray(data)) { this._data = []; @@ -10464,36 +11920,36 @@ } } else if (data && this._data && this._isHost(this._data)) { throw new Error("Can't merge these send calls"); - } // merge - + } + // merge if (isObject_ && isObject(this._data)) { - for (var key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key]; + for (const key in data) { + if (typeof data[key] == 'bigint' && !data[key].toJSON) throw new Error('Cannot serialize BigInt value to json'); + if (hasOwn(data, key)) this._data[key] = data[key]; } - } else if (typeof data === 'string') { + } else if (typeof data === 'bigint') throw new Error("Cannot send value of type BigInt");else if (typeof data === 'string') { // default to x-www-form-urlencoded if (!type) this.type('form'); type = this._header['content-type']; if (type) type = type.toLowerCase().trim(); - if (type === 'application/x-www-form-urlencoded') { - this._data = this._data ? "".concat(this._data, "&").concat(data) : data; + this._data = this._data ? `${this._data}&${data}` : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } - if (!isObject_ || this._isHost(data)) { return this; - } // default to json - + } + // default to json if (!type) this.type('json'); return this; }; + /** * Sort `querystring` by the sort function * @@ -10522,228 +11978,100 @@ * @api public */ - RequestBase.prototype.sortQuery = function (sort) { // _sort default to true but otherwise can be a function or boolean this._sort = typeof sort === 'undefined' ? true : sort; return this; }; + /** * Compose querystring to append to req.url * * @api private */ - - RequestBase.prototype._finalizeQueryString = function () { - var query = this._query.join('&'); - + const query = this._query.join('&'); if (query) { this.url += (this.url.includes('?') ? '&' : '?') + query; } - this._query.length = 0; // Makes the call idempotent if (this._sort) { - var index = this.url.indexOf('?'); - + const index = this.url.indexOf('?'); if (index >= 0) { - var queryArray = this.url.slice(index + 1).split('&'); - + const queryArray = this.url.slice(index + 1).split('&'); if (typeof this._sort === 'function') { queryArray.sort(this._sort); } else { queryArray.sort(); } - this.url = this.url.slice(0, index) + '?' + queryArray.join('&'); } } - }; // For backwards compat only - + }; - RequestBase.prototype._appendQueryString = function () { + // For backwards compat only + RequestBase.prototype._appendQueryString = () => { console.warn('Unsupported'); }; + /** * Invoke callback with timeout error. * * @api private */ - RequestBase.prototype._timeoutError = function (reason, timeout, errno) { if (this._aborted) { return; } - - var err = new Error("".concat(reason + timeout, "ms exceeded")); - err.timeout = timeout; - err.code = 'ECONNABORTED'; - err.errno = errno; + const error = new Error(`${reason + timeout}ms exceeded`); + error.timeout = timeout; + error.code = 'ECONNABORTED'; + error.errno = errno; this.timedout = true; - this.timedoutError = err; + this.timedoutError = error; this.abort(); - this.callback(err); + this.callback(error); }; - RequestBase.prototype._setTimeouts = function () { - var self = this; // deadline + const self = this; + // deadline if (this._timeout && !this._timer) { - this._timer = setTimeout(function () { + this._timer = setTimeout(() => { self._timeoutError('Timeout of ', self._timeout, 'ETIME'); }, this._timeout); - } // response timeout - + } + // response timeout if (this._responseTimeout && !this._responseTimeoutTimer) { - this._responseTimeoutTimer = setTimeout(function () { + this._responseTimeoutTimer = setTimeout(() => { self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); }, this._responseTimeout); } }; - var utils$1 = {}; - - function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - - function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } - - function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - - /** - * Return the mime type for the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - utils$1.type = function (str) { - return str.split(/ *; */).shift(); - }; - /** - * Return header field parameters. - * - * @param {String} str - * @return {Object} - * @api private - */ - - - utils$1.params = function (val) { - var obj = {}; - - var _iterator = _createForOfIteratorHelper(val.split(/ *; */)), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var str = _step.value; - var parts = str.split(/ *= */); - var key = parts.shift(); - - var _val = parts.shift(); - - if (key && _val) obj[key] = _val; - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return obj; - }; - /** - * Parse Link header fields. - * - * @param {String} str - * @return {Object} - * @api private - */ - - - utils$1.parseLinks = function (val) { - var obj = {}; - - var _iterator2 = _createForOfIteratorHelper(val.split(/ *, */)), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var str = _step2.value; - var parts = str.split(/ *; */); - var url = parts[0].slice(1, -1); - var rel = parts[1].split(/ *= */)[1].slice(1, -1); - obj[rel] = url; - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - return obj; - }; /** - * Strip content related fields from `header`. - * - * @param {Object} header - * @return {Object} header - * @api private + * Module dependencies. */ - - utils$1.cleanHeader = function (header, changesOrigin) { - delete header['content-type']; - delete header['content-length']; - delete header['transfer-encoding']; - delete header.host; // secuirty - - if (changesOrigin) { - delete header.authorization; - delete header.cookie; - } - - return header; - }; + const utils = utils$1; - /** - * Module dependencies. - */ - var utils = utils$1; /** * Expose `ResponseBase`. */ - var responseBase = ResponseBase; + /** * Initialize a new `ResponseBase`. * * @api public */ - function ResponseBase(obj) { - if (obj) return mixin(obj); - } - /** - * Mixin the prototype properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - - - function mixin(obj) { - for (var key in ResponseBase.prototype) { - if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key]; - } + function ResponseBase() {} - return obj; - } /** * Get case-insensitive `field` value. * @@ -10752,10 +12080,10 @@ * @api public */ - ResponseBase.prototype.get = function (field) { return this.header[field.toLowerCase()]; }; + /** * Set header related properties: * @@ -10768,29 +12096,31 @@ * @api private */ - ResponseBase.prototype._setHeaderProperties = function (header) { // TODO: moar! // TODO: make this a util - // content-type - var ct = header['content-type'] || ''; - this.type = utils.type(ct); // params - var params = utils.params(ct); + // content-type + const ct = header['content-type'] || ''; + this.type = utils.type(ct); - for (var key in params) { - if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key]; + // params + const parameters = utils.params(ct); + for (const key in parameters) { + if (Object.prototype.hasOwnProperty.call(parameters, key)) this[key] = parameters[key]; } + this.links = {}; - this.links = {}; // links - + // links try { if (header.link) { this.links = utils.parseLinks(header.link); } - } catch (_unused) {// ignore + } catch (err) { + // ignore } }; + /** * Set flags such as `.ok` based on `status`. * @@ -10812,21 +12142,23 @@ * @api private */ - ResponseBase.prototype._setStatusProperties = function (status) { - var type = status / 100 | 0; // status / class + const type = Math.trunc(status / 100); + // status / class this.statusCode = status; this.status = this.statusCode; - this.statusType = type; // basics + this.statusType = type; + // basics this.info = type === 1; this.ok = type === 2; this.redirect = type === 3; this.clientError = type === 4; this.serverError = type === 5; - this.error = type === 4 || type === 5 ? this.toError() : false; // sugar + this.error = type === 4 || type === 5 ? this.toError() : false; + // sugar this.created = status === 201; this.accepted = status === 202; this.noContent = status === 204; @@ -10838,55 +12170,52 @@ this.unprocessableEntity = status === 422; }; - function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - - function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - + function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - - function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } - - function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - + function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function Agent() { this._defaults = []; } - - ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) { + for (var _i = 0, _arr = ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts']; _i < _arr.length; _i++) { + const fn = _arr[_i]; // Default setting for all requests from this agent Agent.prototype[fn] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } - this._defaults.push({ - fn: fn, - args: args + fn, + args }); - return this; }; - }); - - Agent.prototype._setDefaults = function (req) { - this._defaults.forEach(function (def) { - req[def.fn].apply(req, _toConsumableArray(def.args)); - }); + } + Agent.prototype._setDefaults = function (request) { + var _iterator = _createForOfIteratorHelper(this._defaults), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const def = _step.value; + request[def.fn](...def.args); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } }; - var agentBase = Agent; (function (module, exports) { - function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - + function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /** * Root reference for iframes. */ - var root; + let root; if (typeof window !== 'undefined') { // Browser window root = window; @@ -10898,75 +12227,54 @@ // Web Worker root = self; } + const Emitter = componentEmitter.exports; + const safeStringify = fastSafeStringify; + const qs = lib; + const RequestBase = requestBase; + const _require = utils$1, + isObject = _require.isObject, + mixin = _require.mixin, + hasOwn = _require.hasOwn; + const ResponseBase = responseBase; + const Agent = agentBase; - var Emitter = componentEmitter.exports; - - var safeStringify = fastSafeStringify; - - var qs = lib; - - var RequestBase = requestBase; - - var isObject = isObject_1; - - var ResponseBase = responseBase; - - var Agent = agentBase; /** * Noop. */ - function noop() {} + /** * Expose `request`. */ - module.exports = function (method, url) { // callback if (typeof url === 'function') { return new exports.Request('GET', method).end(url); - } // url first - + } + // url first if (arguments.length === 1) { return new exports.Request('GET', method); } - return new exports.Request(method, url); }; - exports = module.exports; - var request = exports; + const request = exports; exports.Request = Request; + /** * Determine XHR. */ - request.getXHR = function () { - if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) { - return new XMLHttpRequest(); + request.getXHR = () => { + if (root.XMLHttpRequest) { + return new root.XMLHttpRequest(); } - - try { - return new ActiveXObject('Microsoft.XMLHTTP'); - } catch (_unused) {} - - try { - return new ActiveXObject('Msxml2.XMLHTTP.6.0'); - } catch (_unused2) {} - - try { - return new ActiveXObject('Msxml2.XMLHTTP.3.0'); - } catch (_unused3) {} - - try { - return new ActiveXObject('Msxml2.XMLHTTP'); - } catch (_unused4) {} - throw new Error('Browser-only version of superagent could not find XHR'); }; + /** * Removes leading and trailing whitespace, added to support IE. * @@ -10975,12 +12283,8 @@ * @api private */ + const trim = ''.trim ? s => s.trim() : s => s.replace(/(^\s*|\s*$)/g, ''); - var trim = ''.trim ? function (s) { - return s.trim(); - } : function (s) { - return s.replace(/(^\s*|\s*$)/g, ''); - }; /** * Serialize the given `obj`. * @@ -10989,16 +12293,15 @@ * @api private */ - function serialize(obj) { - if (!isObject(obj)) return obj; - var pairs = []; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]); + function serialize(object) { + if (!isObject(object)) return object; + const pairs = []; + for (const key in object) { + if (hasOwn(object, key)) pushEncodedKeyValuePair(pairs, key, object[key]); } - return pairs.join('&'); } + /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. @@ -11008,33 +12311,40 @@ * @param {Mixed} val */ - - function pushEncodedKeyValuePair(pairs, key, val) { - if (val === undefined) return; - - if (val === null) { + function pushEncodedKeyValuePair(pairs, key, value) { + if (value === undefined) return; + if (value === null) { pairs.push(encodeURI(key)); return; } - - if (Array.isArray(val)) { - val.forEach(function (v) { - pushEncodedKeyValuePair(pairs, key, v); - }); - } else if (isObject(val)) { - for (var subkey in val) { - if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]); + if (Array.isArray(value)) { + var _iterator = _createForOfIteratorHelper(value), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const v = _step.value; + pushEncodedKeyValuePair(pairs, key, v); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } else if (isObject(value)) { + for (const subkey in value) { + if (hasOwn(value, subkey)) pushEncodedKeyValuePair(pairs, `${key}[${subkey}]`, value[subkey]); } } else { - pairs.push(encodeURI(key) + '=' + encodeURIComponent(val)); + pairs.push(encodeURI(key) + '=' + encodeURIComponent(value)); } } + /** * Expose serialization method. */ - request.serializeObject = serialize; + /** * Parse the given x-www-form-urlencoded `str`. * @@ -11043,31 +12353,29 @@ * @api private */ - function parseString(str) { - var obj = {}; - var pairs = str.split('&'); - var pair; - var pos; - - for (var i = 0, len = pairs.length; i < len; ++i) { + function parseString(string_) { + const object = {}; + const pairs = string_.split('&'); + let pair; + let pos; + for (let i = 0, length_ = pairs.length; i < length_; ++i) { pair = pairs[i]; pos = pair.indexOf('='); - if (pos === -1) { - obj[decodeURIComponent(pair)] = ''; + object[decodeURIComponent(pair)] = ''; } else { - obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); + object[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); } } - - return obj; + return object; } + /** * Expose parser. */ - request.parseString = parseString; + /** * Default MIME type map. * @@ -11083,6 +12391,7 @@ form: 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; + /** * Default serialization map. * @@ -11096,6 +12405,7 @@ 'application/x-www-form-urlencoded': qs.stringify, 'application/json': safeStringify }; + /** * Default parsers. * @@ -11109,6 +12419,7 @@ 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; + /** * Parse the given header `str` into * an object containing the mapped fields. @@ -11118,30 +12429,27 @@ * @api private */ - function parseHeader(str) { - var lines = str.split(/\r?\n/); - var fields = {}; - var index; - var line; - var field; - var val; - - for (var i = 0, len = lines.length; i < len; ++i) { + function parseHeader(string_) { + const lines = string_.split(/\r?\n/); + const fields = {}; + let index; + let line; + let field; + let value; + for (let i = 0, length_ = lines.length; i < length_; ++i) { line = lines[i]; index = line.indexOf(':'); - if (index === -1) { // could be empty line, just skip it continue; } - field = line.slice(0, index).toLowerCase(); - val = trim(line.slice(index + 1)); - fields[field] = val; + value = trim(line.slice(index + 1)); + fields[field] = value; } - return fields; } + /** * Check if `mime` is json or has +json structured syntax suffix. * @@ -11150,12 +12458,12 @@ * @api private */ - function isJSON(mime) { // should match /json or +json // but not /json-seq return /[/+]json($|[^-\w])/i.test(mime); } + /** * Initialize a new `Response` with the given `xhr`. * @@ -11202,39 +12510,33 @@ * @api private */ - - function Response(req) { - this.req = req; - this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers - + function Response(request_) { + this.req = request_; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; - var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - + let status = this.xhr.status; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request if (status === 1223) { status = 204; } - this._setStatusProperties(status); - this.headers = parseHeader(this.xhr.getAllResponseHeaders()); - this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + this.header = this.headers; + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but // getResponseHeader still works. so we get content-type even if getting // other headers fails. - this.header['content-type'] = this.xhr.getResponseHeader('content-type'); - this._setHeaderProperties(this.header); - - if (this.text === null && req._responseType) { + if (this.text === null && request_._responseType) { this.body = this.xhr.response; } else { this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); } - } // eslint-disable-next-line new-cap - + } + mixin(Response.prototype, ResponseBase.prototype); - ResponseBase(Response.prototype); /** * Parse the given body `str`. * @@ -11246,19 +12548,17 @@ * @api private */ - Response.prototype._parseBody = function (str) { - var parse = request.parse[this.type]; - + Response.prototype._parseBody = function (string_) { + let parse = request.parse[this.type]; if (this.req._parser) { - return this.req._parser(this, str); + return this.req._parser(this, string_); } - if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } - - return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null; + return parse && string_ && (string_.length > 0 || string_ instanceof Object) ? parse(string_) : null; }; + /** * Return an `Error` representative of this response. * @@ -11266,24 +12566,24 @@ * @api public */ - Response.prototype.toError = function () { - var req = this.req; - var method = req.method; - var url = req.url; - var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")"); - var err = new Error(msg); - err.status = this.status; - err.method = method; - err.url = url; - return err; + const req = this.req; + const method = req.method; + const url = req.url; + const message = `cannot ${method} ${url} (${this.status})`; + const error = new Error(message); + error.status = this.status; + error.method = method; + error.url = url; + return error; }; + /** * Expose `Response`. */ - request.Response = Response; + /** * Initialize a new `Request` with the given `method` and `url`. * @@ -11293,70 +12593,64 @@ */ function Request(method, url) { - var self = this; + const self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; // preserves header name case - this._header = {}; // coerces header names to lowercase - - this.on('end', function () { - var err = null; - var res = null; - + this.on('end', () => { + let error = null; + let res = null; try { res = new Response(self); - } catch (err_) { - err = new Error('Parser is unable to parse the response'); - err.parse = true; - err.original = err_; // issue #675: return the raw response if the response parsing fails - + } catch (err) { + error = new Error('Parser is unable to parse the response'); + error.parse = true; + error.original = err; + // issue #675: return the raw response if the response parsing fails if (self.xhr) { // ie9 doesn't have 'response' property - err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails - - err.status = self.xhr.status ? self.xhr.status : null; - err.statusCode = err.status; // backwards-compat only + error.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + error.status = self.xhr.status ? self.xhr.status : null; + error.statusCode = error.status; // backwards-compat only } else { - err.rawResponse = null; - err.status = null; + error.rawResponse = null; + error.status = null; } - - return self.callback(err); + return self.callback(error); } - self.emit('response', res); - var new_err; - + let new_error; try { if (!self._isResponseOK(res)) { - new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); + new_error = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); } - } catch (err_) { - new_err = err_; // ok() callback can throw - } // #1000 don't catch errors from the callback to avoid double calling it - + } catch (err) { + new_error = err; // ok() callback can throw + } - if (new_err) { - new_err.original = err; - new_err.response = res; - new_err.status = res.status; - self.callback(new_err, res); + // #1000 don't catch errors from the callback to avoid double calling it + if (new_error) { + new_error.original = error; + new_error.response = res; + new_error.status = new_error.status || res.status; + self.callback(new_error, res); } else { self.callback(null, res); } }); } + /** * Mixin `Emitter` and `RequestBase`. */ - // eslint-disable-next-line new-cap + // eslint-disable-next-line new-cap + Emitter(Request.prototype); + mixin(Request.prototype, RequestBase.prototype); - Emitter(Request.prototype); // eslint-disable-next-line new-cap - - RequestBase(Request.prototype); /** * Set Content-Type to `type`, mapping values from `request.types`. * @@ -11383,6 +12677,7 @@ this.set('Content-Type', request.types[type] || type); return this; }; + /** * Set Accept to `type`, mapping values from `request.types`. * @@ -11403,11 +12698,11 @@ * @api public */ - Request.prototype.accept = function (type) { this.set('Accept', request.types[type] || type); return this; }; + /** * Set Authorization field value with `user` and `pass`. * @@ -11418,32 +12713,27 @@ * @api public */ - Request.prototype.auth = function (user, pass, options) { if (arguments.length === 1) pass = ''; - - if (_typeof(pass) === 'object' && pass !== null) { + if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options options = pass; pass = ''; } - if (!options) { options = { type: typeof btoa === 'function' ? 'basic' : 'auto' }; } - - var encoder = function encoder(string) { + const encoder = options.encoder ? options.encoder : string => { if (typeof btoa === 'function') { return btoa(string); } - throw new Error('Cannot use basic auth, btoa is not a function'); }; - return this._auth(user, pass, options, encoder); }; + /** * Add query-string `val`. * @@ -11458,12 +12748,12 @@ * @api public */ - - Request.prototype.query = function (val) { - if (typeof val !== 'string') val = serialize(val); - if (val) this._query.push(val); + Request.prototype.query = function (value) { + if (typeof value !== 'string') value = serialize(value); + if (value) this._query.push(value); return this; }; + /** * Queue the given `file` as an attachment to the specified `field`, * with optional `options` (or filename). @@ -11481,26 +12771,22 @@ * @api public */ - Request.prototype.attach = function (field, file, options) { if (file) { if (this._data) { throw new Error("superagent can't mix .send() and .attach()"); } - this._getFormData().append(field, file, options || file.name); } - return this; }; - Request.prototype._getFormData = function () { if (!this._formData) { this._formData = new root.FormData(); } - return this._formData; }; + /** * Invoke the callback with `err` and `res` * and handle arity check. @@ -11510,52 +12796,48 @@ * @api private */ - - Request.prototype.callback = function (err, res) { - if (this._shouldRetry(err, res)) { + Request.prototype.callback = function (error, res) { + if (this._shouldRetry(error, res)) { return this._retry(); } - - var fn = this._callback; + const fn = this._callback; this.clearTimeout(); - - if (err) { - if (this._maxRetries) err.retries = this._retries - 1; - this.emit('error', err); + if (error) { + if (this._maxRetries) error.retries = this._retries - 1; + this.emit('error', error); } - - fn(err, res); + fn(error, res); }; + /** * Invoke callback with x-domain error. * * @api private */ - Request.prototype.crossDomainError = function () { - var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); - err.crossDomain = true; - err.status = this.status; - err.method = this.method; - err.url = this.url; - this.callback(err); - }; // This only warns, because the request is still likely to work - + const error = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + error.crossDomain = true; + error.status = this.status; + error.method = this.method; + error.url = this.url; + this.callback(error); + }; + // This only warns, because the request is still likely to work Request.prototype.agent = function () { console.warn('This is not supported in browser version of superagent'); return this; }; - Request.prototype.ca = Request.prototype.agent; - Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected + Request.prototype.buffer = Request.prototype.ca; - Request.prototype.write = function () { + // This throws, because it can't send/receive data as expected + Request.prototype.write = () => { throw new Error('Streaming is not supported in browser version of superagent'); }; - Request.prototype.pipe = Request.prototype.write; + /** * Check if `obj` is a host object, * we don't want to serialize these :) @@ -11564,11 +12846,11 @@ * @return {Boolean} is a host object * @api private */ - - Request.prototype._isHost = function (obj) { + Request.prototype._isHost = function (object) { // Native objects stringify to [object File], [object Blob], [object FormData], etc. - return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; + return object && typeof object === 'object' && !Array.isArray(object) && Object.prototype.toString.call(object) !== '[object Object]'; }; + /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. @@ -11578,103 +12860,92 @@ * @api public */ - Request.prototype.end = function (fn) { if (this._endCalled) { console.warn('Warning: .end() was called twice. This is not supported in superagent'); } + this._endCalled = true; - this._endCalled = true; // store callback - - this._callback = fn || noop; // querystring + // store callback + this._callback = fn || noop; + // querystring this._finalizeQueryString(); - this._end(); }; - Request.prototype._setUploadTimeout = function () { - var self = this; // upload timeout it's wokrs only if deadline timeout is off + const self = this; + // upload timeout it's wokrs only if deadline timeout is off if (this._uploadTimeout && !this._uploadTimeoutTimer) { - this._uploadTimeoutTimer = setTimeout(function () { + this._uploadTimeoutTimer = setTimeout(() => { self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); }, this._uploadTimeout); } - }; // eslint-disable-next-line complexity - + }; + // eslint-disable-next-line complexity Request.prototype._end = function () { if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); - var self = this; + const self = this; this.xhr = request.getXHR(); - var xhr = this.xhr; - var data = this._formData || this._data; - - this._setTimeouts(); // state change - - - xhr.onreadystatechange = function () { - var readyState = xhr.readyState; + const xhr = this.xhr; + let data = this._formData || this._data; + this._setTimeouts(); + // state change + xhr.addEventListener('readystatechange', () => { + const readyState = xhr.readyState; if (readyState >= 2 && self._responseTimeoutTimer) { clearTimeout(self._responseTimeoutTimer); } - if (readyState !== 4) { return; - } // In IE9, reads to any property (e.g. status) off of an aborted XHR will - // result in the error "Could not complete the operation due to error c00c023f" - - - var status; + } + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + let status; try { status = xhr.status; - } catch (_unused5) { + } catch (err) { status = 0; } - if (!status) { if (self.timedout || self._aborted) return; return self.crossDomainError(); } - self.emit('end'); - }; // progress - + }); - var handleProgress = function handleProgress(direction, e) { + // progress + const handleProgress = (direction, e) => { if (e.total > 0) { e.percent = e.loaded / e.total * 100; - if (e.percent === 100) { clearTimeout(self._uploadTimeoutTimer); } } - e.direction = direction; self.emit('progress', e); }; - if (this.hasListeners('progress')) { try { xhr.addEventListener('progress', handleProgress.bind(null, 'download')); - if (xhr.upload) { xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); } - } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + } catch (err) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. // Reported here: // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context } } - if (xhr.upload) { this._setUploadTimeout(); - } // initiate request - + } + // initiate request try { if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); @@ -11684,59 +12955,52 @@ } catch (err) { // see #1149 return this.callback(err); - } // CORS - + } - if (this._withCredentials) xhr.withCredentials = true; // body + // CORS + if (this._withCredentials) xhr.withCredentials = true; + // body if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { // serialize stuff - var contentType = this._header['content-type']; - - var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; - - if (!_serialize && isJSON(contentType)) { - _serialize = request.serialize['application/json']; + const contentType = this._header['content-type']; + let serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; } + if (serialize) data = serialize(data); + } - if (_serialize) data = _serialize(data); - } // set header fields - - - for (var field in this.header) { + // set header fields + for (const field in this.header) { if (this.header[field] === null) continue; - if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]); + if (hasOwn(this.header, field)) xhr.setRequestHeader(field, this.header[field]); } - if (this._responseType) { xhr.responseType = this._responseType; - } // send stuff + } + // send stuff + this.emit('request', this); - this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) // We need null here if data is undefined - xhr.send(typeof data === 'undefined' ? null : data); }; - - request.agent = function () { - return new Agent(); - }; - - ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) { + request.agent = () => new Agent(); + for (var _i = 0, _arr = ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE']; _i < _arr.length; _i++) { + const method = _arr[_i]; Agent.prototype[method.toLowerCase()] = function (url, fn) { - var req = new request.Request(method, url); - - this._setDefaults(req); - + const request_ = new request.Request(method, url); + this._setDefaults(request_); if (fn) { - req.end(fn); + request_.end(fn); } - - return req; + return request_; }; - }); + } Agent.prototype.del = Agent.prototype.delete; + /** * GET `url` with optional callback `fn(res)`. * @@ -11747,18 +13011,17 @@ * @api public */ - request.get = function (url, data, fn) { - var req = request('GET', url); - + request.get = (url, data, fn) => { + const request_ = request('GET', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.query(data); - if (fn) req.end(fn); - return req; + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; }; + /** * HEAD `url` with optional callback `fn(res)`. * @@ -11769,19 +13032,17 @@ * @api public */ - - request.head = function (url, data, fn) { - var req = request('HEAD', url); - + request.head = (url, data, fn) => { + const request_ = request('HEAD', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.query(data); - if (fn) req.end(fn); - return req; + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; }; + /** * OPTIONS query to `url` with optional callback `fn(res)`. * @@ -11792,19 +13053,17 @@ * @api public */ - - request.options = function (url, data, fn) { - var req = request('OPTIONS', url); - + request.options = (url, data, fn) => { + const request_ = request('OPTIONS', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.send(data); - if (fn) req.end(fn); - return req; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; }; + /** * DELETE `url` with optional `data` and callback `fn(res)`. * @@ -11815,22 +13074,19 @@ * @api public */ - function del(url, data, fn) { - var req = request('DELETE', url); - + const request_ = request('DELETE', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.send(data); - if (fn) req.end(fn); - return req; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; } - request.del = del; request.delete = del; + /** * PATCH `url` with optional `data` and callback `fn(res)`. * @@ -11841,18 +13097,17 @@ * @api public */ - request.patch = function (url, data, fn) { - var req = request('PATCH', url); - + request.patch = (url, data, fn) => { + const request_ = request('PATCH', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.send(data); - if (fn) req.end(fn); - return req; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; }; + /** * POST `url` with optional `data` and callback `fn(res)`. * @@ -11863,19 +13118,17 @@ * @api public */ - - request.post = function (url, data, fn) { - var req = request('POST', url); - + request.post = (url, data, fn) => { + const request_ = request('POST', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.send(data); - if (fn) req.end(fn); - return req; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; }; + /** * PUT `url` with optional `data` and callback `fn(res)`. * @@ -11886,18 +13139,15 @@ * @api public */ - - request.put = function (url, data, fn) { - var req = request('PUT', url); - + request.put = (url, data, fn) => { + const request_ = request('PUT', url); if (typeof data === 'function') { fn = data; data = null; } - - if (data) req.send(data); - if (fn) req.end(fn); - return req; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; }; }(client, client.exports)); @@ -12142,10 +13392,13 @@ var bKey, abPlaindata, abCipherdata; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.getKey(key)]; + case 0: + if (file.data.byteLength <= 0) + throw new Error('encryption error. empty content'); + return [4 /*yield*/, this.getKey(key)]; case 1: bKey = _a.sent(); - return [4 /*yield*/, file.toArrayBuffer()]; + return [4 /*yield*/, file.data.arrayBuffer()]; case 2: abPlaindata = _a.sent(); return [4 /*yield*/, this.encryptArrayBuffer(bKey, abPlaindata)]; @@ -12168,7 +13421,7 @@ case 0: return [4 /*yield*/, this.getKey(key)]; case 1: bKey = _a.sent(); - return [4 /*yield*/, file.toArrayBuffer()]; + return [4 /*yield*/, file.data.arrayBuffer()]; case 2: abCipherdata = _a.sent(); return [4 /*yield*/, this.decryptArrayBuffer(bKey, abCipherdata)]; @@ -12184,15 +13437,16 @@ }; WebCryptography.prototype.getKey = function (key) { return __awaiter(this, void 0, void 0, function () { - var bKey, abHash, abKey; + var digest, hashHex, abKey; return __generator(this, function (_a) { switch (_a.label) { - case 0: - bKey = Buffer.from(key); - return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; + case 0: return [4 /*yield*/, crypto.subtle.digest('SHA-256', WebCryptography.encoder.encode(key))]; case 1: - abHash = _a.sent(); - abKey = Buffer.from(Buffer.from(abHash).toString('hex').slice(0, 32), 'utf8').buffer; + digest = _a.sent(); + hashHex = Array.from(new Uint8Array(digest)) + .map(function (b) { return b.toString(16).padStart(2, '0'); }) + .join(''); + abKey = WebCryptography.encoder.encode(hashHex.slice(0, 32)).buffer; return [2 /*return*/, crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt'])]; } }); @@ -12215,10 +13469,18 @@ }; WebCryptography.prototype.decryptArrayBuffer = function (key, ciphertext) { return __awaiter(this, void 0, void 0, function () { - var abIv; + var abIv, data; return __generator(this, function (_a) { - abIv = ciphertext.slice(0, 16); - return [2 /*return*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16))]; + switch (_a.label) { + case 0: + abIv = ciphertext.slice(0, 16); + if (ciphertext.slice(WebCryptography.IV_LENGTH).byteLength <= 0) + throw new Error('decryption error: empty content'); + return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(WebCryptography.IV_LENGTH))]; + case 1: + data = _a.sent(); + return [2 /*return*/, data]; + } }); }); }; @@ -12229,12 +13491,12 @@ switch (_a.label) { case 0: abIv = crypto.getRandomValues(new Uint8Array(16)); - abPlaintext = Buffer.from(plaintext).buffer; + abPlaintext = WebCryptography.encoder.encode(plaintext).buffer; return [4 /*yield*/, crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext)]; case 1: abPayload = _a.sent(); ciphertext = concatArrayBuffer(abIv.buffer, abPayload); - return [2 /*return*/, Buffer.from(ciphertext).toString('utf8')]; + return [2 /*return*/, WebCryptography.decoder.decode(ciphertext)]; } }); }); @@ -12245,18 +13507,20 @@ return __generator(this, function (_a) { switch (_a.label) { case 0: - abCiphertext = Buffer.from(ciphertext); + abCiphertext = WebCryptography.encoder.encode(ciphertext).buffer; abIv = abCiphertext.slice(0, 16); abPayload = abCiphertext.slice(16); return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload)]; case 1: abPlaintext = _a.sent(); - return [2 /*return*/, Buffer.from(abPlaintext).toString('utf8')]; + return [2 /*return*/, WebCryptography.decoder.decode(abPlaintext)]; } }); }); }; WebCryptography.IV_LENGTH = 16; + WebCryptography.encoder = new TextEncoder(); + WebCryptography.decoder = new TextDecoder(); return WebCryptography; }()); @@ -12372,6 +13636,461 @@ _a.supportsFileUri = false, _a); + var LegacyCryptor = /** @class */ (function () { + function LegacyCryptor(config) { + this.config = config; + this.cryptor = new default_1$a({ config: config }); + this.fileCryptor = new WebCryptography(); + } + Object.defineProperty(LegacyCryptor.prototype, "identifier", { + get: function () { + return ''; + }, + enumerable: false, + configurable: true + }); + LegacyCryptor.prototype.encrypt = function (data) { + var stringData = typeof data === 'string' ? data : new TextDecoder().decode(data); + return { + data: this.cryptor.encrypt(stringData), + metadata: null, + }; + }; + LegacyCryptor.prototype.decrypt = function (encryptedData) { + var data = typeof encryptedData.data === 'string' ? encryptedData.data : encode$1(encryptedData.data); + return this.cryptor.decrypt(data); + }; + LegacyCryptor.prototype.encryptFile = function (file, File) { + var _a; + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_b) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: can not detect cipherKey from old Config + return [2 /*return*/, this.fileCryptor.encryptFile((_a = this.config) === null || _a === void 0 ? void 0 : _a.cipherKey, file, File)]; + }); + }); + }; + LegacyCryptor.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: can not detect cipherKey from old Config + return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)]; + }); + }); + }; + return LegacyCryptor; + }()); + + var AesCbcCryptor = /** @class */ (function () { + function AesCbcCryptor(configuration) { + this.cipherKey = configuration.cipherKey; + this.CryptoJS = hmacSha256; + this.encryptedKey = this.CryptoJS.SHA256(this.cipherKey); + } + Object.defineProperty(AesCbcCryptor.prototype, "algo", { + get: function () { + return 'AES-CBC'; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AesCbcCryptor.prototype, "identifier", { + get: function () { + return 'ACRH'; + }, + enumerable: false, + configurable: true + }); + AesCbcCryptor.prototype.getIv = function () { + return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); + }; + AesCbcCryptor.prototype.getKey = function () { + return __awaiter(this, void 0, void 0, function () { + var bKey, abHash; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + bKey = AesCbcCryptor.encoder.encode(this.cipherKey); + return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; + case 1: + abHash = _a.sent(); + return [2 /*return*/, crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt'])]; + } + }); + }); + }; + AesCbcCryptor.prototype.encrypt = function (data) { + var stringData = typeof data === 'string' ? data : AesCbcCryptor.decoder.decode(data); + if (stringData.length === 0) + throw new Error('encryption error. empty content'); + var abIv = this.getIv(); + return { + metadata: abIv, + data: decode$1(this.CryptoJS.AES.encrypt(data, this.encryptedKey, { + iv: this.bufferToWordArray(abIv), + mode: this.CryptoJS.mode.CBC, + }).ciphertext.toString(this.CryptoJS.enc.Base64)), + }; + }; + AesCbcCryptor.prototype.decrypt = function (encryptedData) { + var iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata)); + var data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); + return AesCbcCryptor.encoder.encode(this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { + iv: iv, + mode: this.CryptoJS.mode.CBC, + }).toString(this.CryptoJS.enc.Utf8)).buffer; + }; + AesCbcCryptor.prototype.encryptFileData = function (data) { + return __awaiter(this, void 0, void 0, function () { + var key, iv; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this.getKey()]; + case 1: + key = _b.sent(); + iv = this.getIv(); + _a = {}; + return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: iv }, key, data)]; + case 2: return [2 /*return*/, (_a.data = _b.sent(), + _a.metadata = iv, + _a)]; + } + }); + }); + }; + AesCbcCryptor.prototype.decryptFileData = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + var key; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.getKey()]; + case 1: + key = _a.sent(); + return [2 /*return*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)]; + } + }); + }); + }; + AesCbcCryptor.prototype.bufferToWordArray = function (b) { + var wa = []; + var i; + for (i = 0; i < b.length; i += 1) { + wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); + } + return this.CryptoJS.lib.WordArray.create(wa, b.length); + }; + AesCbcCryptor.BLOCK_SIZE = 16; + AesCbcCryptor.encoder = new TextEncoder(); + AesCbcCryptor.decoder = new TextDecoder(); + return AesCbcCryptor; + }()); + + var CryptoModule = /** @class */ (function () { + function CryptoModule(cryptoModuleConfiguration) { + var _a; + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: type detection issue with old Config type assignment + CryptoModule.legacyCryptoModule = function (config) { + var _a; + return new this({ + default: new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + var _a; + return new this({ + default: new AesCbcCryptor({ cipherKey: config.cipherKey }), + cryptors: [ + new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], + }); + }; + CryptoModule.withDefaultCryptor = function (defaultCryptor) { + return new this({ default: defaultCryptor }); + }; + CryptoModule.prototype.getAllCryptors = function () { + return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); + }; + CryptoModule.prototype.encrypt = function (data) { + var encrypted = this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) + return encrypted.data; + var headerData = this.getHeaderData(encrypted); + return this.concatArrayBuffer(headerData, encrypted.data); + }; + CryptoModule.prototype.decrypt = function (data) { + var encryptedData = typeof data === 'string' ? decode$1(data) : data; + var header = CryptorHeader.tryParse(encryptedData); + var cryptor = this.getCryptor(header); + var metadata = header.length > 0 + ? encryptedData.slice(header.length - header.metadataLength, header.length) + : null; + if (encryptedData.slice(header.length).byteLength <= 0) + throw new Error('decryption error. empty content'); + return cryptor.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + }; + CryptoModule.prototype.encryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var fileData, encrypted; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + return [4 /*yield*/, this.getFileData(file.data)]; + case 1: + fileData = _a.sent(); + return [4 /*yield*/, this.defaultCryptor.encryptFileData(fileData)]; + case 2: + encrypted = _a.sent(); + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: this.concatArrayBuffer(this.getHeaderData(encrypted), encrypted.data), + })]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var data, header, cryptor, fileData, metadata, _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: return [4 /*yield*/, file.data.arrayBuffer()]; + case 1: + data = _d.sent(); + header = CryptorHeader.tryParse(data); + cryptor = this.getCryptor(header); + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) { + return [2 /*return*/, cryptor.decryptFile(file, File)]; + } + return [4 /*yield*/, this.getFileData(data)]; + case 2: + fileData = _d.sent(); + metadata = fileData.slice(header.length - header.metadataLength, header.length); + _b = (_a = File).create; + _c = { + name: file.name + }; + return [4 /*yield*/, this.defaultCryptor.decryptFileData({ + data: data.slice(header.length), + metadata: metadata, + })]; + case 3: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + _c)])]; + } + }); + }); + }; + CryptoModule.prototype.getCryptor = function (header) { + if (header === '') { + var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); + if (cryptor) + return cryptor; + throw new Error('unknown cryptor error'); + } + else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + }; + CryptoModule.prototype.getCryptorFromId = function (id) { + var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; }); + if (cryptor) { + return cryptor; + } + throw Error('unknown cryptor error'); + }; + CryptoModule.prototype.concatArrayBuffer = function (ab1, ab2) { + var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); + tmp.set(new Uint8Array(ab1), 0); + tmp.set(new Uint8Array(ab2), ab1.byteLength); + return tmp.buffer; + }; + CryptoModule.prototype.getHeaderData = function (encrypted) { + if (!encrypted.metadata) + return; + var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + var headerData = new Uint8Array(header.length); + var pos = 0; + headerData.set(header.data, pos); + pos += header.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + return headerData.buffer; + }; + CryptoModule.prototype.getFileData = function (input) { + return __awaiter(this, void 0, void 0, function () { + var fileData; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(input instanceof Blob)) return [3 /*break*/, 2]; + return [4 /*yield*/, input.arrayBuffer()]; + case 1: + fileData = _a.sent(); + return [2 /*return*/, fileData]; + case 2: + if (input instanceof ArrayBuffer) { + return [2 /*return*/, input]; + } + if (typeof input === 'string') { + return [2 /*return*/, CryptoModule.encoder.encode(input)]; + } + throw new Error('Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob'); + } + }); + }); + }; + CryptoModule.LEGACY_IDENTIFIER = ''; + CryptoModule.encoder = new TextEncoder(); + CryptoModule.decoder = new TextDecoder(); + return CryptoModule; + }()); + // CryptorHeader Utility + var CryptorHeader = /** @class */ (function () { + function CryptorHeader() { + } + CryptorHeader.from = function (id, metadata) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) + return; + return new CryptorHeaderV1(id, metadata.byteLength); + }; + CryptorHeader.tryParse = function (data) { + var encryptedData = new Uint8Array(data); + var sentinel = ''; + var version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) + return ''; + } + if (encryptedData.byteLength >= 5) { + version = encryptedData[4]; + } + else { + throw new Error('decryption error. invalid header version'); + } + if (version > CryptorHeader.MAX_VERSION) + throw new Error('unknown cryptor error'); + var identifier = ''; + var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) { + identifier = encryptedData.slice(5, pos); + } + else { + throw new Error('decryption error. invalid crypto identifier'); + } + var metadataLength = null; + if (encryptedData.byteLength >= pos + 1) { + metadataLength = encryptedData[pos]; + } + else { + throw new Error('decryption error. invalid metadata length'); + } + pos += 1; + if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + pos += 2; + } + return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + CryptorHeader.decoder = new TextDecoder(); + return CryptorHeader; + }()); + // v1 CryptorHeader + var CryptorHeaderV1 = /** @class */ (function () { + function CryptorHeaderV1(id, metadataLength) { + this._identifier = id; + this._metadataLength = metadataLength; + } + Object.defineProperty(CryptorHeaderV1.prototype, "identifier", { + get: function () { + return this._identifier; + }, + set: function (value) { + this._identifier = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "metadataLength", { + get: function () { + return this._metadataLength; + }, + set: function (value) { + this._metadataLength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "version", { + get: function () { + return CryptorHeader.VERSION; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "length", { + get: function () { + return (CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "data", { + get: function () { + var pos = 0; + var header = new Uint8Array(this.length); + var encoder = new TextEncoder(); + header.set(encoder.encode(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(encoder.encode(this.identifier), pos); + pos += CryptorHeader.IDENTIFIER_LENGTH; + var metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; + } + else { + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + } + return header; + }, + enumerable: false, + configurable: true + }); + CryptorHeaderV1.IDENTIFIER_LENGTH = 4; + CryptorHeaderV1.SENTINEL = 'PNED'; + return CryptorHeaderV1; + }()); + /* eslint no-bitwise: ["error", { "allow": ["~", "&", ">>"] }] */ function sendBeacon(url) { if (navigator && navigator.sendBeacon) { @@ -12400,6 +14119,15 @@ setup.cbor = new default_1$1(function (arrayBuffer) { return stringifyBufferKeys(CborReader.decode(arrayBuffer)); }, decode$1); setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); + setup.initCryptoModule = function (cryptoConfiguration) { + return new CryptoModule({ + default: new LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); + }; _this = _super.call(this, setup) || this; if (listenToBrowserNetworkEvents) { // mount network events. @@ -12412,6 +14140,7 @@ } return _this; } + default_1.CryptoModule = CryptoModule; return default_1; }(default_1$3)); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 7290bf6e9..26d385d32 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -12,6 +12,6 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};function t(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function u(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i>2,c=0;c>6),i.push(128|63&s)):s<55296?(i.push(224|s>>12),i.push(128|s>>6&63),i.push(128|63&s)):(s=(1023&s)<<10,s|=1023&t.charCodeAt(++r),s+=65536,i.push(240|s>>18),i.push(128|s>>12&63),i.push(128|s>>6&63),i.push(128|63&s))}return h(3,i.length),p(i);default:var f;if(Array.isArray(t))for(h(4,f=t.length),r=0;r>5!==e)throw"Invalid indefinite length element";return n}function g(e,t){for(var n=0;n>10),e.push(56320|1023&r))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof o&&(o=function(){return n});var v=function e(){var i,h,v=l(),m=v>>5,b=31&v;if(7===m)switch(b){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),n=p(),i=32768&n,o=31744&n,s=1023&n;if(31744===o)o=261120;else if(0!==o)o+=114688;else if(0!==s)return s*r;return t.setUint32(0,i<<16|o<<13|s<<13),t.getFloat32(0)}();case 26:return u(s.getFloat32(a),4);case 27:return u(s.getFloat64(a),8)}if((h=d(b))<0&&(m<2||6=0;)O+=h,_.push(c(h));var P=new Uint8Array(O),S=0;for(i=0;i<_.length;++i)P.set(_[i],S),S+=_[i].length;return P}return c(h);case 3:var w=[];if(h<0)for(;(h=y(m))>=0;)g(w,h);else g(w,h);return String.fromCharCode.apply(null,w);case 4:var E;if(h<0)for(E=[];!f();)E.push(e());else for(E=new Array(h),i=0;i0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function s(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function u(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o>2,c=0;c>6),o.push(128|63&a)):a<55296?(o.push(224|a>>12),o.push(128|a>>6&63),o.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++r),a+=65536,o.push(240|a>>18),o.push(128|a>>12&63),o.push(128|a>>6&63),o.push(128|63&a))}return f(3,o.length),p(o);default:var h;if(Array.isArray(t))for(f(4,h=t.length),r=0;r>5!==e)throw"Invalid indefinite length element";return n}function g(e,t){for(var n=0;n>10),e.push(56320|1023&r))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var b=function e(){var o,f,b=l(),v=b>>5,m=31&b;if(7===v)switch(m){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),n=p(),o=32768&n,i=31744&n,a=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==a)return a*r;return t.setUint32(0,o<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return u(a.getFloat32(s),4);case 27:return u(a.getFloat64(s),8)}if((f=d(m))<0&&(v<2||6=0;)S+=f,_.push(c(f));var O=new Uint8Array(S),P=0;for(o=0;o<_.length;++o)O.set(_[o],P),P+=_[o].length;return O}return c(f);case 3:var w=[];if(f<0)for(;(f=y(v))>=0;)g(w,f);else g(w,f);return String.fromCharCode.apply(null,w);case 4:var E;if(f<0)for(E=[];!h();)E.push(e());else for(E=new Array(f),o=0;o=20?this._presenceTimeout=e:(this._presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",this._presenceTimeout)),this.setHeartbeatInterval(this._presenceTimeout/2-1),this},e.prototype.setProxy=function(e){this.proxy=e},e.prototype.getHeartbeatInterval=function(){return this._heartbeatInterval},e.prototype.setHeartbeatInterval=function(e){return this._heartbeatInterval=e,this},e.prototype.getSubscribeTimeout=function(){return this._subscribeRequestTimeout},e.prototype.setSubscribeTimeout=function(e){return this._subscribeRequestTimeout=e,this},e.prototype.getTransactionTimeout=function(){return this._transactionalRequestTimeout},e.prototype.setTransactionTimeout=function(e){return this._transactionalRequestTimeout=e,this},e.prototype.isSendBeaconEnabled=function(){return this._useSendBeacon},e.prototype.setSendBeaconConfig=function(e){return this._useSendBeacon=e,this},e.prototype.getVersion=function(){return"7.2.3"},e.prototype.setRetryConfiguration=function(e){if(e.minimumdelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(e.maximumDelay>150)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(e.maximumDelay&&maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6");if(e.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10");this.retryConfiguration=e},e.prototype._addPnsdkSuffix=function(e,t){this._PNSDKSuffix[e]=t},e.prototype._getPnsdkSuffix=function(e){var t=this;return Object.keys(this._PNSDKSuffix).reduce((function(n,r){return n+e+t._PNSDKSuffix[r]}),"")},e}();function g(e){var t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),r=new ArrayBuffer(n),i=new Uint8Array(r),o=0;function s(){var e=t.charAt(o++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error("Illegal character at ".concat(o,": ").concat(t.charAt(o-1)));return n}for(var a=0;a>4,f=(15&c)<<4|l>>2,d=(3&l)<<6|p>>0;i[a]=h,64!=l&&(i[a+1]=f),64!=p&&(i[a+2]=d)}return r}var v,m,b,_,O,P=P||function(e,t){var n={},r=n.lib={},i=function(){},o=r.Base={extend:function(e){i.prototype=this;var t=new i;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var i=0;i>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(65535>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},p=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,i=e.min(4*t,i),t){for(var u=0;uc;){var l;e:{l=u;for(var p=e.sqrt(l),h=2;h<=p;h++)if(!(l%h)){l=!1;break e}l=!0}l&&(8>c&&(o[c]=a(e.pow(u,.5))),s[c]=a(e.pow(u,1/3)),c++),u++}var f=[];i=i.SHA256=r.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],a=n[3],u=n[4],c=n[5],l=n[6],p=n[7],h=0;64>h;h++){if(16>h)f[h]=0|e[t+h];else{var d=f[h-15],y=f[h-2];f[h]=((d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3)+f[h-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+f[h-16]}d=p+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&l)+s[h]+f[h],y=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),p=l,l=c,c=u,u=a+d|0,a=o,o=i,i=r,r=d+y|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+a|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+l|0,n[7]=n[7]+p|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=r._createHelper(i),t.HmacSHA256=r._createHmacHelper(i)}(Math),m=(v=P).enc.Utf8,v.algo.HMAC=v.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var n=e.blockSize,r=4*n;t.sigBytes>r&&(t=e.finalize(t)),t.clamp();for(var i=this._oKey=t.clone(),o=this._iKey=t.clone(),s=i.words,a=o.words,u=0;u>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=r.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(r=n.charAt(64))&&-1!=(r=e.indexOf(r))&&(t=r);for(var r=[],i=0,o=0;o>>6-o%4*2;r[i>>>2]|=(s|a)<<24-i%4*8,i++}return _.create(r,i)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,r,i,o,s){return((e=e+(t&n|~t&r)+i+s)<>>32-o)+t}function n(e,t,n,r,i,o,s){return((e=e+(t&r|n&~r)+i+s)<>>32-o)+t}function r(e,t,n,r,i,o,s){return((e=e+(t^n^r)+i+s)<>>32-o)+t}function i(e,t,n,r,i,o,s){return((e=e+(n^(t|~r))+i+s)<>>32-o)+t}for(var o=P,s=(u=o.lib).WordArray,a=u.Hasher,u=o.algo,c=[],l=0;64>l;l++)c[l]=4294967296*e.abs(e.sin(l+1))|0;u=u.MD5=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,o){for(var s=0;16>s;s++){var a=e[u=o+s];e[u]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}s=this._hash.words;var u=e[o+0],l=(a=e[o+1],e[o+2]),p=e[o+3],h=e[o+4],f=e[o+5],d=e[o+6],y=e[o+7],g=e[o+8],v=e[o+9],m=e[o+10],b=e[o+11],_=e[o+12],O=e[o+13],P=e[o+14],S=e[o+15],w=t(w=s[0],k=s[1],T=s[2],E=s[3],u,7,c[0]),E=t(E,w,k,T,a,12,c[1]),T=t(T,E,w,k,l,17,c[2]),k=t(k,T,E,w,p,22,c[3]);w=t(w,k,T,E,h,7,c[4]),E=t(E,w,k,T,f,12,c[5]),T=t(T,E,w,k,d,17,c[6]),k=t(k,T,E,w,y,22,c[7]),w=t(w,k,T,E,g,7,c[8]),E=t(E,w,k,T,v,12,c[9]),T=t(T,E,w,k,m,17,c[10]),k=t(k,T,E,w,b,22,c[11]),w=t(w,k,T,E,_,7,c[12]),E=t(E,w,k,T,O,12,c[13]),T=t(T,E,w,k,P,17,c[14]),w=n(w,k=t(k,T,E,w,S,22,c[15]),T,E,a,5,c[16]),E=n(E,w,k,T,d,9,c[17]),T=n(T,E,w,k,b,14,c[18]),k=n(k,T,E,w,u,20,c[19]),w=n(w,k,T,E,f,5,c[20]),E=n(E,w,k,T,m,9,c[21]),T=n(T,E,w,k,S,14,c[22]),k=n(k,T,E,w,h,20,c[23]),w=n(w,k,T,E,v,5,c[24]),E=n(E,w,k,T,P,9,c[25]),T=n(T,E,w,k,p,14,c[26]),k=n(k,T,E,w,g,20,c[27]),w=n(w,k,T,E,O,5,c[28]),E=n(E,w,k,T,l,9,c[29]),T=n(T,E,w,k,y,14,c[30]),w=r(w,k=n(k,T,E,w,_,20,c[31]),T,E,f,4,c[32]),E=r(E,w,k,T,g,11,c[33]),T=r(T,E,w,k,b,16,c[34]),k=r(k,T,E,w,P,23,c[35]),w=r(w,k,T,E,a,4,c[36]),E=r(E,w,k,T,h,11,c[37]),T=r(T,E,w,k,y,16,c[38]),k=r(k,T,E,w,m,23,c[39]),w=r(w,k,T,E,O,4,c[40]),E=r(E,w,k,T,u,11,c[41]),T=r(T,E,w,k,p,16,c[42]),k=r(k,T,E,w,d,23,c[43]),w=r(w,k,T,E,v,4,c[44]),E=r(E,w,k,T,_,11,c[45]),T=r(T,E,w,k,S,16,c[46]),w=i(w,k=r(k,T,E,w,l,23,c[47]),T,E,u,6,c[48]),E=i(E,w,k,T,y,10,c[49]),T=i(T,E,w,k,P,15,c[50]),k=i(k,T,E,w,f,21,c[51]),w=i(w,k,T,E,_,6,c[52]),E=i(E,w,k,T,p,10,c[53]),T=i(T,E,w,k,m,15,c[54]),k=i(k,T,E,w,a,21,c[55]),w=i(w,k,T,E,g,6,c[56]),E=i(E,w,k,T,S,10,c[57]),T=i(T,E,w,k,d,15,c[58]),k=i(k,T,E,w,O,21,c[59]),w=i(w,k,T,E,h,6,c[60]),E=i(E,w,k,T,b,10,c[61]),T=i(T,E,w,k,l,15,c[62]),k=i(k,T,E,w,v,21,c[63]);s[0]=s[0]+w|0,s[1]=s[1]+k|0,s[2]=s[2]+T|0,s[3]=s[3]+E|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;n[i>>>5]|=128<<24-i%32;var o=e.floor(r/4294967296);for(n[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),n[14+(i+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,r=0;4>r;r++)i=n[r],n[r]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),o.MD5=a._createHelper(u),o.HmacMD5=a._createHmacHelper(u)}(Math),function(){var e,t=P,n=(e=t.lib).Base,r=e.WordArray,i=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(a=this.cfg).hasher.create(),i=r.create(),o=i.words,s=a.keySize,a=a.iterations;o.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:u,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var p=t.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(u=(f.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?r.create([1398893684,1701076831]).concat(e).concat(t):t).toString(o)},parse:function(e){var t=(e=o.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=r.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return p.create({ciphertext:e,salt:n})}},t.SerializableCipher=n.extend({cfg:n.extend({format:u}),encrypt:function(e,t,n,r){r=this.cfg.extend(r);var i=e.createEncryptor(n,r);return t=i.finalize(t),i=i.cfg,p.create({ciphertext:t,key:n,iv:i.iv,algorithm:e,mode:i.mode,padding:i.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(n,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),f=(f.kdf={}).OpenSSL={execute:function(e,t,n,i){return i||(i=r.random(8)),e=s.create({keySize:t+n}).compute(e,i),n=r.create(e.words.slice(t),4*n),e.sigBytes=4*t,p.create({key:e,iv:n,salt:i})}},d=t.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:f}),encrypt:function(e,t,n,r){return n=(r=this.cfg.extend(r)).kdf.execute(n,e.keySize,e.ivSize),r.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,r)).mixIn(n),e},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),n=r.kdf.execute(n,e.keySize,e.ivSize,t.salt),r.iv=n.iv,h.decrypt.call(this,e,t,n.key,r)}})}(),function(){for(var e=P,t=e.lib.BlockCipher,n=e.algo,r=[],i=[],o=[],s=[],a=[],u=[],c=[],l=[],p=[],h=[],f=[],d=0;256>d;d++)f[d]=128>d?d<<1:d<<1^283;var y=0,g=0;for(d=0;256>d;d++){var v=(v=g^g<<1^g<<2^g<<3^g<<4)>>>8^255&v^99;r[y]=v,i[v]=y;var m=f[y],b=f[m],_=f[b],O=257*f[v]^16843008*v;o[y]=O<<24|O>>>8,s[y]=O<<16|O>>>16,a[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*b^257*m^16843008*y,c[v]=O<<24|O>>>8,l[v]=O<<16|O>>>16,p[v]=O<<8|O>>>24,h[v]=O,y?(y=m^f[f[f[_^m]]],g^=f[f[g]]):y=g=1}var S=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),i=this._keySchedule=[],o=0;o>>24]<<24|r[s>>>16&255]<<16|r[s>>>8&255]<<8|r[255&s]):(s=r[(s=s<<8|s>>>24)>>>24]<<24|r[s>>>16&255]<<16|r[s>>>8&255]<<8|r[255&s],s^=S[o/t|0]<<24),i[o]=i[o-t]^s}for(e=this._invKeySchedule=[],t=0;tt||4>=o?s:c[r[s>>>24]]^l[r[s>>>16&255]]^p[r[s>>>8&255]]^h[r[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,o,s,a,u,r)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,c,l,p,h,i),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,i,o,s,a){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],p=e[t+2]^n[2],h=e[t+3]^n[3],f=4,d=1;d>>24]^i[l>>>16&255]^o[p>>>8&255]^s[255&h]^n[f++],g=r[l>>>24]^i[p>>>16&255]^o[h>>>8&255]^s[255&c]^n[f++],v=r[p>>>24]^i[h>>>16&255]^o[c>>>8&255]^s[255&l]^n[f++];h=r[h>>>24]^i[c>>>16&255]^o[l>>>8&255]^s[255&p]^n[f++],c=y,l=g,p=v}y=(a[c>>>24]<<24|a[l>>>16&255]<<16|a[p>>>8&255]<<8|a[255&h])^n[f++],g=(a[l>>>24]<<24|a[p>>>16&255]<<16|a[h>>>8&255]<<8|a[255&c])^n[f++],v=(a[p>>>24]<<24|a[h>>>16&255]<<16|a[c>>>8&255]<<8|a[255&l])^n[f++],h=(a[h>>>24]<<24|a[c>>>16&255]<<16|a[l>>>8&255]<<8|a[255&p])^n[f++],e[t]=y,e[t+1]=g,e[t+2]=v,e[t+3]=h},keySize:8});e.AES=t._createHelper(n)}(),P.mode.ECB=((O=P.lib.BlockCipherMode.extend()).Encryptor=O.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),O.Decryptor=O.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),O);var S=P;function w(e){var t,n=[];for(t=0;t=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))},e.prototype.clearHistory=function(){this.hashHistory=[]},e}();function C(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function N(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var A={signPamFromParams:function(e){return N(e).map((function(t){return"".concat(t,"=").concat(C(e[t]))})).join("&")},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e,t;return{promise:new Promise((function(n,r){e=n,t=r})),reject:t,fulfill:e}},encodeString:C},R={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory",PNDisconnectedCategory:"PNDisconnectedCategory",PNConnectionErrorCategory:"PNConnectionErrorCategory",PNDisconnectedUnexpectedlyCategory:"PNDisconnectedUnexpectedlyCategory"},M=function(){function e(e){var t=e.subscribeEndpoint,n=e.leaveEndpoint,r=e.heartbeatEndpoint,i=e.setStateEndpoint,o=e.timeEndpoint,s=e.getFileUrl,a=e.config,u=e.crypto,c=e.listenerManager;this._listenerManager=c,this._config=a,this._leaveEndpoint=n,this._heartbeatEndpoint=r,this._setStateEndpoint=i,this._subscribeEndpoint=t,this._getFileUrl=s,this._crypto=u,this._channels={},this._presenceChannels={},this._heartbeatChannels={},this._heartbeatChannelGroups={},this._channelGroups={},this._presenceChannelGroups={},this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[],this._currentTimetoken=0,this._lastTimetoken=0,this._storedTimetoken=null,this._subscriptionStatusAnnounced=!1,this._isOnline=!0,this._reconnectionManager=new T({timeEndpoint:o}),this._dedupingManager=new k({config:a})}return e.prototype.adaptStateChange=function(e,t){var n=this,r=e.state,i=e.channels,o=void 0===i?[]:i,s=e.channelGroups,a=void 0===s?[]:s,u=e.withHeartbeat,c=void 0!==u&&u;if(o.forEach((function(e){e in n._channels&&(n._channels[e].state=r)})),a.forEach((function(e){e in n._channelGroups&&(n._channelGroups[e].state=r)})),c){var l={};return o.forEach((function(e){return l[e]=r})),a.forEach((function(e){return l[e]=r})),this._heartbeatEndpoint({channels:o,channelGroups:a,state:l},t)}return this._setStateEndpoint({state:r,channels:o,channelGroups:a},t)},e.prototype.adaptPresenceChange=function(e){var t=this,n=e.connected,r=e.channels,i=void 0===r?[]:r,o=e.channelGroups,s=void 0===o?[]:o;n?(i.forEach((function(e){t._heartbeatChannels[e]={state:{}}})),s.forEach((function(e){t._heartbeatChannelGroups[e]={state:{}}}))):(i.forEach((function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]})),s.forEach((function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]})),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:i,channelGroups:s},(function(e){t._listenerManager.announceStatus(e)}))),this.reconnect()},e.prototype.adaptSubscribeChange=function(e){var t=this,n=e.timetoken,r=e.channels,i=void 0===r?[]:r,o=e.channelGroups,s=void 0===o?[]:o,a=e.withPresence,u=void 0!==a&&a,c=e.withHeartbeats,l=void 0!==c&&c;this._config.subscribeKey&&""!==this._config.subscribeKey?(n&&(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=n),"0"!==this._currentTimetoken&&0!==this._currentTimetoken&&(this._storedTimetoken=this._currentTimetoken,this._currentTimetoken=0),i.forEach((function(e){t._channels[e]={state:{}},u&&(t._presenceChannels[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannels[e]={}),t._pendingChannelSubscriptions.push(e)})),s.forEach((function(e){t._channelGroups[e]={state:{}},u&&(t._presenceChannelGroups[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannelGroups[e]={}),t._pendingChannelGroupSubscriptions.push(e)})),this._subscriptionStatusAnnounced=!1,this.reconnect()):console&&console.log&&console.log("subscribe key missing; aborting subscribe")},e.prototype.adaptUnsubscribeChange=function(e,t){var n=this,r=e.channels,i=void 0===r?[]:r,o=e.channelGroups,s=void 0===o?[]:o,a=[],u=[];i.forEach((function(e){e in n._channels&&(delete n._channels[e],a.push(e),e in n._heartbeatChannels&&delete n._heartbeatChannels[e]),e in n._presenceChannels&&(delete n._presenceChannels[e],a.push(e))})),s.forEach((function(e){e in n._channelGroups&&(delete n._channelGroups[e],u.push(e),e in n._heartbeatChannelGroups&&delete n._heartbeatChannelGroups[e]),e in n._presenceChannelGroups&&(delete n._presenceChannelGroups[e],u.push(e))})),0===a.length&&0===u.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:a,channelGroups:u},(function(e){e.affectedChannels=a,e.affectedChannelGroups=u,e.currentTimetoken=n._currentTimetoken,e.lastTimetoken=n._lastTimetoken,n._listenerManager.announceStatus(e)})),0===Object.keys(this._channels).length&&0===Object.keys(this._presenceChannels).length&&0===Object.keys(this._channelGroups).length&&0===Object.keys(this._presenceChannelGroups).length&&(this._lastTimetoken=0,this._currentTimetoken=0,this._storedTimetoken=null,this._region=null,this._reconnectionManager.stopPolling()),this.reconnect())},e.prototype.unsubscribeAll=function(e){this.adaptUnsubscribeChange({channels:this.getSubscribedChannels(),channelGroups:this.getSubscribedChannelGroups()},e)},e.prototype.getHeartbeatChannels=function(){return Object.keys(this._heartbeatChannels)},e.prototype.getHeartbeatChannelGroups=function(){return Object.keys(this._heartbeatChannelGroups)},e.prototype.getSubscribedChannels=function(){return Object.keys(this._channels)},e.prototype.getSubscribedChannelGroups=function(){return Object.keys(this._channelGroups)},e.prototype.reconnect=function(){this._startSubscribeLoop(),this._registerHeartbeatTimer()},e.prototype.disconnect=function(){this._stopSubscribeLoop(),this._stopHeartbeatTimer(),this._reconnectionManager.stopPolling()},e.prototype._registerHeartbeatTimer=function(){this._stopHeartbeatTimer(),0!==this._config.getHeartbeatInterval()&&void 0!==this._config.getHeartbeatInterval()&&(this._performHeartbeatLoop(),this._heartbeatTimer=setInterval(this._performHeartbeatLoop.bind(this),1e3*this._config.getHeartbeatInterval()))},e.prototype._stopHeartbeatTimer=function(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null)},e.prototype._performHeartbeatLoop=function(){var e=this,t=this.getHeartbeatChannels(),n=this.getHeartbeatChannelGroups(),r={};if(0!==t.length||0!==n.length){this.getSubscribedChannels().forEach((function(t){var n=e._channels[t].state;Object.keys(n).length&&(r[t]=n)})),this.getSubscribedChannelGroups().forEach((function(t){var n=e._channelGroups[t].state;Object.keys(n).length&&(r[t]=n)}));this._heartbeatEndpoint({channels:t,channelGroups:n,state:r},function(t){t.error&&e._config.announceFailedHeartbeats&&e._listenerManager.announceStatus(t),t.error&&e._config.autoNetworkDetection&&e._isOnline&&(e._isOnline=!1,e.disconnect(),e._listenerManager.announceNetworkDown(),e.reconnect()),!t.error&&e._config.announceSuccessfulHeartbeats&&e._listenerManager.announceStatus(t)}.bind(this))}},e.prototype._startSubscribeLoop=function(){var e=this;this._stopSubscribeLoop();var t={},n=[],r=[];if(Object.keys(this._channels).forEach((function(r){var i=e._channels[r].state;Object.keys(i).length&&(t[r]=i),n.push(r)})),Object.keys(this._presenceChannels).forEach((function(e){n.push("".concat(e,"-pnpres"))})),Object.keys(this._channelGroups).forEach((function(n){var i=e._channelGroups[n].state;Object.keys(i).length&&(t[n]=i),r.push(n)})),Object.keys(this._presenceChannelGroups).forEach((function(e){r.push("".concat(e,"-pnpres"))})),0!==n.length||0!==r.length){var i={channels:n,channelGroups:r,state:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(i,this._processSubscribeResponse.bind(this))}},e.prototype._processSubscribeResponse=function(e,t){var i=this;if(e.error){if(e.errorData&&"Aborted"===e.errorData.message)return;e.category===R.PNTimeoutCategory?this._startSubscribeLoop():e.category===R.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection((function(){i._config.autoNetworkDetection&&!i._isOnline&&(i._isOnline=!0,i._listenerManager.announceNetworkUp()),i.reconnect(),i._subscriptionStatusAnnounced=!0;var t={category:R.PNReconnectedCategory,operation:e.operation,lastTimetoken:i._lastTimetoken,currentTimetoken:i._currentTimetoken};i._listenerManager.announceStatus(t)})),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===R.PNBadRequestCategory?(this._stopHeartbeatTimer(),this._listenerManager.announceStatus(e)):this._listenerManager.announceStatus(e)}else{if(this._storedTimetoken?(this._currentTimetoken=this._storedTimetoken,this._storedTimetoken=null):(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=t.metadata.timetoken),!this._subscriptionStatusAnnounced){var o={};o.category=R.PNConnectedCategory,o.operation=e.operation,o.affectedChannels=this._pendingChannelSubscriptions,o.subscribedChannels=this.getSubscribedChannels(),o.affectedChannelGroups=this._pendingChannelGroupSubscriptions,o.lastTimetoken=this._lastTimetoken,o.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(o),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var s=t.messages||[],a=this._config,u=a.requestMessageCountThreshold,c=a.dedupeOnSubscribe;if(u&&s.length>=u){var l={};l.category=R.PNRequestMessageCountExceededCategory,l.operation=e.operation,this._listenerManager.announceStatus(l)}s.forEach((function(e){var t=e.channel,o=e.subscriptionMatch,s=e.publishMetaData;if(t===o&&(o=null),c){if(i._dedupingManager.isDuplicate(e))return;i._dedupingManager.addEntry(e)}if(A.endsWith(e.channel,"-pnpres"))(y={channel:null,subscription:null}).actualChannel=null!=o?t:null,y.subscribedChannel=null!=o?o:t,t&&(y.channel=t.substring(0,t.lastIndexOf("-pnpres"))),o&&(y.subscription=o.substring(0,o.lastIndexOf("-pnpres"))),y.action=e.payload.action,y.state=e.payload.data,y.timetoken=s.publishTimetoken,y.occupancy=e.payload.occupancy,y.uuid=e.payload.uuid,y.timestamp=e.payload.timestamp,e.payload.join&&(y.join=e.payload.join),e.payload.leave&&(y.leave=e.payload.leave),e.payload.timeout&&(y.timeout=e.payload.timeout),i._listenerManager.announcePresence(y);else if(1===e.messageType){(y={channel:null,subscription:null}).channel=t,y.subscription=o,y.timetoken=s.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),y.message=e.payload,i._listenerManager.announceSignal(y)}else if(2===e.messageType){if((y={channel:null,subscription:null}).channel=t,y.subscription=o,y.timetoken=s.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),y.message={event:e.payload.event,type:e.payload.type,data:e.payload.data},i._listenerManager.announceObjects(y),"uuid"===e.payload.type){var a=i._renameChannelField(y);i._listenerManager.announceUser(n(n({},a),{message:n(n({},a.message),{event:i._renameEvent(a.message.event),type:"user"})}))}else if("channel"===e.payload.type){a=i._renameChannelField(y);i._listenerManager.announceSpace(n(n({},a),{message:n(n({},a.message),{event:i._renameEvent(a.message.event),type:"space"})}))}else if("membership"===e.payload.type){var u=(a=i._renameChannelField(y)).message.data,l=u.uuid,p=u.channel,h=r(u,["uuid","channel"]);h.user=l,h.space=p,i._listenerManager.announceMembership(n(n({},a),{message:n(n({},a.message),{event:i._renameEvent(a.message.event),data:h})}))}}else if(3===e.messageType){(y={}).channel=t,y.subscription=o,y.timetoken=s.publishTimetoken,y.publisher=e.issuingClientId,y.data={messageTimetoken:e.payload.data.messageTimetoken,actionTimetoken:e.payload.data.actionTimetoken,type:e.payload.data.type,uuid:e.issuingClientId,value:e.payload.data.value},y.event=e.payload.event,i._listenerManager.announceMessageAction(y)}else if(4===e.messageType){(y={}).channel=t,y.subscription=o,y.timetoken=s.publishTimetoken,y.publisher=e.issuingClientId;var f=e.payload;if(i._config.cipherKey){var d=i._crypto.decrypt(e.payload);"object"==typeof d&&null!==d&&(f=d)}e.userMetadata&&(y.userMetadata=e.userMetadata),y.message=f.message,y.file={id:f.file.id,name:f.file.name,url:i._getFileUrl({id:f.file.id,name:f.file.name,channel:t})},i._listenerManager.announceFile(y)}else{var y;(y={channel:null,subscription:null}).actualChannel=null!=o?t:null,y.subscribedChannel=null!=o?o:t,y.channel=t,y.subscription=o,y.timetoken=s.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),i._config.cipherKey?y.message=i._crypto.decrypt(e.payload):y.message=e.payload,i._listenerManager.announceMessage(y)}})),this._region=t.metadata.region,this._startSubscribeLoop()}},e.prototype._stopSubscribeLoop=function(){this._subscribeCall&&("function"==typeof this._subscribeCall.abort&&this._subscribeCall.abort(),this._subscribeCall=null)},e.prototype._renameEvent=function(e){return"set"===e?"updated":"removed"},e.prototype._renameChannelField=function(e){var t=e.channel,n=r(e,["channel"]);return n.spaceId=t,n},e}(),j={PNTimeOperation:"PNTimeOperation",PNHistoryOperation:"PNHistoryOperation",PNDeleteMessagesOperation:"PNDeleteMessagesOperation",PNFetchMessagesOperation:"PNFetchMessagesOperation",PNMessageCounts:"PNMessageCountsOperation",PNSubscribeOperation:"PNSubscribeOperation",PNUnsubscribeOperation:"PNUnsubscribeOperation",PNPublishOperation:"PNPublishOperation",PNSignalOperation:"PNSignalOperation",PNAddMessageActionOperation:"PNAddActionOperation",PNRemoveMessageActionOperation:"PNRemoveMessageActionOperation",PNGetMessageActionsOperation:"PNGetMessageActionsOperation",PNCreateUserOperation:"PNCreateUserOperation",PNUpdateUserOperation:"PNUpdateUserOperation",PNDeleteUserOperation:"PNDeleteUserOperation",PNGetUserOperation:"PNGetUsersOperation",PNGetUsersOperation:"PNGetUsersOperation",PNCreateSpaceOperation:"PNCreateSpaceOperation",PNUpdateSpaceOperation:"PNUpdateSpaceOperation",PNDeleteSpaceOperation:"PNDeleteSpaceOperation",PNGetSpaceOperation:"PNGetSpacesOperation",PNGetSpacesOperation:"PNGetSpacesOperation",PNGetMembersOperation:"PNGetMembersOperation",PNUpdateMembersOperation:"PNUpdateMembersOperation",PNGetMembershipsOperation:"PNGetMembershipsOperation",PNUpdateMembershipsOperation:"PNUpdateMembershipsOperation",PNListFilesOperation:"PNListFilesOperation",PNGenerateUploadUrlOperation:"PNGenerateUploadUrlOperation",PNPublishFileOperation:"PNPublishFileOperation",PNGetFileUrlOperation:"PNGetFileUrlOperation",PNDownloadFileOperation:"PNDownloadFileOperation",PNGetAllUUIDMetadataOperation:"PNGetAllUUIDMetadataOperation",PNGetUUIDMetadataOperation:"PNGetUUIDMetadataOperation",PNSetUUIDMetadataOperation:"PNSetUUIDMetadataOperation",PNRemoveUUIDMetadataOperation:"PNRemoveUUIDMetadataOperation",PNGetAllChannelMetadataOperation:"PNGetAllChannelMetadataOperation",PNGetChannelMetadataOperation:"PNGetChannelMetadataOperation",PNSetChannelMetadataOperation:"PNSetChannelMetadataOperation",PNRemoveChannelMetadataOperation:"PNRemoveChannelMetadataOperation",PNSetMembersOperation:"PNSetMembersOperation",PNSetMembershipsOperation:"PNSetMembershipsOperation",PNPushNotificationEnabledChannelsOperation:"PNPushNotificationEnabledChannelsOperation",PNRemoveAllPushNotificationsOperation:"PNRemoveAllPushNotificationsOperation",PNWhereNowOperation:"PNWhereNowOperation",PNSetStateOperation:"PNSetStateOperation",PNHereNowOperation:"PNHereNowOperation",PNGetStateOperation:"PNGetStateOperation",PNHeartbeatOperation:"PNHeartbeatOperation",PNChannelGroupsOperation:"PNChannelGroupsOperation",PNRemoveGroupOperation:"PNRemoveGroupOperation",PNChannelsForGroupOperation:"PNChannelsForGroupOperation",PNAddChannelsToGroupOperation:"PNAddChannelsToGroupOperation",PNRemoveChannelsFromGroupOperation:"PNRemoveChannelsFromGroupOperation",PNAccessManagerGrant:"PNAccessManagerGrant",PNAccessManagerGrantToken:"PNAccessManagerGrantToken",PNAccessManagerAudit:"PNAccessManagerAudit",PNAccessManagerRevokeToken:"PNAccessManagerRevokeToken",PNHandshakeOperation:"PNHandshakeOperation",PNReceiveMessagesOperation:"PNReceiveMessagesOperation"},U=function(){function e(e){this._maximumSamplesCount=100,this._trackedLatencies={},this._latencies={},this._maximumSamplesCount=e.maximumSamplesCount||this._maximumSamplesCount}return e.prototype.operationsLatencyForRequest=function(){var e=this,t={};return Object.keys(this._latencies).forEach((function(n){var r=e._latencies[n],i=e._averageLatency(r);i>0&&(t["l_".concat(n)]=i)})),t},e.prototype.startLatencyMeasure=function(e,t){e!==j.PNSubscribeOperation&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(e!==j.PNSubscribeOperation&&t){var n=this._endpointName(e),r=this._latencies[n],i=this._trackedLatencies[t];r||(this._latencies[n]=[],r=this._latencies[n]),r.push(Date.now()-i),r.length>this._maximumSamplesCount&&r.splice(0,r.length-this._maximumSamplesCount),delete this._trackedLatencies[t]}},e.prototype._averageLatency=function(e){return Math.floor(e.reduce((function(e,t){return e+t}),0)/e.length)},e.prototype._endpointName=function(e){var t=null;switch(e){case j.PNPublishOperation:t="pub";break;case j.PNSignalOperation:t="sig";break;case j.PNHistoryOperation:case j.PNFetchMessagesOperation:case j.PNDeleteMessagesOperation:case j.PNMessageCounts:t="hist";break;case j.PNUnsubscribeOperation:case j.PNWhereNowOperation:case j.PNHereNowOperation:case j.PNHeartbeatOperation:case j.PNSetStateOperation:case j.PNGetStateOperation:t="pres";break;case j.PNAddChannelsToGroupOperation:case j.PNRemoveChannelsFromGroupOperation:case j.PNChannelGroupsOperation:case j.PNRemoveGroupOperation:case j.PNChannelsForGroupOperation:t="cg";break;case j.PNPushNotificationEnabledChannelsOperation:case j.PNRemoveAllPushNotificationsOperation:t="push";break;case j.PNCreateUserOperation:case j.PNUpdateUserOperation:case j.PNDeleteUserOperation:case j.PNGetUserOperation:case j.PNGetUsersOperation:case j.PNCreateSpaceOperation:case j.PNUpdateSpaceOperation:case j.PNDeleteSpaceOperation:case j.PNGetSpaceOperation:case j.PNGetSpacesOperation:case j.PNGetMembersOperation:case j.PNUpdateMembersOperation:case j.PNGetMembershipsOperation:case j.PNUpdateMembershipsOperation:t="obj";break;case j.PNAddMessageActionOperation:case j.PNRemoveMessageActionOperation:case j.PNGetMessageActionsOperation:t="msga";break;case j.PNAccessManagerGrant:case j.PNAccessManagerAudit:t="pam";break;case j.PNAccessManagerGrantToken:case j.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),x=function(){function e(e,t,n){this._payload=e,this._setDefaultPayloadStructure(),this.title=t,this.body=n}return Object.defineProperty(e.prototype,"payload",{get:function(){return this._payload},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{set:function(e){this._title=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{set:function(e){this._subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{set:function(e){this._body=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{set:function(e){this._badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{set:function(e){this._sound=e},enumerable:!1,configurable:!0}),e.prototype._setDefaultPayloadStructure=function(){},e.prototype.toObject=function(){return{}},e}(),D=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"configurations",{set:function(e){e&&e.length&&(this._configurations=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"notification",{get:function(){return this._payload.aps},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.aps.alert.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){e&&e.length&&(this._payload.aps.alert.subtitle=e,this._subtitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.aps.alert.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this._badge},set:function(e){null!=e&&(this._payload.aps.badge=e,this._badge=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.aps.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),r.prototype._setDefaultPayloadStructure=function(){this._payload.aps={alert:{}}},r.prototype.toObject=function(){var e=this,t=n({},this._payload),r=t.aps,i=r.alert;if(this._isSilent&&(r["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");var o=[];this._configurations.forEach((function(t){o.push(e._objectFromAPNS2Configuration(t))})),o.length&&(t.pn_push=o)}return i&&Object.keys(i).length||delete r.alert,this._isSilent&&(delete r.alert,delete r.badge,delete r.sound,i={}),this._isSilent||Object.keys(i).length?t:null},r.prototype._objectFromAPNS2Configuration=function(e){var t=this;if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");var n=[];e.targets.forEach((function(e){n.push(t._objectFromAPNSTarget(e))}));var r=e.collapseId,i=e.expirationDate,o={auth_method:"token",targets:n,version:"v2"};return r&&r.length&&(o.collapse_id=r),i&&(o.expiration=i.toISOString()),o},r.prototype._objectFromAPNSTarget=function(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");var t=e.topic,n=e.environment,r=void 0===n?"development":n,i=e.excludedDevices,o=void 0===i?[]:i,s={topic:t,environment:r};return o.length&&(s.excluded_devices=o),s},r}(x),I=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"backContent",{get:function(){return this._backContent},set:function(e){e&&e.length&&(this._payload.back_content=e,this._backContent=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"backTitle",{get:function(){return this._backTitle},set:function(e){e&&e.length&&(this._payload.back_title=e,this._backTitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},set:function(e){null!=e&&(this._payload.count=e,this._count=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"type",{get:function(){return this._type},set:function(e){e&&e.length&&(this._payload.type=e,this._type=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this.backTitle},set:function(e){this.backTitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this.backContent},set:function(e){this.backContent=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this.count},set:function(e){this.count=e},enumerable:!1,configurable:!0}),r.prototype.toObject=function(){return Object.keys(this._payload).length?n({},this._payload):null},r}(x),G=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),Object.defineProperty(i.prototype,"notification",{get:function(){return this._payload.notification},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"data",{get:function(){return this._payload.data},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.notification.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.notification.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.notification.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"icon",{get:function(){return this._icon},set:function(e){e&&e.length&&(this._payload.notification.icon=e,this._icon=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"tag",{get:function(){return this._tag},set:function(e){e&&e.length&&(this._payload.notification.tag=e,this._tag=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),i.prototype._setDefaultPayloadStructure=function(){this._payload.notification={},this._payload.data={}},i.prototype.toObject=function(){var e=n({},this._payload.data),t=null,i={};if(Object.keys(this._payload).length>2){var o=this._payload;o.notification,o.data;var s=r(o,["notification","data"]);e=n(n({},e),s)}return this._isSilent?e.notification=this._payload.notification:t=this._payload.notification,Object.keys(e).length&&(i.data=e),t&&Object.keys(t).length&&(i.notification=t),Object.keys(i).length?i:null},i}(x),K=function(){function e(e,t){this._payload={apns:{},mpns:{},fcm:{}},this._title=e,this._body=t,this.apns=new D(this._payload.apns,e,t),this.mpns=new I(this._payload.mpns,e,t),this.fcm=new G(this._payload.fcm,e,t)}return Object.defineProperty(e.prototype,"debugging",{set:function(e){this._debugging=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{get:function(){return this._title},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{get:function(){return this._body},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){this._subtitle=e,this.apns.subtitle=e,this.mpns.subtitle=e,this.fcm.subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{get:function(){return this._badge},set:function(e){this._badge=e,this.apns.badge=e,this.mpns.badge=e,this.fcm.badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{get:function(){return this._sound},set:function(e){this._sound=e,this.apns.sound=e,this.mpns.sound=e,this.fcm.sound=e},enumerable:!1,configurable:!0}),e.prototype.buildPayload=function(e){var t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";var n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("mpns")){var r=this.mpns.toObject();r&&Object.keys(r).length&&(t.pn_mpns=r)}if(e.includes("fcm")){var i=this.fcm.toObject();i&&Object.keys(i).length&&(t.pn_gcm=i)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t},e}(),F=function(){function e(){this._listeners=[]}return e.prototype.addListener=function(e){this._listeners.push(e)},e.prototype.removeListener=function(e){var t=[];this._listeners.forEach((function(n){n!==e&&t.push(n)})),this._listeners=t},e.prototype.removeAllListeners=function(){this._listeners=[]},e.prototype.announcePresence=function(e){this._listeners.forEach((function(t){t.presence&&t.presence(e)}))},e.prototype.announceStatus=function(e){this._listeners.forEach((function(t){t.status&&t.status(e)}))},e.prototype.announceMessage=function(e){this._listeners.forEach((function(t){t.message&&t.message(e)}))},e.prototype.announceSignal=function(e){this._listeners.forEach((function(t){t.signal&&t.signal(e)}))},e.prototype.announceMessageAction=function(e){this._listeners.forEach((function(t){t.messageAction&&t.messageAction(e)}))},e.prototype.announceFile=function(e){this._listeners.forEach((function(t){t.file&&t.file(e)}))},e.prototype.announceObjects=function(e){this._listeners.forEach((function(t){t.objects&&t.objects(e)}))},e.prototype.announceUser=function(e){this._listeners.forEach((function(t){t.user&&t.user(e)}))},e.prototype.announceSpace=function(e){this._listeners.forEach((function(t){t.space&&t.space(e)}))},e.prototype.announceMembership=function(e){this._listeners.forEach((function(t){t.membership&&t.membership(e)}))},e.prototype.announceNetworkUp=function(){var e={};e.category=R.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=R.PNNetworkDownCategory,this.announceStatus(e)},e}(),L=function(){function e(e,t){this._config=e,this._cbor=t}return e.prototype.setToken=function(e){e&&e.length>0?this._token=e:this._token=void 0},e.prototype.getToken=function(){return this._token},e.prototype.extractPermissions=function(e){var t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128==(128&e)&&(t.join=!0),64==(64&e)&&(t.update=!0),32==(32&e)&&(t.get=!0),8==(8&e)&&(t.delete=!0),4==(4&e)&&(t.manage=!0),2==(2&e)&&(t.write=!0),1==(1&e)&&(t.read=!0),t},e.prototype.parseToken=function(e){var t=this,n=this._cbor.decodeToken(e);if(void 0!==n){var r=n.res.uuid?Object.keys(n.res.uuid):[],i=Object.keys(n.res.chan),o=Object.keys(n.res.grp),s=n.pat.uuid?Object.keys(n.pat.uuid):[],a=Object.keys(n.pat.chan),u=Object.keys(n.pat.grp),c={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid},l=r.length>0,p=i.length>0,h=o.length>0;(l||p||h)&&(c.resources={},l&&(c.resources.uuids={},r.forEach((function(e){c.resources.uuids[e]=t.extractPermissions(n.res.uuid[e])}))),p&&(c.resources.channels={},i.forEach((function(e){c.resources.channels[e]=t.extractPermissions(n.res.chan[e])}))),h&&(c.resources.groups={},o.forEach((function(e){c.resources.groups[e]=t.extractPermissions(n.res.grp[e])}))));var f=s.length>0,d=a.length>0,y=u.length>0;return(f||d||y)&&(c.patterns={},f&&(c.patterns.uuids={},s.forEach((function(e){c.patterns.uuids[e]=t.extractPermissions(n.pat.uuid[e])}))),d&&(c.patterns.channels={},a.forEach((function(e){c.patterns.channels[e]=t.extractPermissions(n.pat.chan[e])}))),y&&(c.patterns.groups={},u.forEach((function(e){c.patterns.groups[e]=t.extractPermissions(n.pat.grp[e])})))),Object.keys(n.meta).length>0&&(c.meta=n.meta),c.signature=n.sig,c}},e}(),B=function(e){function n(t,n){var r=this.constructor,i=e.call(this,t)||this;return i.name=i.constructor.name,i.status=n,i.message=t,Object.setPrototypeOf(i,r.prototype),i}return t(n,e),n}(Error);function H(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}function q(e,t,n){return e.usePost&&e.usePost(t,n)?e.postURL(t,n):e.usePatch&&e.usePatch(t,n)?e.patchURL(t,n):e.useGetFile&&e.useGetFile(t,n)?e.getFileURL(t,n):e.getURL(t,n)}function z(e){if(e.sdkName)return e.sdkName;var t="PubNub-JS-".concat(e.sdkFamily);e.partnerId&&(t+="-".concat(e.partnerId)),t+="/".concat(e.getVersion());var n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}function V(e,t,n){return t.usePost&&t.usePost(e,n)?"POST":t.usePatch&&t.usePatch(e,n)?"PATCH":t.useDelete&&t.useDelete(e,n)?"DELETE":t.useGetFile&&t.useGetFile(e,n)?"GETFILE":"GET"}function J(e,t,n,r,i){var o=e.config,s=e.crypto,a=V(e,i,r);n.timestamp=Math.floor((new Date).getTime()/1e3),"PNPublishOperation"===i.getOperation()&&i.usePost&&i.usePost(e,r)&&(a="GET"),"GETFILE"===a&&(a="GET");var u="".concat(a,"\n").concat(o.publishKey,"\n").concat(t,"\n").concat(A.signPamFromParams(n),"\n");if("POST"===a)u+="string"==typeof(c=i.postPayload(e,r))?c:JSON.stringify(c);else if("PATCH"===a){var c;u+="string"==typeof(c=i.patchPayload(e,r))?c:JSON.stringify(c)}var l="v2.".concat(s.HMACSHA256(u));l=(l=(l=l.replace(/\+/g,"-")).replace(/\//g,"_")).replace(/=+$/,""),n.signature=l}function W(e,t){for(var r=[],i=2;i0?i.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(o),"/leave")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i={};return r.length>0&&(i["channel-group"]=r.join(",")),i},handleResponse:function(){return{}}});var oe=Object.freeze({__proto__:null,getOperation:function(){return j.PNWhereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,i=void 0===r?n.UUID:r;return"/v2/presence/sub-key/".concat(n.subscribeKey,"/uuid/").concat(A.encodeString(i))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return t.payload?{channels:t.payload.channels}:{channels:[]}}});var se=Object.freeze({__proto__:null,getOperation:function(){return j.PNHeartbeatOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,o=i.length>0?i.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(o),"/heartbeat")},isAuthSupported:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i=t.state,o=e.config,s={};return r.length>0&&(s["channel-group"]=r.join(",")),i&&(s.state=JSON.stringify(i)),s.heartbeat=o.getPresenceTimeout(),s},handleResponse:function(){return{}}});var ae=Object.freeze({__proto__:null,getOperation:function(){return j.PNGetStateOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,i=void 0===r?n.UUID:r,o=t.channels,s=void 0===o?[]:o,a=s.length>0?s.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(a),"/uuid/").concat(i)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i={};return r.length>0&&(i["channel-group"]=r.join(",")),i},handleResponse:function(e,t,n){var r=n.channels,i=void 0===r?[]:r,o=n.channelGroups,s=void 0===o?[]:o,a={};return 1===i.length&&0===s.length?a[i[0]]=t.payload:a=t.payload,{channels:a}}});var ue=Object.freeze({__proto__:null,getOperation:function(){return j.PNSetStateOperation},validateParams:function(e,t){var n=e.config,r=t.state,i=t.channels,o=void 0===i?[]:i,s=t.channelGroups,a=void 0===s?[]:s;return r?n.subscribeKey?0===o.length&&0===a.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key":"Missing State"},getURL:function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,o=i.length>0?i.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(o),"/uuid/").concat(A.encodeString(n.UUID),"/data")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.state,r=t.channelGroups,i=void 0===r?[]:r,o={};return o.state=JSON.stringify(n),i.length>0&&(o["channel-group"]=i.join(",")),o},handleResponse:function(e,t){return{state:t.payload}}});var ce=Object.freeze({__proto__:null,getOperation:function(){return j.PNHereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,o=t.channelGroups,s=void 0===o?[]:o,a="/v2/presence/sub-key/".concat(n.subscribeKey);if(i.length>0||s.length>0){var u=i.length>0?i.join(","):",";a+="/channel/".concat(A.encodeString(u))}return a},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var r=t.channelGroups,i=void 0===r?[]:r,o=t.includeUUIDs,s=void 0===o||o,a=t.includeState,u=void 0!==a&&a,c=t.queryParameters,l=void 0===c?{}:c,p={};return s||(p.disable_uuids=1),u&&(p.state=1),i.length>0&&(p["channel-group"]=i.join(",")),p=n(n({},p),l)},handleResponse:function(e,t,n){var r=n.channels,i=void 0===r?[]:r,o=n.channelGroups,s=void 0===o?[]:o,a=n.includeUUIDs,u=void 0===a||a,c=n.includeState,l=void 0!==c&&c;return i.length>1||s.length>0||0===s.length&&0===i.length?function(){var e={};return e.totalChannels=t.payload.total_channels,e.totalOccupancy=t.payload.total_occupancy,e.channels={},Object.keys(t.payload.channels).forEach((function(n){var r=t.payload.channels[n],i=[];return e.channels[n]={occupants:i,name:n,occupancy:r.occupancy},u&&r.uuids.forEach((function(e){l?i.push({state:e.state,uuid:e.uuid}):i.push({state:null,uuid:e})})),e})),e}():function(){var e={},n=[];return e.totalChannels=1,e.totalOccupancy=t.occupancy,e.channels={},e.channels[i[0]]={occupants:n,name:i[0],occupancy:t.occupancy},u&&t.uuids&&t.uuids.forEach((function(e){l?n.push({state:e.state,uuid:e.uuid}):n.push({state:null,uuid:e})})),e}()},handleError:function(e,t,n){402!==n.statusCode||this.getURL(e,t).includes("channel")||(n.errorData.message="You have tried to perform a Global Here Now operation, your keyset configuration does not support that. Please provide a channel, or enable the Global Here Now feature from the Portal.")}});var le=Object.freeze({__proto__:null,getOperation:function(){return j.PNAddMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.action,i=t.channel;return t.messageTimetoken?n.subscribeKey?i?r?r.value?r.type?r.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message channel":"Missing Subscribe Key":"Missing message timetoken"},usePost:function(){return!0},postURL:function(e,t){var n=e.config,r=t.channel,i=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(r),"/message/").concat(i)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},getRequestHeaders:function(){return{"Content-Type":"application/json"}},isAuthSupported:function(){return!0},prepareParams:function(){return{}},postPayload:function(e,t){return t.action},handleResponse:function(e,t){return{data:t.data}}});var pe=Object.freeze({__proto__:null,getOperation:function(){return j.PNRemoveMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.channel,i=t.actionTimetoken;return t.messageTimetoken?i?n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key":"Missing action timetoken":"Missing message timetoken"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config,r=t.channel,i=t.actionTimetoken,o=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(r),"/message/").concat(o,"/action/").concat(i)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{data:t.data}}});var he=Object.freeze({__proto__:null,getOperation:function(){return j.PNGetMessageActionsOperation},validateParams:function(e,t){var n=e.config,r=t.channel;return n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channel;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(A.encodeString(r))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.limit,r=t.start,i=t.end,o={};return n&&(o.limit=n),r&&(o.start=r),i&&(o.end=i),o},handleResponse:function(e,t){var n={data:t.data,start:null,end:null};return n.data.length&&(n.end=n.data[n.data.length-1].actionTimetoken,n.start=n.data[0].actionTimetoken),n}}),fe={getOperation:function(){return j.PNListFilesOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel can't be empty"},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel),"/files")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.limit&&(n.limit=t.limit),t.next&&(n.next=t.next),n},handleResponse:function(e,t){return{status:t.status,data:t.data,next:t.next,count:t.count}}},de={getOperation:function(){return j.PNGenerateUploadUrlOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?void 0:"name can't be empty":"channel can't be empty"},usePost:function(){return!0},postURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel),"/generate-upload-url")},postPayload:function(e,t){return{name:t.name}},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data,file_upload_request:t.file_upload_request}}},ye={getOperation:function(){return j.PNPublishFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.fileId)?(null==t?void 0:t.fileName)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},getURL:function(e,t){var n=e.config,r=n.publishKey,i=n.subscribeKey,o=function(e,t){var n=e.crypto,r=e.config,i=JSON.stringify(t);return r.cipherKey&&(i=n.encrypt(i),i=JSON.stringify(i)),i||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(i,"/0/").concat(A.encodeString(t.channel),"/0/").concat(A.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.ttl&&(n.ttl=t.ttl),void 0!==t.storeInHistory&&(n.store=t.storeInHistory?"1":"0"),t.meta&&"object"==typeof t.meta&&(n.meta=JSON.stringify(t.meta)),n},handleResponse:function(e,t){return{timetoken:t[2]}}},ge=function(e){var t=function(e){var t=this,n=e.generateUploadUrl,r=e.publishFile,s=e.modules,a=s.PubNubFile,u=s.config,c=s.cryptography,l=s.networking;return function(e){var s=e.channel,p=e.file,h=e.message,f=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return i(t,void 0,void 0,(function(){var e,t,i,v,m,b,_,O,P,S,w,E,T,k,C,N,A,R,M,j,U,x,D,I,G,K,F,L;return o(this,(function(o){switch(o.label){case 0:if(!s)throw new B("Validation failed, check status for details",H("channel can't be empty"));if(!p)throw new B("Validation failed, check status for details",H("file can't be empty"));return e=a.create(p),[4,n({channel:s,name:e.name})];case 1:return t=o.sent(),i=t.file_upload_request,v=i.url,m=i.form_fields,b=t.data,_=b.id,O=b.name,a.supportsEncryptFile&&(null!=f?f:u.cipherKey)?[4,c.encryptFile(null!=f?f:u.cipherKey,e,a)]:[3,3];case 2:e=o.sent(),o.label=3;case 3:P=m,e.mimeType&&(P=m.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),o.label=4;case 4:return o.trys.push([4,18,,22]),a.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[v,P],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([o.sent()]))];case 6:return S=o.sent(),[3,17];case 7:return a.supportsFile?(C=(k=l).POSTFILE,N=[v,P],[4,e.toFile()]):[3,10];case 8:return[4,C.apply(k,N.concat([o.sent()]))];case 9:return S=o.sent(),[3,17];case 10:return a.supportsBuffer?(R=(A=l).POSTFILE,M=[v,P],[4,e.toBuffer()]):[3,13];case 11:return[4,R.apply(A,M.concat([o.sent()]))];case 12:return S=o.sent(),[3,17];case 13:return a.supportsBlob?(U=(j=l).POSTFILE,x=[v,P],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(j,x.concat([o.sent()]))];case 15:return S=o.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,22];case 18:return(D=o.sent()).response?[4,(q=D.response,new Promise((function(e){var t="";q.on("data",(function(e){t+=e.toString("utf8")})),q.on("end",(function(){e(t)}))})))]:[3,20];case 19:throw I=o.sent(),G=/(.*)<\/Message>/gi.exec(I),new B(G?"Upload to bucket failed: ".concat(G[1]):"Upload to bucket failed.",D);case 20:throw new B("Upload to bucket failed.",D);case 21:return[3,22];case 22:if(204!==S.status)throw new B("Upload to bucket was unsuccessful",S);K=u.fileUploadPublishRetryLimit,F=!1,L={timetoken:"0"},o.label=23;case 23:return o.trys.push([23,25,,26]),[4,r({channel:s,message:h,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 24:return L=o.sent(),F=!0,[3,26];case 25:return o.sent(),K-=1,[3,26];case 26:if(!F&&K>0)return[3,23];o.label=27;case 27:if(F)return[2,{timetoken:L.timetoken,id:_,name:O}];throw new B("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:s,id:_,name:O})}var q}))}))}}(e);return function(e,n){var r=t(e);return"function"==typeof n?(r.then((function(e){return n(null,e)})).catch((function(e){return n(e,null)})),r):r}},ve=function(e,t){var n=t.channel,r=t.id,i=t.name,o=e.config,s=e.networking,a=e.tokenManager;if(!n)throw new B("Validation failed, check status for details",H("channel can't be empty"));if(!r)throw new B("Validation failed, check status for details",H("file id can't be empty"));if(!i)throw new B("Validation failed, check status for details",H("file name can't be empty"));var u="/v1/files/".concat(o.subscribeKey,"/channels/").concat(A.encodeString(n),"/files/").concat(r,"/").concat(i),c={};c.uuid=o.getUUID(),c.pnsdk=z(o);var l=a.getToken()||o.getAuthKey();l&&(c.auth=l),o.secretKey&&J(e,u,c,{},{getOperation:function(){return"PubNubGetFileUrlOperation"}});var p=Object.keys(c).map((function(e){return"".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(c[e]))})).join("&");return""!==p?"".concat(s.getStandardOrigin()).concat(u,"?").concat(p):"".concat(s.getStandardOrigin()).concat(u)},me={getOperation:function(){return j.PNDownloadFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?(null==t?void 0:t.id)?void 0:"id can't be empty":"name can't be empty":"channel can't be empty"},useGetFile:function(){return!0},getFileURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},ignoreBody:function(){return!0},forceBuffered:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t,n){var r=e.PubNubFile,s=e.config,a=e.cryptography;return i(void 0,void 0,void 0,(function(){var e,i,u,c;return o(this,(function(o){switch(o.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(i=n.cipherKey)&&void 0!==i?i:s.cipherKey)?[4,a.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:s.cipherKey,e)]:[3,2];case 1:e=o.sent(),o.label=2;case 2:return[2,r.create({data:e,name:null!==(c=t.response.name)&&void 0!==c?c:n.name,mimeType:t.response.type})]}}))}))}},be={getOperation:function(){return j.PNListFilesOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.id)?(null==t?void 0:t.name)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status}}},_e={getOperation:function(){return j.PNGetAllUUIDMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i,o,s,u,c,l,p,h={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),h.include=h.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(h.count=null===(i=t.include)||void 0===i?void 0:i.totalCount),(null===(o=null==t?void 0:t.page)||void 0===o?void 0:o.next)&&(h.start=null===(s=t.page)||void 0===s?void 0:s.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(h.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),h.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,next:t.next,prev:t.prev}}},Oe={getOperation:function(){return j.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(A.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i=e.config,o={};return o.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:i.getUUID(),o.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&o.include.pop(),o.include=o.include.join(","),o},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Pe={getOperation:function(){return j.PNSetUUIDMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.data))return"Data cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(A.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i=e.config,o={};return o.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:i.getUUID(),o.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&o.include.pop(),o.include=o.include.join(","),o},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Se={getOperation:function(){return j.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(A.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r=e.config;return{uuid:null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},we={getOperation:function(){return j.PNGetAllChannelMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i,o,s,u,c,l,p,h={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),h.include=h.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(h.count=null===(i=t.include)||void 0===i?void 0:i.totalCount),(null===(o=null==t?void 0:t.page)||void 0===o?void 0:o.next)&&(h.start=null===(s=t.page)||void 0===s?void 0:s.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(h.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),h.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Ee={getOperation:function(){return j.PNGetChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Te={getOperation:function(){return j.PNSetChannelMetadataOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.data)?void 0:"Data cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},ke={getOperation:function(){return j.PNRemoveChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ce={getOperation:function(){return j.PNGetMembersOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"UUID cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel),"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i,o,s,u,c,l,p,h,f,d,y={include:["uuid.status","uuid.type","type"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&y.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customUUIDFields)&&y.include.push("uuid.custom"),(null===(o=null===(i=t.include)||void 0===i?void 0:i.UUIDFields)||void 0===o||o)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(s=null==t?void 0:t.include)||void 0===s?void 0:s.totalCount)&&(y.count=null===(u=t.include)||void 0===u?void 0:u.totalCount),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.next)&&(y.start=null===(l=t.page)||void 0===l?void 0:l.next),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.prev)&&(y.end=null===(h=t.page)||void 0===h?void 0:h.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),y},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Ne={getOperation:function(){return j.PNSetMembersOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.uuids)&&0!==(null==t?void 0:t.uuids.length)?void 0:"UUIDs cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(A.encodeString(t.channel),"/uuids")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.uuids.map((function(e){return"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i,o,s,u,c,l,p,h={include:["uuid.status","uuid.type","type"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customUUIDFields)&&h.include.push("uuid.custom"),(null===(i=t.include)||void 0===i?void 0:i.UUIDFields)&&h.include.push("uuid")),h.include=h.include.join(","),(null===(o=null==t?void 0:t.include)||void 0===o?void 0:o.totalCount)&&(h.count=!0),(null===(s=null==t?void 0:t.page)||void 0===s?void 0:s.next)&&(h.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(h.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),null!=t.limit&&(h.limit=t.limit),(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Ae={getOperation:function(){return j.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(A.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i,o,s,u,c,l,p,h,f,d={include:["channel.status","channel.type","status"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&d.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customChannelFields)&&d.include.push("channel.custom"),(null===(i=t.include)||void 0===i?void 0:i.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(o=null==t?void 0:t.include)||void 0===o?void 0:o.totalCount)&&(d.count=null===(s=t.include)||void 0===s?void 0:s.totalCount),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.next)&&(d.start=null===(c=t.page)||void 0===c?void 0:c.next),(null===(l=null==t?void 0:t.page)||void 0===l?void 0:l.prev)&&(d.end=null===(p=t.page)||void 0===p?void 0:p.prev),(null==t?void 0:t.filter)&&(d.filter=t.filter),d.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(f=t.sort)&&void 0!==f?f:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),d},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Re={getOperation:function(){return j.PNSetMembershipsOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)||0===(null==t?void 0:t.channels.length))return"Channels cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(A.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.channels.map((function(e){return"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,i,o,s,u,c,l,p,h={include:["channel.status","channel.type","status"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customChannelFields)&&h.include.push("channel.custom"),(null===(i=t.include)||void 0===i?void 0:i.channelFields)&&h.include.push("channel")),h.include=h.include.join(","),(null===(o=null==t?void 0:t.include)||void 0===o?void 0:o.totalCount)&&(h.count=!0),(null===(s=null==t?void 0:t.page)||void 0===s?void 0:s.next)&&(h.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(h.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),null!=t.limit&&(h.limit=t.limit),(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}};var Me=Object.freeze({__proto__:null,getOperation:function(){return j.PNAccessManagerAudit},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/audit/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channel,r=t.channelGroup,i=t.authKeys,o=void 0===i?[]:i,s={};return n&&(s.channel=n),r&&(s["channel-group"]=r),o.length>0&&(s.auth=o.join(",")),s},handleResponse:function(e,t){return t.payload}});var je=Object.freeze({__proto__:null,getOperation:function(){return j.PNAccessManagerGrant},validateParams:function(e,t){var n=e.config;return n.subscribeKey?n.publishKey?n.secretKey?null==t.uuids||t.authKeys?null==t.uuids||null==t.channels&&null==t.channelGroups?void 0:"Both channel/channelgroup and uuid cannot be used in the same request":"authKeys are required for grant request on uuids":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/grant/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channels,r=void 0===n?[]:n,i=t.channelGroups,o=void 0===i?[]:i,s=t.uuids,a=void 0===s?[]:s,u=t.ttl,c=t.read,l=void 0!==c&&c,p=t.write,h=void 0!==p&&p,f=t.manage,d=void 0!==f&&f,y=t.get,g=void 0!==y&&y,v=t.join,m=void 0!==v&&v,b=t.update,_=void 0!==b&&b,O=t.authKeys,P=void 0===O?[]:O,S=t.delete,w={};return w.r=l?"1":"0",w.w=h?"1":"0",w.m=d?"1":"0",w.d=S?"1":"0",w.g=g?"1":"0",w.j=m?"1":"0",w.u=_?"1":"0",r.length>0&&(w.channel=r.join(",")),o.length>0&&(w["channel-group"]=o.join(",")),P.length>0&&(w.auth=P.join(",")),a.length>0&&(w["target-uuid"]=a.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function Ue(e){var t,n,r,i,o=void 0!==(null==e?void 0:e.authorizedUserId),s=void 0!==(null===(t=null==e?void 0:e.resources)||void 0===t?void 0:t.users),a=void 0!==(null===(n=null==e?void 0:e.resources)||void 0===n?void 0:n.spaces),u=void 0!==(null===(r=null==e?void 0:e.patterns)||void 0===r?void 0:r.users),c=void 0!==(null===(i=null==e?void 0:e.patterns)||void 0===i?void 0:i.spaces);return u||s||c||a||o}function xe(e){var t=0;return e.join&&(t|=128),e.update&&(t|=64),e.get&&(t|=32),e.delete&&(t|=8),e.manage&&(t|=4),e.write&&(t|=2),e.read&&(t|=1),t}function De(e,t){if(Ue(t))return function(e,t){var n=t.ttl,r=t.resources,i=t.patterns,o=t.meta,s=t.authorizedUserId,a={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.users,c=r.spaces,l=r.groups;u&&Object.keys(u).forEach((function(e){a.permissions.resources.uuids[e]=xe(u[e])})),c&&Object.keys(c).forEach((function(e){a.permissions.resources.channels[e]=xe(c[e])})),l&&Object.keys(l).forEach((function(e){a.permissions.resources.groups[e]=xe(l[e])}))}if(i){var p=i.users,h=i.spaces,f=i.groups;p&&Object.keys(p).forEach((function(e){a.permissions.patterns.uuids[e]=xe(p[e])})),h&&Object.keys(h).forEach((function(e){a.permissions.patterns.channels[e]=xe(h[e])})),f&&Object.keys(f).forEach((function(e){a.permissions.patterns.groups[e]=xe(f[e])}))}return(n||0===n)&&(a.ttl=n),o&&(a.permissions.meta=o),s&&(a.permissions.uuid="".concat(s)),a}(0,t);var n=t.ttl,r=t.resources,i=t.patterns,o=t.meta,s=t.authorized_uuid,a={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.uuids,c=r.channels,l=r.groups;u&&Object.keys(u).forEach((function(e){a.permissions.resources.uuids[e]=xe(u[e])})),c&&Object.keys(c).forEach((function(e){a.permissions.resources.channels[e]=xe(c[e])})),l&&Object.keys(l).forEach((function(e){a.permissions.resources.groups[e]=xe(l[e])}))}if(i){var p=i.uuids,h=i.channels,f=i.groups;p&&Object.keys(p).forEach((function(e){a.permissions.patterns.uuids[e]=xe(p[e])})),h&&Object.keys(h).forEach((function(e){a.permissions.patterns.channels[e]=xe(h[e])})),f&&Object.keys(f).forEach((function(e){a.permissions.patterns.groups[e]=xe(f[e])}))}return(n||0===n)&&(a.ttl=n),o&&(a.permissions.meta=o),s&&(a.permissions.uuid="".concat(s)),a}var Ie=Object.freeze({__proto__:null,getOperation:function(){return j.PNAccessManagerGrantToken},extractPermissions:xe,validateParams:function(e,t){var n,r,i,o,s,a,u=e.config;if(!u.subscribeKey)return"Missing Subscribe Key";if(!u.publishKey)return"Missing Publish Key";if(!u.secretKey)return"Missing Secret Key";if(!t.resources&&!t.patterns)return"Missing either Resources or Patterns.";var c=void 0!==(null==t?void 0:t.authorized_uuid),l=void 0!==(null===(n=null==t?void 0:t.resources)||void 0===n?void 0:n.uuids),p=void 0!==(null===(r=null==t?void 0:t.resources)||void 0===r?void 0:r.channels),h=void 0!==(null===(i=null==t?void 0:t.resources)||void 0===i?void 0:i.groups),f=void 0!==(null===(o=null==t?void 0:t.patterns)||void 0===o?void 0:o.uuids),d=void 0!==(null===(s=null==t?void 0:t.patterns)||void 0===s?void 0:s.channels),y=void 0!==(null===(a=null==t?void 0:t.patterns)||void 0===a?void 0:a.groups),g=c||l||f||p||d||h||y;return Ue(t)&&g?"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`":(!t.resources||t.resources.uuids&&0!==Object.keys(t.resources.uuids).length||t.resources.channels&&0!==Object.keys(t.resources.channels).length||t.resources.groups&&0!==Object.keys(t.resources.groups).length||t.resources.users&&0!==Object.keys(t.resources.users).length||t.resources.spaces&&0!==Object.keys(t.resources.spaces).length)&&(!t.patterns||t.patterns.uuids&&0!==Object.keys(t.patterns.uuids).length||t.patterns.channels&&0!==Object.keys(t.patterns.channels).length||t.patterns.groups&&0!==Object.keys(t.patterns.groups).length||t.patterns.users&&0!==Object.keys(t.patterns.users).length||t.patterns.spaces&&0!==Object.keys(t.patterns.spaces).length)?void 0:"Missing values for either Resources or Patterns."},postURL:function(e){var t=e.config;return"/v3/pam/".concat(t.subscribeKey,"/grant")},usePost:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(){return{}},postPayload:function(e,t){return De(0,t)},handleResponse:function(e,t){return t.data.token}}),Ge={getOperation:function(){return j.PNAccessManagerRevokeToken},validateParams:function(e,t){return e.config.secretKey?t?void 0:"token can't be empty":"Missing Secret Key"},getURL:function(e,t){var n=e.config;return"/v3/pam/".concat(n.subscribeKey,"/grant/").concat(A.encodeString(t))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e){return{uuid:e.config.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}};function Ke(e,t){var n=e.crypto,r=e.config,i=JSON.stringify(t);return r.cipherKey&&(i=n.encrypt(i),i=JSON.stringify(i)),i}var Fe=Object.freeze({__proto__:null,getOperation:function(){return j.PNPublishOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},usePost:function(e,t){var n=t.sendByPost;return void 0!==n&&n},getURL:function(e,t){var n=e.config,r=t.channel,i=Ke(e,t.message);return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(A.encodeString(r),"/0/").concat(A.encodeString(i))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(A.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},postPayload:function(e,t){return Ke(e,t.message)},prepareParams:function(e,t){var n=t.meta,r=t.replicate,i=void 0===r||r,o=t.storeInHistory,s=t.ttl,a={};return null!=o&&(a.store=o?"1":"0"),s&&(a.ttl=s),!1===i&&(a.norep="true"),n&&"object"==typeof n&&(a.meta=JSON.stringify(n)),a},handleResponse:function(e,t){return{timetoken:t[2]}}});var Le=Object.freeze({__proto__:null,getOperation:function(){return j.PNSignalOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},getURL:function(e,t){var n,r=e.config,i=t.channel,o=t.message,s=(n=o,JSON.stringify(n));return"/signal/".concat(r.publishKey,"/").concat(r.subscribeKey,"/0/").concat(A.encodeString(i),"/0/").concat(A.encodeString(s))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});function Be(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}var He=Object.freeze({__proto__:null,getOperation:function(){return j.PNHistoryOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channel,r=e.config;return"/v2/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(A.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,i=t.reverse,o=t.count,s=void 0===o?100:o,a=t.stringifiedTimeToken,u=void 0!==a&&a,c=t.includeMeta,l=void 0!==c&&c,p={include_token:"true"};return p.count=s,n&&(p.start=n),r&&(p.end=r),u&&(p.string_message_token="true"),null!=i&&(p.reverse=i.toString()),l&&(p.include_meta="true"),p},handleResponse:function(e,t){var n={messages:[],startTimeToken:t[1],endTimeToken:t[2]};return Array.isArray(t[0])&&t[0].forEach((function(t){var r={timetoken:t.timetoken,entry:Be(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var qe=Object.freeze({__proto__:null,getOperation:function(){return j.PNDeleteMessagesOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},useDelete:function(){return!0},getURL:function(e,t){var n=t.channel,r=e.config;return"/v3/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(A.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,i={};return n&&(i.start=n),r&&(i.end=r),i},handleResponse:function(e,t){return t.payload}});var ze=Object.freeze({__proto__:null,getOperation:function(){return j.PNMessageCounts},validateParams:function(e,t){var n=t.channels,r=t.timetoken,i=t.channelTimetokens,o=e.config;return n?r&&i?"timetoken and channelTimetokens are incompatible together":r&&i&&i.length>1&&n.length!==i.length?"Length of channelTimetokens and channels do not match":o.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channels,r=e.config,i=n.join(",");return"/v3/history/sub-key/".concat(r.subscribeKey,"/message-counts/").concat(A.encodeString(i))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.timetoken,r=t.channelTimetokens,i={};if(r&&1===r.length){var o=a(r,1)[0];i.timetoken=o}else r?i.channelsTimetoken=r.join(","):n&&(i.timetoken=n);return i},handleResponse:function(e,t){return{channels:t.channels}}});var Ve=Object.freeze({__proto__:null,getOperation:function(){return j.PNFetchMessagesOperation},validateParams:function(e,t){var n=t.channels,r=t.includeMessageActions,i=void 0!==r&&r,o=e.config;if(!n||0===n.length)return"Missing channels";if(!o.subscribeKey)return"Missing Subscribe Key";if(i&&n.length>1)throw new TypeError("History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.")},getURL:function(e,t){var n=t.channels,r=void 0===n?[]:n,i=t.includeMessageActions,o=void 0!==i&&i,s=e.config,a=o?"history-with-actions":"history",u=r.length>0?r.join(","):",";return"/v3/".concat(a,"/sub-key/").concat(s.subscribeKey,"/channel/").concat(A.encodeString(u))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channels,r=t.start,i=t.end,o=t.includeMessageActions,s=t.count,a=t.stringifiedTimeToken,u=void 0!==a&&a,c=t.includeMeta,l=void 0!==c&&c,p=t.includeUuid,h=t.includeUUID,f=void 0===h||h,d=t.includeMessageType,y=void 0===d||d,g={};return g.max=s||(n.length>1||!0===o?25:100),r&&(g.start=r),i&&(g.end=i),u&&(g.string_message_token="true"),l&&(g.include_meta="true"),f&&!1!==p&&(g.include_uuid="true"),y&&(g.include_message_type="true"),g},handleResponse:function(e,t){var n={channels:{}};return Object.keys(t.channels||{}).forEach((function(r){n.channels[r]=[],(t.channels[r]||[]).forEach((function(t){var i={};i.channel=r,i.timetoken=t.timetoken,i.message=function(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}(e,t.message),i.messageType=t.message_type,i.uuid=t.uuid,t.actions&&(i.actions=t.actions,i.data=t.actions),t.meta&&(i.meta=t.meta),n.channels[r].push(i)}))})),t.more&&(n.more=t.more),n}});var Je=Object.freeze({__proto__:null,getOperation:function(){return j.PNTimeOperation},getURL:function(){return"/time/0"},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(){return{}},isAuthSupported:function(){return!1},handleResponse:function(e,t){return{timetoken:t[0]}},validateParams:function(){}});var We=Object.freeze({__proto__:null,getOperation:function(){return j.PNSubscribeOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,o=i.length>0?i.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(A.encodeString(o),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=e.config,r=t.state,i=t.channelGroups,o=void 0===i?[]:i,s=t.timetoken,a=t.filterExpression,u=t.region,c={heartbeat:n.getPresenceTimeout()};return o.length>0&&(c["channel-group"]=o.join(",")),a&&a.length>0&&(c["filter-expr"]=a),Object.keys(r).length&&(c.state=JSON.stringify(r)),s&&(c.tt=s),u&&(c.tr=u),c},handleResponse:function(e,t){var n=[];t.m.forEach((function(e){var t={publishTimetoken:e.p.t,region:e.p.r},r={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};n.push(r)}));var r={timetoken:t.t.t,region:t.t.r};return{messages:n,metadata:r}}}),Xe={getOperation:function(){return j.PNHandshakeOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)&&!(null==t?void 0:t.channelGroups))return"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels?t.channels.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(A.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),n.tt=0,t.state&&(n.state=JSON.stringify(t.state)),t.filterExpression&&t.filterExpression.length>0&&(n["filter-expr"]=t.filterExpression),n.ee="",n},handleResponse:function(e,t){return{region:t.t.r,timetoken:t.t.t}}},$e={getOperation:function(){return j.PNReceiveMessagesOperation},validateParams:function(e,t){return(null==t?void 0:t.channels)||(null==t?void 0:t.channelGroups)?(null==t?void 0:t.timetoken)?(null==t?void 0:t.region)?void 0:"region can not be empty":"timetoken can not be empty":"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels?t.channels.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(A.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},getAbortSignal:function(e,t){return t.abortSignal},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),t.filterExpression&&t.filterExpression.length>0&&(n["filter-expr"]=t.filterExpression),n.tt=t.timetoken,n.tr=t.region,n.ee="",n},handleResponse:function(e,t){var n=[];return t.m.forEach((function(e){var t={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,publishMetaData:{timetoken:e.p.t,region:e.p.r}};n.push(t)})),{messages:n,metadata:{region:t.t.r,timetoken:t.t.t}}}},Qe=function(){function e(e){void 0===e&&(e=!1),this.sync=e,this.listeners=new Set}return e.prototype.subscribe=function(e){var t=this;return this.listeners.add(e),function(){t.listeners.delete(e)}},e.prototype.notify=function(e){var t=this,n=function(){t.listeners.forEach((function(t){t(e)}))};this.sync?n():setTimeout(n,0)},e}(),Ye=function(){function e(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}return e.prototype.transition=function(e,t){var n;if(this.transitionMap.has(t.type))return null===(n=this.transitionMap.get(t.type))||void 0===n?void 0:n(e,t)},e.prototype.on=function(e,t){return this.transitionMap.set(e,t),this},e.prototype.with=function(e,t){return[this,e,null!=t?t:[]]},e.prototype.onEnter=function(e){return this.enterEffects.push(e),this},e.prototype.onExit=function(e){return this.exitEffects.push(e),this},e}(),Ze=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new Ye(e)},n.prototype.start=function(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})},n.prototype.transition=function(e){var t,n,r,i,o,u;if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});var c=this.currentState.transition(this.currentContext,e);if(c){var l=a(c,3),p=l[0],h=l[1],f=l[2];try{for(var d=s(this.currentState.exitEffects),y=d.next();!y.done;y=d.next()){var g=y.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){t={error:e}}finally{try{y&&!y.done&&(n=d.return)&&n.call(d)}finally{if(t)throw t.error}}var v=this.currentState;this.currentState=p;var m=this.currentContext;this.currentContext=h,this.notify({type:"transitionDone",fromState:v,fromContext:m,toState:p,toContext:h,event:e});try{for(var b=s(f),_=b.next();!_.done;_=b.next()){g=_.value;this.notify({type:"invocationDispatched",invocation:g})}}catch(e){r={error:e}}finally{try{_&&!_.done&&(i=b.return)&&i.call(b)}finally{if(r)throw r.error}}try{for(var O=s(this.currentState.enterEffects),P=O.next();!P.done;P=O.next()){g=P.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){o={error:e}}finally{try{P&&!P.done&&(u=O.return)&&u.call(O)}finally{if(o)throw o.error}}}},n}(Qe),et=function(){function e(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}return e.prototype.on=function(e,t){this.handlers.set(e,t)},e.prototype.dispatch=function(e){if("CANCEL"!==e.type){var t=this.handlers.get(e.type);if(!t)throw new Error("Unhandled invocation '".concat(e.type,"'"));var n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}else if(this.instances.has(e.payload)){var r=this.instances.get(e.payload);null==r||r.cancel(),this.instances.delete(e.payload)}},e.prototype.dispose=function(){var e,t;try{for(var n=s(this.instances.entries()),r=n.next();!r.done;r=n.next()){var i=a(r.value,2),o=i[0];i[1].cancel(),this.instances.delete(o)}}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}},e}();function tt(e,t){var n=function(){for(var n=[],r=0;r0&&s(e),[2]}))}))}))),r.on(pt.type,at((function(e,t,n){var s=n.emitStatus;return i(r,void 0,void 0,(function(){return o(this,(function(t){return s(e),[2]}))}))}))),r.on(ht.type,at((function(e,n,s){var a=s.receiveEvents,u=s.delay,c=s.config;return i(r,void 0,void 0,(function(){var r,i;return o(this,(function(o){switch(o.label){case 0:return c.retryConfiguration&&c.retryConfiguration.shouldRetry(e.reason,e.attempts)?(n.throwIfAborted(),[4,u(c.retryConfiguration.getDelay(e.attempts))]):[3,6];case 1:o.sent(),n.throwIfAborted(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,a({abortSignal:n,channels:e.channels,channelGroups:e.groups,timetoken:e.cursor.timetoken,region:e.cursor.region,filterExpression:c.filterExpression})];case 3:return r=o.sent(),[2,t.transition(Et(r.metadata,r.messages))];case 4:return(i=o.sent())instanceof Error&&"Aborted"===i.message?[2]:i instanceof B?[2,t.transition(Tt(i))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(kt())];case 7:return[2]}}))}))}))),r.on(ft.type,at((function(e,n,s){var a=s.handshake,u=s.delay,c=s.presenceState,l=s.config;return i(r,void 0,void 0,(function(){var r,i;return o(this,(function(o){switch(o.label){case 0:return l.retryConfiguration&&l.retryConfiguration.shouldRetry(e.reason,e.attempts)?(n.throwIfAborted(),[4,u(l.retryConfiguration.getDelay(e.attempts))]):[3,6];case 1:o.sent(),n.throwIfAborted(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,a({abortSignal:n,channels:e.channels,channelGroups:e.groups,filterExpression:l.filterExpression,state:c})];case 3:return r=o.sent(),[2,t.transition(_t(r))];case 4:return(i=o.sent())instanceof Error&&"Aborted"===i.message?[2]:i instanceof B?[2,t.transition(Ot(i))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(Pt())];case 7:return[2]}}))}))}))),r}return t(n,e),n}(et),Rt=new Ye("HANDSHAKE_STOPPED");Rt.on(dt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(gt.type,(function(e){return Gt.with(n({},e))}));var Mt=new Ye("HANDSHAKE_FAILURE");Mt.on(yt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})})),Mt.on(gt.type,(function(e){return Gt.with(n({},e))}));var jt=new Ye("STOPPED");jt.on(dt.type,(function(e,t){return Dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),jt.on(vt.type,(function(e,t){return Dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),jt.on(gt.type,(function(e){return Gt.with({channels:e.channels,groups:e.groups})})),jt.on(Nt.type,(function(){return Kt.with(void 0)}));var Ut=new Ye("RECEIVE_FAILED");Ut.on(Ct.type,(function(e){return Gt.with({channels:e.channels,groups:e.groups,timetoken:e.cursor.timetoken})})),Ut.on(yt.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})})),Ut.on(dt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups,timetoken:t.payload.timetoken})})),Ut.on(vt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups,timetoken:t.payload.timetoken})})),Ut.on(Nt.type,(function(e){return Kt.with(void 0)}));var xt=new Ye("RECEIVE_RECONNECTING");xt.onEnter((function(e){return ht(e)})),xt.onExit((function(){return ht.cancel})),xt.on(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[lt(t.payload.events)])})),xt.on(Tt.type,(function(e,t){return xt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),xt.on(kt.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason},[pt({category:R.PNDisconnectedUnexpectedlyCategory})])})),xt.on(yt.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[pt({category:R.PNDisconnectedCategory})])})),xt.on(vt.type,(function(e,t){var n,r;return Dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:null!==(n=t.payload.timetoken)&&void 0!==n?n:e.cursor.timetoken,region:null!==(r=t.payload.region)&&void 0!==r?r:e.cursor.region}})})),xt.on(dt.type,(function(e,t){return Dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(Nt.type,(function(e){return Kt.with(void 0,[pt({category:R.PNDisconnectedCategory})])}));var Dt=new Ye("RECEIVING");Dt.onEnter((function(e){return ct(e.channels,e.groups,e.cursor)})),Dt.onExit((function(){return ct.cancel})),Dt.on(St.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[lt(t.payload.events)])})),Dt.on(dt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Dt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups})})),Dt.on(wt.type,(function(e,t){return xt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Dt.on(yt.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[pt({category:R.PNDisconnectedCategory})])})),Dt.on(Nt.type,(function(e){return Kt.with(void 0,[pt({category:R.PNDisconnectedCategory})])}));var It=new Ye("HANDSHAKE_RECONNECTING");It.onEnter((function(e){return ft(e)})),It.onExit((function(){return ft.cancel})),It.on(_t.type,(function(e,t){var n=e.timetoken?{timetoken:e.timetoken,region:1}:t.payload.cursor;return Dt.with({channels:e.channels,groups:e.groups,cursor:n},[pt({category:R.PNConnectedCategory})])})),It.on(Ot.type,(function(e,t){return It.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),It.on(Pt.type,(function(e){return Mt.with({groups:e.groups,channels:e.channels,reason:e.reason},[pt({category:R.PNConnectionErrorCategory})])})),It.on(yt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups},[pt({category:R.PNDisconnectedCategory})])})),It.on(dt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})})),It.on(vt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})})),It.on(Nt.type,(function(e){return Kt.with(void 0,[pt({category:R.PNDisconnectedCategory})])}));var Gt=new Ye("HANDSHAKING");Gt.onEnter((function(e){return ut(e.channels,e.groups)})),Gt.onExit((function(){return ut.cancel})),Gt.on(dt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Gt.with({channels:t.payload.channels,groups:t.payload.groups})})),Gt.on(mt.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:e.timetoken&&"0"!==e.timetoken?e.timetoken:t.payload.timetoken,region:t.payload.region}},[pt({category:R.PNConnectedCategory})])})),Gt.on(bt.type,(function(e,t){return It.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(yt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})})),Gt.on(Nt.type,(function(e){return Kt.with()})),Gt.on(vt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups,timetoken:t.payload.timetoken})}));var Kt=new Ye("UNSUBSCRIBED");Kt.on(dt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups,timetoken:t.payload.timetoken})})),Kt.on(vt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups,timetoken:t.payload.timetoken})}));var Ft=function(){function e(e){var t=this;this.engine=new Ze,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new At(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Kt,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(e){var t=this,n=e.channels,r=e.channelGroups,i=e.timetoken,o=e.withPresence;this.channels=u(u([],a(this.channels),!1),a(null!=n?n:[]),!1),this.groups=u(u([],a(this.groups),!1),a(null!=r?r:[]),!1),o&&(this.channels.map((function(e){return t.channels.push("".concat(e,"-pnpres"))})),this.groups.map((function(e){return t.groups.push("".concat(e,"-pnpres"))}))),i?this.engine.transition(vt(this.channels,this.groups,i)):this.engine.transition(dt(this.channels,this.groups)),this.dependencies.join&&this.dependencies.join({channels:this.channels.filter((function(e){return!e.endsWith("-pnpres")})),groups:this.groups.filter((function(e){return!e.endsWith("-pnpres")}))})},e.prototype.unsubscribe=function(e){var t=this,n=e.channels,r=e.groups,i=null==n?void 0:n.slice(0);null==n||n.map((function(e){return i.push("".concat(e,"-pnpres"))})),this.channels=this.channels.filter((function(e){return!(null==i?void 0:i.includes(e))}));var o=null==r?void 0:r.slice(0);null==r||r.map((function(e){return o.push("".concat(e,"-pnpres"))})),this.groups=this.groups.filter((function(e){return!(null==o?void 0:o.includes(e))})),this.dependencies.presenceState&&(null==n||n.forEach((function(e){return delete t.dependencies.presenceState[e]})),null==r||r.forEach((function(e){return delete t.dependencies.presenceState[e]}))),this.engine.transition(dt(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leave&&this.dependencies.leave({channels:n,groups:r})},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.dependencies.presenceState&&(this.dependencies.presenceState={}),this.engine.transition(dt(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()},e.prototype.reconnect=function(){this.engine.transition(gt())},e.prototype.disconnect=function(){this.engine.transition(yt()),this.dependencies.leaveAll&&this.dependencies.leaveAll()},e.prototype.dispose=function(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()},e}(),Lt=tt("RECONNECT",(function(){return{}})),Bt=tt("DISCONNECT",(function(){return{}})),Ht=tt("JOINED",(function(e,t){return{channels:e,groups:t}})),qt=tt("LEFT",(function(e,t){return{channels:e,groups:t}})),zt=tt("LEFT_ALL",(function(){return{}})),Vt=tt("HEARTBEAT_SUCCESS",(function(){return{}})),Jt=tt("HEARTBEAT_FAILURE",(function(e){return e})),Wt=tt("HEARTBEAT_GIVEUP",(function(){return{}})),Xt=tt("TIMES_UP",(function(){return{}})),$t=nt("HEARTBEAT",(function(e,t){return{channels:e,groups:t}})),Qt=nt("LEAVE",(function(e,t){return{channels:e,groups:t}})),Yt=rt("WAIT",(function(){return{}})),Zt=rt("DELAYED_HEARTBEAT",(function(e){return e})),en=function(e){function n(t,n){var r=e.call(this,n)||this;return r.on($t.type,at((function(e,n,s){var a=s.heartbeat,u=s.presenceState;return i(r,void 0,void 0,(function(){var n;return o(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,a({channels:e.channels,channelGroups:e.groups,state:u})];case 1:return r.sent(),t.transition(Vt()),[3,3];case 2:return(n=r.sent())instanceof B?[2,t.transition(Jt(n))]:[3,3];case 3:return[2]}}))}))}))),r.on(Qt.type,at((function(e,t,n){var s=n.leave,a=n.config;return i(r,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:if(a.suppressLeaveEvents)return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,s({channels:e.channels,channelGroups:e.groups})];case 2:case 3:return t.sent(),[3,4];case 4:return[2]}}))}))}))),r.on(Yt.type,at((function(e,n,s){var a=s.heartbeatDelay;return i(r,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return n.throwIfAborted(),[4,a()];case 1:return e.sent(),n.throwIfAborted(),[2,t.transition(Xt())]}}))}))}))),r.on(Zt.type,at((function(e,n,s){var a=s.heartbeat,u=s.retryDelay,c=s.presenceState,l=s.config;return i(r,void 0,void 0,(function(){var r;return o(this,(function(i){switch(i.label){case 0:return l.retryConfiguration&&l.retryConfiguration.shouldRetry(e.reason,e.attempts)?(n.throwIfAborted(),[4,u(l.retryConfiguration.getDelay(e.attempts))]):[3,6];case 1:i.sent(),n.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,a({channels:e.channels,channelGroups:e.groups,state:c})];case 3:return i.sent(),console.log("after hb call"),[2,t.transition(Vt())];case 4:return(r=i.sent())instanceof Error&&"Aborted"===r.message?[2]:r instanceof B?[2,t.transition(Jt(r))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(Wt())];case 7:return[2]}}))}))}))),r}return t(n,e),n}(et),tn=new Ye("HEARTBEAT_STOPPED");tn.on(Ht.type,(function(e,t){return tn.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),tn.on(qt.type,(function(e,t){return tn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Qt(t.payload.channels,t.payload.groups)])})),tn.on(Lt.type,(function(e,t){return sn.with({channels:e.channels,groups:e.groups})})),tn.on(Bt.type,(function(e,t){return tn.with({channels:e.channels,groups:e.groups},[Qt(e.channels,e.groups)])})),tn.on(zt.type,(function(e,t){return an.with(void 0,[Qt(e.channels,e.groups)])}));var nn=new Ye("HEARTBEATCOOLDOWN");nn.onEnter((function(){return Yt()})),nn.onExit((function(){return Yt.cancel})),nn.on(Xt.type,(function(e,t){return sn.with({channels:e.channels,groups:e.groups})})),nn.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),nn.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Qt(t.payload.channels,t.payload.groups)])})),nn.on(Bt.type,(function(e){return tn.with({channels:e.channels,groups:e.groups},[Qt(e.channels,e.groups)])})),nn.on(zt.type,(function(e,t){return an.with(void 0,[Qt(e.channels,e.groups)])}));var rn=new Ye("HEARTBEAT_FAILED");rn.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),rn.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Qt(t.payload.channels,t.payload.groups)])})),rn.on(Lt.type,(function(e,t){return sn.with({channels:e.channels,groups:e.groups})})),rn.on(Bt.type,(function(e,t){return tn.with({channels:e.channels,groups:e.groups},[Qt(e.channels,e.groups)])})),rn.on(zt.type,(function(e,t){return an.with(void 0,[Qt(e.channels,e.groups)])}));var on=new Ye("HEARBEAT_RECONNECTING");on.onEnter((function(e){return Zt(e)})),on.onExit((function(){return Zt.cancel})),on.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),on.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Qt(t.payload.channels,t.payload.groups)])})),on.on(Bt.type,(function(e,t){tn.with({channels:e.channels,groups:e.groups},[Qt(e.channels,e.groups)])})),on.on(Vt.type,(function(e,t){return nn.with({channels:e.channels,groups:e.groups})})),on.on(Jt.type,(function(e,t){return on.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),on.on(Wt.type,(function(e,t){return rn.with({channels:e.channels,groups:e.groups})})),on.on(zt.type,(function(e,t){return an.with(void 0,[Qt(e.channels,e.groups)])}));var sn=new Ye("HEARTBEATING");sn.onEnter((function(e){return $t(e.channels,e.groups)})),sn.on(Vt.type,(function(e,t){return nn.with({channels:e.channels,groups:e.groups})})),sn.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),sn.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Qt(t.payload.channels,t.payload.groups)])})),sn.on(Jt.type,(function(e,t){return on.with(n(n({},e),{attempts:0,reason:t.payload}))})),sn.on(Bt.type,(function(e){return tn.with({channels:e.channels,groups:e.groups},[Qt(e.channels,e.groups)])})),sn.on(zt.type,(function(e,t){return an.with(void 0,[Qt(e.channels,e.groups)])}));var an=new Ye("HEARTBEAT_INACTIVE");an.on(Ht.type,(function(e,t){return sn.with({channels:t.payload.channels,groups:t.payload.groups})})),an.on(qt.type,(function(e,t){return an.with()}));var un=function(){function e(e){var t=this;this.engine=new Ze,this.channels=[],this.groups=[],this.dispatcher=new en(this.engine,e),this.dependencies=e,this._unsubscribeEngine=this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(an,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.join=function(e){var t=e.channels,n=e.groups;this.channels=u(u([],a(this.channels),!1),a(null!=t?t:[]),!1),this.groups=u(u([],a(this.groups),!1),a(null!=n?n:[]),!1),this.engine.transition(Ht(this.channels.slice(0),this.groups.slice(0)))},e.prototype.leave=function(e){var t=this,n=e.channels,r=e.groups;this.dependencies.presenceState&&(null==n||n.forEach((function(e){return delete t.dependencies.presenceState[e]})),null==r||r.forEach((function(e){return delete t.dependencies.presenceState[e]}))),this.engine.transition(qt(null!=n?n:[],null!=r?r:[]))},e.prototype.leaveAll=function(){this.engine.transition(zt())},e.prototype.dispose=function(){this._unsubscribeEngine(),this.dispatcher.dispose()},e}(),cn=function(){function e(){}return e.LinearRetryPolicy=function(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry:function(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay:function(e){return 1e3*this.delay}}},e.ExponentialRetryPolicy=function(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry:function(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay:function(e){var t=1e3*Math.trunc(Math.pow(2,e))+1e3*Math.random();return t>15e4?15e4:t}}},e}(),ln=function(){function e(e){var t=this,r=e.networking,i=e.cbor,o=new y({setup:e});this._config=o;var c=new E({config:o}),l=e.cryptography;r.init(o);var p=new L(o,i);this._tokenManager=p;var h=new U({maximumSamplesCount:6e4});this._telemetryManager=h;var f={config:o,networking:r,crypto:c,cryptography:l,tokenManager:p,telemetryManager:h,PubNubFile:e.PubNubFile};this.File=e.PubNubFile,this.encryptFile=function(e,n){return l.encryptFile(e,n,t.File)},this.decryptFile=function(e,n){return l.decryptFile(e,n,t.File)};var d=W.bind(this,f,Je),g=W.bind(this,f,ie),v=W.bind(this,f,se),m=W.bind(this,f,ue),b=W.bind(this,f,We),_=new F;if(this._listenerManager=_,this.iAmHere=W.bind(this,f,se),this.iAmAway=W.bind(this,f,ie),this.setPresenceState=W.bind(this,f,ue),this.handshake=W.bind(this,f,Xe),this.receiveMessages=W.bind(this,f,$e),!0===o.enableEventEngine){if(o.maintainPresenceState&&(this.presenceState={},this.setState=function(e){var n,r;return null===(n=e.channels)||void 0===n||n.forEach((function(n){return t.presenceState[n]=e.state})),null===(r=e.channelGroups)||void 0===r||r.forEach((function(n){return t.presenceState[n]=e.state})),t.setPresenceState({channels:e.channels,channelGroups:e.channelGroups,state:t.presenceState})}),o.getHeartbeatInterval()){var O=new un({heartbeat:this.iAmHere,leave:this.iAmAway,heartbeatDelay:function(){return new Promise((function(e){return setTimeout(e,1e3*f.config.getHeartbeatInterval())}))},retryDelay:function(e){return new Promise((function(t){return setTimeout(t,e)}))},config:f.config,presenceState:this.presenceState});this.presenceEventEngine=O,this.join=this.presenceEventEngine.join.bind(O),this.leave=this.presenceEventEngine.leave.bind(O),this.leaveAll=this.presenceEventEngine.leaveAll.bind(O)}var P=new Ft({handshake:this.handshake,receiveEvents:this.receiveMessages,delay:function(e){return new Promise((function(t){return setTimeout(t,e)}))},join:this.join,leave:this.leave,leaveAll:this.leaveAll,presenceState:this.presenceState,config:f.config,emitEvents:function(e){var t,n;try{for(var r=s(e),i=r.next();!i.done;i=r.next()){var o=i.value;_.announceMessage(o)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}},emitStatus:function(e){_.announceStatus(e)}});this.subscribe=P.subscribe.bind(P),this.unsubscribe=P.unsubscribe.bind(P),this.unsubscribeAll=P.unsubscribeAll.bind(P),this.reconnect=P.reconnect.bind(P),this.disconnect=P.disconnect.bind(P),this.eventEngine=P}else{var S=new M({timeEndpoint:d,leaveEndpoint:g,heartbeatEndpoint:v,setStateEndpoint:m,subscribeEndpoint:b,crypto:f.crypto,config:f.config,listenerManager:_,getFileUrl:function(e){return ve(f,e)}});this.subscribe=S.adaptSubscribeChange.bind(S),this.unsubscribe=S.adaptUnsubscribeChange.bind(S),this.disconnect=S.disconnect.bind(S),this.reconnect=S.reconnect.bind(S),this.unsubscribeAll=S.unsubscribeAll.bind(S),this.getSubscribedChannels=S.getSubscribedChannels.bind(S),this.getSubscribedChannelGroups=S.getSubscribedChannelGroups.bind(S),this.setState=S.adaptStateChange.bind(S),this.presence=S.adaptPresenceChange.bind(S),this.destroy=function(e){S.unsubscribeAll(e),S.disconnect()}}this.addListener=_.addListener.bind(_),this.removeListener=_.removeListener.bind(_),this.removeAllListeners=_.removeAllListeners.bind(_),this.parseToken=p.parseToken.bind(p),this.setToken=p.setToken.bind(p),this.getToken=p.getToken.bind(p),this.channelGroups={listGroups:W.bind(this,f,Y),listChannels:W.bind(this,f,Z),addChannels:W.bind(this,f,X),removeChannels:W.bind(this,f,$),deleteGroup:W.bind(this,f,Q)},this.push={addChannels:W.bind(this,f,ee),removeChannels:W.bind(this,f,te),deleteDevice:W.bind(this,f,re),listChannels:W.bind(this,f,ne)},this.hereNow=W.bind(this,f,ce),this.whereNow=W.bind(this,f,oe),this.getState=W.bind(this,f,ae),this.grant=W.bind(this,f,je),this.grantToken=W.bind(this,f,Ie),this.audit=W.bind(this,f,Me),this.revokeToken=W.bind(this,f,Ge),this.publish=W.bind(this,f,Fe),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=W.bind(this,f,Le),this.history=W.bind(this,f,He),this.deleteMessages=W.bind(this,f,qe),this.messageCounts=W.bind(this,f,ze),this.fetchMessages=W.bind(this,f,Ve),this.addMessageAction=W.bind(this,f,le),this.removeMessageAction=W.bind(this,f,pe),this.getMessageActions=W.bind(this,f,he),this.listFiles=W.bind(this,f,fe);var w=W.bind(this,f,de);this.publishFile=W.bind(this,f,ye),this.sendFile=ge({generateUploadUrl:w,publishFile:this.publishFile,modules:f}),this.getFileUrl=function(e){return ve(f,e)},this.downloadFile=W.bind(this,f,me),this.deleteFile=W.bind(this,f,be),this.objects={getAllUUIDMetadata:W.bind(this,f,_e),getUUIDMetadata:W.bind(this,f,Oe),setUUIDMetadata:W.bind(this,f,Pe),removeUUIDMetadata:W.bind(this,f,Se),getAllChannelMetadata:W.bind(this,f,we),getChannelMetadata:W.bind(this,f,Ee),setChannelMetadata:W.bind(this,f,Te),removeChannelMetadata:W.bind(this,f,ke),getChannelMembers:W.bind(this,f,Ce),setChannelMembers:function(e){for(var r=[],i=1;i=this._config.origin.length&&(this._currentSubDomain=0);var t=this._config.origin[this._currentSubDomain];return"".concat(e).concat(t)},e.prototype.hasModule=function(e){return e in this._modules},e.prototype.shiftStandardOrigin=function(){return this._standardOrigin=this.nextOrigin(),this._standardOrigin},e.prototype.getStandardOrigin=function(){return this._standardOrigin},e.prototype.POSTFILE=function(e,t,n){return this._modules.postfile(e,t,n)},e.prototype.GETFILE=function(e,t,n){return this._modules.getfile(e,t,n)},e.prototype.POST=function(e,t,n,r){return this._modules.post(e,t,n,r)},e.prototype.PATCH=function(e,t,n,r){return this._modules.patch(e,t,n,r)},e.prototype.GET=function(e,t,n){return this._modules.get(e,t,n)},e.prototype.DELETE=function(e,t,n){return this._modules.del(e,t,n)},e.prototype._detectErrorCategory=function(e){if("ENOTFOUND"===e.code)return R.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return R.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return R.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return R.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return R.PNNetworkIssuesCategory;if(e.timeout)return R.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return R.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return R.PNBadRequestCategory;if(e.response.forbidden)return R.PNAccessDeniedCategory}return R.PNUnknownCategory},e}();function hn(e){var t=function(e){return e&&"object"==typeof e&&e.constructor===Object};if(!t(e))return e;var n={};return Object.keys(e).forEach((function(r){var i=function(e){return"string"==typeof e||e instanceof String}(r),o=r,s=e[r];Array.isArray(r)||i&&r.indexOf(",")>=0?o=(i?r.split(","):r).reduce((function(e,t){return e+=String.fromCharCode(t)}),""):(function(e){return"number"==typeof e&&isFinite(e)}(r)||i&&!isNaN(r))&&(o=String.fromCharCode(i?parseInt(r,10):10));n[o]=t(s)?hn(s):s})),n}var fn=function(){function e(e,t){this._base64ToBinary=t,this._decode=e}return e.prototype.decodeToken=function(e){var t="";e.length%4==3?t="=":e.length%4==2&&(t="==");var n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,r=this._decode(this._base64ToBinary(n));if("object"==typeof r)return r},e}(),dn={exports:{}},yn={exports:{}};!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;is.depthLimit)return void Sn(vn,e,t,i);if(void 0!==s.edgesLimit&&n+1>s.edgesLimit)return void Sn(vn,e,t,i);if(r.push(e),Array.isArray(e))for(a=0;at?1:0}function Tn(e,t,n,r){void 0===r&&(r=On());var i,o=kn(e,"",0,[],void 0,0,r)||e;try{i=0===_n.length?JSON.stringify(o,t,n):JSON.stringify(o,Cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==bn.length;){var s=bn.pop();4===s.length?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return i}function kn(e,t,n,r,i,o,s){var a;if(o+=1,"object"==typeof e&&null!==e){for(a=0;as.depthLimit)return void Sn(vn,e,t,i);if(void 0!==s.edgesLimit&&n+1>s.edgesLimit)return void Sn(vn,e,t,i);if(r.push(e),Array.isArray(e))for(a=0;a0)for(var r=0;r<_n.length;r++){var i=_n[r];if(i[1]===t&&i[0]===n){n=i[2],_n.splice(r,1);break}}return e.call(this,t,n)}}var Nn=String.prototype.replace,An=/%20/g,Rn="RFC3986",Mn={default:Rn,formatters:{RFC1738:function(e){return Nn.call(e,An,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:Rn},jn=Mn,Un=Object.prototype.hasOwnProperty,xn=Array.isArray,Dn=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),In=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r1;){var t=e.pop(),n=t.obj[t.prop];if(xn(n)){for(var r=[],i=0;i=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||i===jn.RFC1738&&(40===u||41===u)?s+=o.charAt(a):u<128?s+=Dn[u]:u<2048?s+=Dn[192|u>>6]+Dn[128|63&u]:u<55296||u>=57344?s+=Dn[224|u>>12]+Dn[128|u>>6&63]+Dn[128|63&u]:(a+=1,u=65536+((1023&u)<<10|1023&o.charCodeAt(a)),s+=Dn[240|u>>18]+Dn[128|u>>12&63]+Dn[128|u>>6&63]+Dn[128|63&u])}return s},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(xn(e)){for(var n=[],r=0;r0?g.join(",")||null:void 0}];else if(Hn(a))O=a;else{var S=Object.keys(g);O=u?S.sort(u):S}for(var w=0;w-1?e.split(","):e},rr=function(e,t,n,r){if(e){var i=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/g,s=n.depth>0&&/(\[[^[\]]*])/.exec(i),a=s?i.slice(0,s.index):i,u=[];if(a){if(!n.plainObjects&&Yn.call(Object.prototype,a)&&!n.allowPrototypes)return;u.push(a)}for(var c=0;n.depth>0&&null!==(s=o.exec(i))&&c=0;--o){var s,a=e[o];if("[]"===a&&n.parseArrays)s=[].concat(i);else{s=n.plainObjects?Object.create(null):{};var u="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,c=parseInt(u,10);n.parseArrays||""!==u?!isNaN(c)&&a!==u&&String(c)===u&&c>=0&&n.parseArrays&&c<=n.arrayLimit?(s=[])[c]=i:"__proto__"!==u&&(s[u]=i):s={0:i}}i=s}return i}(u,t,n,r)}},ir=function(e,t){var n,r=e,i=function(e){if(!e)return Xn;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Xn.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=Fn.default;if(void 0!==e.format){if(!Ln.call(Fn.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=Fn.formatters[n],i=Xn.filter;return("function"==typeof e.filter||Hn(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Xn.addQueryPrefix,allowDots:void 0===e.allowDots?Xn.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Xn.charsetSentinel,delimiter:void 0===e.delimiter?Xn.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Xn.encode,encoder:"function"==typeof e.encoder?e.encoder:Xn.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Xn.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Xn.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Xn.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Xn.strictNullHandling}}(t);"function"==typeof i.filter?r=(0,i.filter)("",r):Hn(i.filter)&&(n=i.filter);var o,s=[];if("object"!=typeof r||null===r)return"";o=t&&t.arrayFormat in Bn?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=Bn[o];n||(n=Object.keys(r)),i.sort&&n.sort(i.sort);for(var u=0;u0?p+l:""},or={formats:Mn,parse:function(e,t){var n=function(e){if(!e)return er;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?er.charset:e.charset;return{allowDots:void 0===e.allowDots?er.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:er.allowPrototypes,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:er.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:er.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:er.comma,decoder:"function"==typeof e.decoder?e.decoder:er.decoder,delimiter:"string"==typeof e.delimiter||Qn.isRegExp(e.delimiter)?e.delimiter:er.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:er.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:er.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:er.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:er.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:er.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var r="string"==typeof e?function(e,t){var n,r={},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,o=t.parameterLimit===1/0?void 0:t.parameterLimit,s=i.split(t.delimiter,o),a=-1,u=t.charset;if(t.charsetSentinel)for(n=0;n-1&&(l=Zn(l)?[l]:l),Yn.call(r,c)?r[c]=Qn.combine(r[c],l):r[c]=l}return r}(e,n):e,i=n.plainObjects?Object.create(null):{},o=Object.keys(r),s=0;s=this._maxRetries)return!1;if(this._retryCallback)try{var n=this._retryCallback(e,t);if(!0===n)return!0;if(!1===n)return!1}catch(e){console.error(e)}if(t&&t.status&&fr.has(t.status))return!0;if(e){if(e.code&&hr.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},pr.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this.timedoutError=null,this._end()},pr.prototype.then=function(e,t){var n=this;if(!this._fullfilledPromise){var r=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise((function(e,t){r.on("abort",(function(){if(!(n._maxRetries&&n._maxRetries>n._retries))if(n.timedout&&n.timedoutError)t(n.timedoutError);else{var e=new Error("Aborted");e.code="ABORTED",e.status=n.status,e.method=n.method,e.url=n.url,t(e)}})),r.end((function(n,r){n?t(n):e(r)}))}))}return this._fullfilledPromise.then(e,t)},pr.prototype.catch=function(e){return this.then(void 0,e)},pr.prototype.use=function(e){return e(this),this},pr.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},pr.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},pr.prototype.get=function(e){return this._header[e.toLowerCase()]},pr.prototype.getHeader=pr.prototype.get,pr.prototype.set=function(e,t){if(cr(e)){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&this.set(n,e[n]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},pr.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},pr.prototype.field=function(e,t){if(null==e)throw new Error(".field(name, val) name can not be empty");if(this._data)throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");if(cr(e)){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&this.field(n,e[n]);return this}if(Array.isArray(t)){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&this.field(e,t[r]);return this}if(null==t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=String(t)),this._getFormData().append(e,t),this},pr.prototype.abort=function(){return this._aborted||(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort")),this},pr.prototype._auth=function(e,t,n,r){switch(n.type){case"basic":this.set("Authorization","Basic ".concat(r("".concat(e,":").concat(t))));break;case"auto":this.username=e,this.password=t;break;case"bearer":this.set("Authorization","Bearer ".concat(e))}return this},pr.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},pr.prototype.redirects=function(e){return this._maxRedirects=e,this},pr.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},pr.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},pr.prototype.send=function(e){var t=cr(e),n=this._header["content-type"];if(this._formData)throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");if(t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw new Error("Can't merge these send calls");if(t&&cr(this._data))for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(this._data[r]=e[r]);else"string"==typeof e?(n||this.type("form"),(n=this._header["content-type"])&&(n=n.toLowerCase().trim()),this._data="application/x-www-form-urlencoded"===n?this._data?"".concat(this._data,"&").concat(e):e:(this._data||"")+e):this._data=e;return!t||this._isHost(e)||n||this.type("json"),this},pr.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},pr.prototype._finalizeQueryString=function(){var e=this._query.join("&");if(e&&(this.url+=(this.url.includes("?")?"&":"?")+e),this._query.length=0,this._sort){var t=this.url.indexOf("?");if(t>=0){var n=this.url.slice(t+1).split("&");"function"==typeof this._sort?n.sort(this._sort):n.sort(),this.url=this.url.slice(0,t)+"?"+n.join("&")}}},pr.prototype._appendQueryString=function(){console.warn("Unsupported")},pr.prototype._timeoutError=function(e,t,n){if(!this._aborted){var r=new Error("".concat(e+t,"ms exceeded"));r.timeout=t,r.code="ECONNABORTED",r.errno=n,this.timedout=!0,this.timedoutError=r,this.abort(),this.callback(r)}},pr.prototype._setTimeouts=function(){var e=this;this._timeout&&!this._timer&&(this._timer=setTimeout((function(){e._timeoutError("Timeout of ",e._timeout,"ETIME")}),this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout((function(){e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")}),this._responseTimeout))};var dr={};function yr(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return gr(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return gr(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function gr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0||e instanceof Object)?t(e):null)},m.prototype.toError=function(){var e=this.req,t=e.method,n=e.url,r="cannot ".concat(t," ").concat(n," (").concat(this.status,")"),i=new Error(r);return i.status=this.status,i.method=t,i.url=n,i},h.Response=m,i(b.prototype),a(b.prototype),b.prototype.type=function(e){return this.set("Content-Type",h.types[e]||e),this},b.prototype.accept=function(e){return this.set("Accept",h.types[e]||e),this},b.prototype.auth=function(e,t,r){1===arguments.length&&(t=""),"object"===n(t)&&null!==t&&(r=t,t=""),r||(r={type:"function"==typeof btoa?"basic":"auto"});var i=function(e){if("function"==typeof btoa)return btoa(e);throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(e,t,r,i)},b.prototype.query=function(e){return"string"!=typeof e&&(e=d(e)),e&&this._query.push(e),this},b.prototype.attach=function(e,t,n){if(t){if(this._data)throw new Error("superagent can't mix .send() and .attach()");this._getFormData().append(e,t,n||t.name)}return this},b.prototype._getFormData=function(){return this._formData||(this._formData=new r.FormData),this._formData},b.prototype.callback=function(e,t){if(this._shouldRetry(e,t))return this._retry();var n=this._callback;this.clearTimeout(),e&&(this._maxRetries&&(e.retries=this._retries-1),this.emit("error",e)),n(e,t)},b.prototype.crossDomainError=function(){var e=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");e.crossDomain=!0,e.status=this.status,e.method=this.method,e.url=this.url,this.callback(e)},b.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},b.prototype.ca=b.prototype.agent,b.prototype.buffer=b.prototype.ca,b.prototype.write=function(){throw new Error("Streaming is not supported in browser version of superagent")},b.prototype.pipe=b.prototype.write,b.prototype._isHost=function(e){return e&&"object"===n(e)&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},b.prototype.end=function(e){this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=e||p,this._finalizeQueryString(),this._end()},b.prototype._setUploadTimeout=function(){var e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((function(){e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},b.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));var e=this;this.xhr=h.getXHR();var t=this.xhr,n=this._formData||this._data;this._setTimeouts(),t.onreadystatechange=function(){var n=t.readyState;if(n>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4===n){var r;try{r=t.status}catch(e){r=0}if(!r){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}};var r=function(t,n){n.total>0&&(n.percent=n.loaded/n.total*100,100===n.percent&&clearTimeout(e._uploadTimeoutTimer)),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{t.addEventListener("progress",r.bind(null,"download")),t.upload&&t.upload.addEventListener("progress",r.bind(null,"upload"))}catch(e){}t.upload&&this._setUploadTimeout();try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!==this.method&&"HEAD"!==this.method&&"string"!=typeof n&&!this._isHost(n)){var i=this._header["content-type"],o=this._serializer||h.serialize[i?i.split(";")[0]:""];!o&&v(i)&&(o=h.serialize["application/json"]),o&&(n=o(n))}for(var s in this.header)null!==this.header[s]&&Object.prototype.hasOwnProperty.call(this.header,s)&&t.setRequestHeader(s,this.header[s]);this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send(void 0===n?null:n)},h.agent=function(){return new l},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach((function(e){l.prototype[e.toLowerCase()]=function(t,n){var r=new h.Request(e,t);return this._setDefaults(r),n&&r.end(n),r}})),l.prototype.del=l.prototype.delete,h.get=function(e,t,n){var r=h("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},h.head=function(e,t,n){var r=h("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},h.options=function(e,t,n){var r=h("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},h.del=_,h.delete=_,h.patch=function(e,t,n){var r=h("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},h.post=function(e,t,n){var r=h("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},h.put=function(e,t,n){var r=h("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}}(dn,dn.exports);var wr=dn.exports;function Er(e){var t=(new Date).getTime(),n=(new Date).toISOString(),r=console&&console.log?console:window&&window.console&&window.console.log?window.console:console;r.log("<<<<<"),r.log("[".concat(n,"]"),"\n",e.url,"\n",e.qs),r.log("-----"),e.on("response",(function(n){var i=(new Date).getTime()-t,o=(new Date).toISOString();r.log(">>>>>>"),r.log("[".concat(o," / ").concat(i,"]"),"\n",e.url,"\n",e.qs,"\n",n.text),r.log("-----")}))}function Tr(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(Er)),this._config.proxy&&this._modules.proxy&&(e=this._modules.proxy.call(this,e)),this._config.keepAlive&&this._modules.keepAlive&&(e=this._modules.keepAlive(e));var i=e;if(t.abortSignal)var o=t.abortSignal.subscribe((function(){i.abort(),o()}));return!0===t.forceBuffered?i="undefined"==typeof Blob?i.buffer().responseType("arraybuffer"):i.responseType("arraybuffer"):!1===t.forceBuffered&&(i=i.buffer(!1)),(i=i.timeout(t.timeout)).on("abort",(function(){return n({category:R.PNUnknownCategory,error:!0,operation:t.operation,errorData:new Error("Aborted")},null)})),i.end((function(e,i){var o,s={};if(s.error=null!==e,s.operation=t.operation,i&&i.status&&(s.statusCode=i.status),e){if(e.response&&e.response.text&&!r._config.logVerbosity)try{s.errorData=JSON.parse(e.response.text)}catch(t){s.errorData=e}else s.errorData=e;return s.category=r._detectErrorCategory(e),n(s,null)}if(t.ignoreBody)o={headers:i.headers,redirects:i.redirects,response:i};else try{o=JSON.parse(i.text)}catch(e){return s.errorData=i,s.error=!0,n(s,null)}return o.error&&1===o.error&&o.status&&o.message&&o.service?(s.errorData=o,s.statusCode=o.status,s.error=!0,s.category=r._detectErrorCategory(s),n(s,null)):(o.error&&o.error.message&&(s.errorData=o.error),n(s,o))})),i}function kr(e,t,n){return i(this,void 0,void 0,(function(){var r;return o(this,(function(i){switch(i.label){case 0:return r=wr.post(e),t.forEach((function(e){var t=e.key,n=e.value;r=r.field(t,n)})),r.attach("file",n,{contentType:"application/octet-stream"}),[4,r];case 1:return[2,i.sent()]}}))}))}function Cr(e,t,n){var r=wr.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return Tr.call(this,r,t,n)}function Nr(e,t,n){var r=wr.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return Tr.call(this,r,t,n)}function Ar(e,t,n,r){var i=wr.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return Tr.call(this,i,n,r)}function Rr(e,t,n,r){var i=wr.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return Tr.call(this,i,n,r)}function Mr(e,t,n){var r=wr.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return Tr.call(this,r,t,n)}function jr(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}var Ur,xr=function(){function e(){}return Object.defineProperty(e.prototype,"algo",{get:function(){return"aes-256-cbc"},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e,t){return i(this,void 0,void 0,(function(){var n;return o(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.encryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.encryptString(n,t)];throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer")}}))}))},e.prototype.decrypt=function(e,t){return i(this,void 0,void 0,(function(){var n;return o(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.decryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.decryptString(n,t)];throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer")}}))}))},e.prototype.encryptFile=function(e,t,n){return i(this,void 0,void 0,(function(){var r,i,s;return o(this,(function(o){switch(o.label){case 0:return[4,this.getKey(e)];case 1:return r=o.sent(),[4,t.toArrayBuffer()];case 2:return i=o.sent(),[4,this.encryptArrayBuffer(r,i)];case 3:return s=o.sent(),[2,n.create({name:t.name,mimeType:"application/octet-stream",data:s})]}}))}))},e.prototype.decryptFile=function(e,t,n){return i(this,void 0,void 0,(function(){var r,i,s;return o(this,(function(o){switch(o.label){case 0:return[4,this.getKey(e)];case 1:return r=o.sent(),[4,t.toArrayBuffer()];case 2:return i=o.sent(),[4,this.decryptArrayBuffer(r,i)];case 3:return s=o.sent(),[2,n.create({name:t.name,data:s})]}}))}))},e.prototype.getKey=function(e){return i(this,void 0,void 0,(function(){var t,n,r;return o(this,(function(i){switch(i.label){case 0:return t=Buffer.from(e),[4,crypto.subtle.digest("SHA-256",t.buffer)];case 1:return n=i.sent(),r=Buffer.from(Buffer.from(n).toString("hex").slice(0,32),"utf8").buffer,[2,crypto.subtle.importKey("raw",r,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encryptArrayBuffer=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i;return o(this,(function(o){switch(o.label){case 0:return n=crypto.getRandomValues(new Uint8Array(16)),r=jr,i=[n.buffer],[4,crypto.subtle.encrypt({name:"AES-CBC",iv:n},e,t)];case 1:return[2,r.apply(void 0,i.concat([o.sent()]))]}}))}))},e.prototype.decryptArrayBuffer=function(e,t){return i(this,void 0,void 0,(function(){var n;return o(this,(function(r){return n=t.slice(0,16),[2,crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,t.slice(16))]}))}))},e.prototype.encryptString=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i,s;return o(this,(function(o){switch(o.label){case 0:return n=crypto.getRandomValues(new Uint8Array(16)),r=Buffer.from(t).buffer,[4,crypto.subtle.encrypt({name:"AES-CBC",iv:n},e,r)];case 1:return i=o.sent(),s=jr(n.buffer,i),[2,Buffer.from(s).toString("utf8")]}}))}))},e.prototype.decryptString=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i,s;return o(this,(function(o){switch(o.label){case 0:return n=Buffer.from(t),r=n.slice(0,16),i=n.slice(16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:r},e,i)];case 1:return s=o.sent(),[2,Buffer.from(s).toString("utf8")]}}))}))},e.IV_LENGTH=16,e}(),Dr=(Ur=function(){function e(e){if(e instanceof File)this.data=e,this.name=this.data.name,this.mimeType=this.data.type;else if(e.data){var t=e.data;this.data=new File([t],e.name,{type:e.mimeType}),this.name=e.name,e.mimeType&&(this.mimeType=e.mimeType)}if(void 0===this.data)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===this.name)throw new Error("Couldn't guess filename out of the options. Please provide one.")}return e.create=function(e){return new this(e)},e.prototype.toBuffer=function(){return i(this,void 0,void 0,(function(){return o(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toStream=function(){return i(this,void 0,void 0,(function(){return o(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toFileUri=function(){return i(this,void 0,void 0,(function(){return o(this,(function(e){throw new Error("This feature is only supported in react native environments.")}))}))},e.prototype.toBlob=function(){return i(this,void 0,void 0,(function(){return o(this,(function(e){return[2,this.data]}))}))},e.prototype.toArrayBuffer=function(){return i(this,void 0,void 0,(function(){var e=this;return o(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if(r.result instanceof ArrayBuffer)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsArrayBuffer(e.data)}))]}))}))},e.prototype.toString=function(){return i(this,void 0,void 0,(function(){var e=this;return o(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if("string"==typeof r.result)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsBinaryString(e.data)}))]}))}))},e.prototype.toFile=function(){return i(this,void 0,void 0,(function(){return o(this,(function(e){return[2,this.data]}))}))},e}(),Ur.supportsFile="undefined"!=typeof File,Ur.supportsBlob="undefined"!=typeof Blob,Ur.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,Ur.supportsBuffer=!1,Ur.supportsStream=!1,Ur.supportsString=!0,Ur.supportsEncryptFile=!0,Ur.supportsFileUri=!1,Ur);function Ir(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Gr=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,i=void 0===r||r;return t.sdkFamily="Web",t.networking=new pn({del:Mr,get:Nr,post:Ar,patch:Rr,sendBeacon:Ir,getfile:Cr,postfile:kr}),t.cbor=new fn((function(e){return hn(p.decode(e))}),g),t.PubNubFile=Dr,t.cryptography=new xr,n=e.call(this,t)||this,i&&(window.addEventListener("offline",(function(){n.networkDownDetected()})),window.addEventListener("online",(function(){n.networkUpDetected()}))),n}return t(n,e),n}(ln);return Gr})); +!function(e,t){!function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function r(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function o(e,t){var r=n[t||"all"];return r&&r.test(e)||!1}r.isUUID=o,r.VERSION=t,e.uuid=r,e.isUUID=o}(t),null!==e&&(e.exports=t.uuid)}(h,h.exports);var d=h.exports,y=function(){return d.uuid?d.uuid():d()},g=function(){function e(e){var t,n,r,o=e.setup;if(this._PNSDKSuffix={},this.instanceId="pn-".concat(y()),this.secretKey=o.secretKey||o.secret_key,this.subscribeKey=o.subscribeKey||o.subscribe_key,this.publishKey=o.publishKey||o.publish_key,this.sdkName=o.sdkName,this.sdkFamily=o.sdkFamily,this.partnerId=o.partnerId,this.setAuthKey(o.authKey),this.cryptoModule=o.cryptoModule,this.setFilterExpression(o.filterExpression),"string"!=typeof o.origin&&!Array.isArray(o.origin)&&void 0!==o.origin)throw new Error("Origin must be either undefined, a string or a list of strings.");if(this.origin=o.origin||Array.from({length:20},(function(e,t){return"ps".concat(t+1,".pndsn.com")})),this.secure=o.ssl||!1,this.restore=o.restore||!1,this.proxy=o.proxy,this.keepAlive=o.keepAlive,this.keepAliveSettings=o.keepAliveSettings,this.autoNetworkDetection=o.autoNetworkDetection||!1,this.dedupeOnSubscribe=o.dedupeOnSubscribe||!1,this.maximumCacheSize=o.maximumCacheSize||100,this.customEncrypt=o.customEncrypt,this.customDecrypt=o.customDecrypt,this.fileUploadPublishRetryLimit=null!==(t=o.fileUploadPublishRetryLimit)&&void 0!==t?t:5,this.useRandomIVs=null===(n=o.useRandomIVs)||void 0===n||n,this.enableSubscribeBeta=null!==(r=o.enableSubscribeBeta)&&void 0!==r&&r,"undefined"!=typeof location&&"https:"===location.protocol&&(this.secure=!0),this.logVerbosity=o.logVerbosity||!1,this.suppressLeaveEvents=o.suppressLeaveEvents||!1,this.announceFailedHeartbeats=o.announceFailedHeartbeats||!0,this.announceSuccessfulHeartbeats=o.announceSuccessfulHeartbeats||!1,this.useInstanceId=o.useInstanceId||!1,this.useRequestId=o.useRequestId||!1,this.requestMessageCountThreshold=o.requestMessageCountThreshold,this.setTransactionTimeout(o.transactionalRequestTimeout||15e3),this.setSubscribeTimeout(o.subscribeRequestTimeout||31e4),this.setSendBeaconConfig(o.useSendBeacon||!0),o.presenceTimeout?this.setPresenceTimeout(o.presenceTimeout):this._presenceTimeout=300,null!=o.heartbeatInterval&&this.setHeartbeatInterval(o.heartbeatInterval),"string"==typeof o.userId){if("string"==typeof o.uuid)throw new Error("Only one of the following configuration options has to be provided: `uuid` or `userId`");this.setUserId(o.userId)}else{if("string"!=typeof o.uuid)throw new Error("One of the following configuration options has to be provided: `uuid` or `userId`");this.setUUID(o.uuid)}this.setCipherKey(o.cipherKey,o)}return e.prototype.getAuthKey=function(){return this.authKey},e.prototype.setAuthKey=function(e){return this.authKey=e,this},e.prototype.setCipherKey=function(e,t,n){var r;return this.cipherKey=e,this.cipherKey&&(this.cryptoModule=null!==(r=t.cryptoModule)&&void 0!==r?r:t.initCryptoModule({cipherKey:this.cipherKey,useRandomIVs:this.useRandomIVs}),n&&(n.cryptoModule=this.cryptoModule)),this},e.prototype.getUUID=function(){return this.UUID},e.prototype.setUUID=function(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing uuid parameter. Provide a valid string uuid");return this.UUID=e,this},e.prototype.getUserId=function(){return this.UUID},e.prototype.setUserId=function(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");return this.UUID=e,this},e.prototype.getFilterExpression=function(){return this.filterExpression},e.prototype.setFilterExpression=function(e){return this.filterExpression=e,this},e.prototype.getPresenceTimeout=function(){return this._presenceTimeout},e.prototype.setPresenceTimeout=function(e){return e>=20?this._presenceTimeout=e:(this._presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",this._presenceTimeout)),this.setHeartbeatInterval(this._presenceTimeout/2-1),this},e.prototype.setProxy=function(e){this.proxy=e},e.prototype.getHeartbeatInterval=function(){return this._heartbeatInterval},e.prototype.setHeartbeatInterval=function(e){return this._heartbeatInterval=e,this},e.prototype.getSubscribeTimeout=function(){return this._subscribeRequestTimeout},e.prototype.setSubscribeTimeout=function(e){return this._subscribeRequestTimeout=e,this},e.prototype.getTransactionTimeout=function(){return this._transactionalRequestTimeout},e.prototype.setTransactionTimeout=function(e){return this._transactionalRequestTimeout=e,this},e.prototype.isSendBeaconEnabled=function(){return this._useSendBeacon},e.prototype.setSendBeaconConfig=function(e){return this._useSendBeacon=e,this},e.prototype.getVersion=function(){return"7.4.5"},e.prototype._addPnsdkSuffix=function(e,t){this._PNSDKSuffix[e]=t},e.prototype._getPnsdkSuffix=function(e){var t=this;return Object.keys(this._PNSDKSuffix).reduce((function(n,r){return n+e+t._PNSDKSuffix[r]}),"")},e}();function b(e){var t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),r=new ArrayBuffer(n),o=new Uint8Array(r),i=0;function a(){var e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error("Illegal character at ".concat(i,": ").concat(t.charAt(i-1)));return n}for(var s=0;s>4,h=(15&c)<<4|l>>2,d=(3&l)<<6|p>>0;o[s]=f,64!=l&&(o[s+1]=h),64!=p&&(o[s+2]=d)}return r}function v(e){for(var t,n="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=new Uint8Array(e),i=o.byteLength,a=i%3,s=i-a,u=0;u>18]+r[(258048&t)>>12]+r[(4032&t)>>6]+r[63&t];return 1==a?n+=r[(252&(t=o[s]))>>2]+r[(3&t)<<4]+"==":2==a&&(n+=r[(64512&(t=o[s]<<8|o[s+1]))>>10]+r[(1008&t)>>4]+r[(15&t)<<2]+"="),n}var m,_,S,O,P,w=w||function(e,t){var n={},r=n.lib={},o=function(){},i=r.Base={extend:function(e){o.prototype=this;var t=new o;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},a=r.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var o=0;o>>2]|=(n[o>>>2]>>>24-o%4*8&255)<<24-(r+o)%4*8;else if(65535>>2]=n[o>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new a.init(n,t/2)}},c=s.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new a.init(n,t)}},l=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},p=r.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,o=n.sigBytes,i=this.blockSize,s=o/(4*i);if(t=(s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0))*i,o=e.min(4*t,o),t){for(var u=0;uc;){var l;e:{l=u;for(var p=e.sqrt(l),f=2;f<=p;f++)if(!(l%f)){l=!1;break e}l=!0}l&&(8>c&&(i[c]=s(e.pow(u,.5))),a[c]=s(e.pow(u,1/3)),c++),u++}var h=[];o=o.SHA256=r.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],o=n[1],i=n[2],s=n[3],u=n[4],c=n[5],l=n[6],p=n[7],f=0;64>f;f++){if(16>f)h[f]=0|e[t+f];else{var d=h[f-15],y=h[f-2];h[f]=((d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3)+h[f-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+h[f-16]}d=p+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&l)+a[f]+h[f],y=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&o^r&i^o&i),p=l,l=c,c=u,u=s+d|0,s=i,i=o,o=r,r=d+y|0}n[0]=n[0]+r|0,n[1]=n[1]+o|0,n[2]=n[2]+i|0,n[3]=n[3]+s|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+l|0,n[7]=n[7]+p|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=e.floor(r/4294967296),n[15+(o+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=r._createHelper(o),t.HmacSHA256=r._createHmacHelper(o)}(Math),_=(m=w).enc.Utf8,m.algo.HMAC=m.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=_.parse(t));var n=e.blockSize,r=4*n;t.sigBytes>r&&(t=e.finalize(t)),t.clamp();for(var o=this._oKey=t.clone(),i=this._iKey=t.clone(),a=o.words,s=i.words,u=0;u>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;4>a&&o+.75*a>>6*(3-a)&63));if(t=r.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(r=n.charAt(64))&&-1!=(r=e.indexOf(r))&&(t=r);for(var r=[],o=0,i=0;i>>6-i%4*2;r[o>>>2]|=(a|s)<<24-o%4*8,o++}return O.create(r,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,r,o,i,a){return((e=e+(t&n|~t&r)+o+a)<>>32-i)+t}function n(e,t,n,r,o,i,a){return((e=e+(t&r|n&~r)+o+a)<>>32-i)+t}function r(e,t,n,r,o,i,a){return((e=e+(t^n^r)+o+a)<>>32-i)+t}function o(e,t,n,r,o,i,a){return((e=e+(n^(t|~r))+o+a)<>>32-i)+t}for(var i=w,a=(u=i.lib).WordArray,s=u.Hasher,u=i.algo,c=[],l=0;64>l;l++)c[l]=4294967296*e.abs(e.sin(l+1))|0;u=u.MD5=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var s=e[u=i+a];e[u]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8)}a=this._hash.words;var u=e[i+0],l=(s=e[i+1],e[i+2]),p=e[i+3],f=e[i+4],h=e[i+5],d=e[i+6],y=e[i+7],g=e[i+8],b=e[i+9],v=e[i+10],m=e[i+11],_=e[i+12],S=e[i+13],O=e[i+14],P=e[i+15],w=t(w=a[0],A=a[1],T=a[2],E=a[3],u,7,c[0]),E=t(E,w,A,T,s,12,c[1]),T=t(T,E,w,A,l,17,c[2]),A=t(A,T,E,w,p,22,c[3]);w=t(w,A,T,E,f,7,c[4]),E=t(E,w,A,T,h,12,c[5]),T=t(T,E,w,A,d,17,c[6]),A=t(A,T,E,w,y,22,c[7]),w=t(w,A,T,E,g,7,c[8]),E=t(E,w,A,T,b,12,c[9]),T=t(T,E,w,A,v,17,c[10]),A=t(A,T,E,w,m,22,c[11]),w=t(w,A,T,E,_,7,c[12]),E=t(E,w,A,T,S,12,c[13]),T=t(T,E,w,A,O,17,c[14]),w=n(w,A=t(A,T,E,w,P,22,c[15]),T,E,s,5,c[16]),E=n(E,w,A,T,d,9,c[17]),T=n(T,E,w,A,m,14,c[18]),A=n(A,T,E,w,u,20,c[19]),w=n(w,A,T,E,h,5,c[20]),E=n(E,w,A,T,v,9,c[21]),T=n(T,E,w,A,P,14,c[22]),A=n(A,T,E,w,f,20,c[23]),w=n(w,A,T,E,b,5,c[24]),E=n(E,w,A,T,O,9,c[25]),T=n(T,E,w,A,p,14,c[26]),A=n(A,T,E,w,g,20,c[27]),w=n(w,A,T,E,S,5,c[28]),E=n(E,w,A,T,l,9,c[29]),T=n(T,E,w,A,y,14,c[30]),w=r(w,A=n(A,T,E,w,_,20,c[31]),T,E,h,4,c[32]),E=r(E,w,A,T,g,11,c[33]),T=r(T,E,w,A,m,16,c[34]),A=r(A,T,E,w,O,23,c[35]),w=r(w,A,T,E,s,4,c[36]),E=r(E,w,A,T,f,11,c[37]),T=r(T,E,w,A,y,16,c[38]),A=r(A,T,E,w,v,23,c[39]),w=r(w,A,T,E,S,4,c[40]),E=r(E,w,A,T,u,11,c[41]),T=r(T,E,w,A,p,16,c[42]),A=r(A,T,E,w,d,23,c[43]),w=r(w,A,T,E,b,4,c[44]),E=r(E,w,A,T,_,11,c[45]),T=r(T,E,w,A,P,16,c[46]),w=o(w,A=r(A,T,E,w,l,23,c[47]),T,E,u,6,c[48]),E=o(E,w,A,T,y,10,c[49]),T=o(T,E,w,A,O,15,c[50]),A=o(A,T,E,w,h,21,c[51]),w=o(w,A,T,E,_,6,c[52]),E=o(E,w,A,T,p,10,c[53]),T=o(T,E,w,A,v,15,c[54]),A=o(A,T,E,w,s,21,c[55]),w=o(w,A,T,E,g,6,c[56]),E=o(E,w,A,T,P,10,c[57]),T=o(T,E,w,A,d,15,c[58]),A=o(A,T,E,w,S,21,c[59]),w=o(w,A,T,E,f,6,c[60]),E=o(E,w,A,T,m,10,c[61]),T=o(T,E,w,A,l,15,c[62]),A=o(A,T,E,w,b,21,c[63]);a[0]=a[0]+w|0,a[1]=a[1]+A|0,a[2]=a[2]+T|0,a[3]=a[3]+E|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;n[o>>>5]|=128<<24-o%32;var i=e.floor(r/4294967296);for(n[15+(o+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(o+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,r=0;4>r;r++)o=n[r],n[r]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8);return t},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=s._createHelper(u),i.HmacMD5=s._createHmacHelper(u)}(Math),function(){var e,t=w,n=(e=t.lib).Base,r=e.WordArray,o=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(s=this.cfg).hasher.create(),o=r.create(),i=o.words,a=s.keySize,s=s.iterations;i.length>>2]}},t.BlockCipher=s.extend({cfg:s.cfg.extend({mode:u,padding:l}),reset:function(){s.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var p=t.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),f=(u=(h.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?r.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=r.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return p.create({ciphertext:e,salt:n})}},t.SerializableCipher=n.extend({cfg:n.extend({format:u}),encrypt:function(e,t,n,r){r=this.cfg.extend(r);var o=e.createEncryptor(n,r);return t=o.finalize(t),o=o.cfg,p.create({ciphertext:t,key:n,iv:o.iv,algorithm:e,mode:o.mode,padding:o.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(n,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),h=(h.kdf={}).OpenSSL={execute:function(e,t,n,o){return o||(o=r.random(8)),e=a.create({keySize:t+n}).compute(e,o),n=r.create(e.words.slice(t),4*n),e.sigBytes=4*t,p.create({key:e,iv:n,salt:o})}},d=t.PasswordBasedCipher=f.extend({cfg:f.cfg.extend({kdf:h}),encrypt:function(e,t,n,r){return n=(r=this.cfg.extend(r)).kdf.execute(n,e.keySize,e.ivSize),r.iv=n.iv,(e=f.encrypt.call(this,e,t,n.key,r)).mixIn(n),e},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),n=r.kdf.execute(n,e.keySize,e.ivSize,t.salt),r.iv=n.iv,f.decrypt.call(this,e,t,n.key,r)}})}(),function(){for(var e=w,t=e.lib.BlockCipher,n=e.algo,r=[],o=[],i=[],a=[],s=[],u=[],c=[],l=[],p=[],f=[],h=[],d=0;256>d;d++)h[d]=128>d?d<<1:d<<1^283;var y=0,g=0;for(d=0;256>d;d++){var b=(b=g^g<<1^g<<2^g<<3^g<<4)>>>8^255&b^99;r[y]=b,o[b]=y;var v=h[y],m=h[v],_=h[m],S=257*h[b]^16843008*b;i[y]=S<<24|S>>>8,a[y]=S<<16|S>>>16,s[y]=S<<8|S>>>24,u[y]=S,S=16843009*_^65537*m^257*v^16843008*y,c[b]=S<<24|S>>>8,l[b]=S<<16|S>>>16,p[b]=S<<8|S>>>24,f[b]=S,y?(y=v^h[h[h[_^v]]],g^=h[h[g]]):y=g=1}var O=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),o=this._keySchedule=[],i=0;i>>24]<<24|r[a>>>16&255]<<16|r[a>>>8&255]<<8|r[255&a]):(a=r[(a=a<<8|a>>>24)>>>24]<<24|r[a>>>16&255]<<16|r[a>>>8&255]<<8|r[255&a],a^=O[i/t|0]<<24),o[i]=o[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:c[r[a>>>24]]^l[r[a>>>16&255]]^p[r[a>>>8&255]]^f[r[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,s,u,r)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,c,l,p,f,o),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,o,i,a,s){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],p=e[t+2]^n[2],f=e[t+3]^n[3],h=4,d=1;d>>24]^o[l>>>16&255]^i[p>>>8&255]^a[255&f]^n[h++],g=r[l>>>24]^o[p>>>16&255]^i[f>>>8&255]^a[255&c]^n[h++],b=r[p>>>24]^o[f>>>16&255]^i[c>>>8&255]^a[255&l]^n[h++];f=r[f>>>24]^o[c>>>16&255]^i[l>>>8&255]^a[255&p]^n[h++],c=y,l=g,p=b}y=(s[c>>>24]<<24|s[l>>>16&255]<<16|s[p>>>8&255]<<8|s[255&f])^n[h++],g=(s[l>>>24]<<24|s[p>>>16&255]<<16|s[f>>>8&255]<<8|s[255&c])^n[h++],b=(s[p>>>24]<<24|s[f>>>16&255]<<16|s[c>>>8&255]<<8|s[255&l])^n[h++],f=(s[f>>>24]<<24|s[c>>>16&255]<<16|s[l>>>8&255]<<8|s[255&p])^n[h++],e[t]=y,e[t+1]=g,e[t+2]=b,e[t+3]=f},keySize:8});e.AES=t._createHelper(n)}(),w.mode.ECB=((P=w.lib.BlockCipherMode.extend()).Encryptor=P.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),P.Decryptor=P.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),P);var E=w;function T(e){var t,n=[];for(t=0;t=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))},e.prototype.clearHistory=function(){this.hashHistory=[]},e}();function C(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function j(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var M={signPamFromParams:function(e){return j(e).map((function(t){return"".concat(t,"=").concat(C(e[t]))})).join("&")},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e,t;return{promise:new Promise((function(n,r){e=n,t=r})),reject:t,fulfill:e}},encodeString:C,stringToArrayBuffer:function(e){for(var t=new ArrayBuffer(2*e.length),n=new Uint16Array(t),r=0,o=e.length;r=u){var l={};l.category=R.PNRequestMessageCountExceededCategory,l.operation=e.operation,this._listenerManager.announceStatus(l)}a.forEach((function(e){var t=e.channel,i=e.subscriptionMatch,a=e.publishMetaData;if(t===i&&(i=null),c){if(o._dedupingManager.isDuplicate(e))return;o._dedupingManager.addEntry(e)}if(M.endsWith(e.channel,"-pnpres"))(y={channel:null,subscription:null}).actualChannel=null!=i?t:null,y.subscribedChannel=null!=i?i:t,t&&(y.channel=t.substring(0,t.lastIndexOf("-pnpres"))),i&&(y.subscription=i.substring(0,i.lastIndexOf("-pnpres"))),y.action=e.payload.action,y.state=e.payload.data,y.timetoken=a.publishTimetoken,y.occupancy=e.payload.occupancy,y.uuid=e.payload.uuid,y.timestamp=e.payload.timestamp,e.payload.join&&(y.join=e.payload.join),e.payload.leave&&(y.leave=e.payload.leave),e.payload.timeout&&(y.timeout=e.payload.timeout),o._listenerManager.announcePresence(y);else if(1===e.messageType){(y={channel:null,subscription:null}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),y.message=e.payload,o._listenerManager.announceSignal(y)}else if(2===e.messageType){if((y={channel:null,subscription:null}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),y.message={event:e.payload.event,type:e.payload.type,data:e.payload.data},o._listenerManager.announceObjects(y),"uuid"===e.payload.type){var s=o._renameChannelField(y);o._listenerManager.announceUser(n(n({},s),{message:n(n({},s.message),{event:o._renameEvent(s.message.event),type:"user"})}))}else if("channel"===e.payload.type){s=o._renameChannelField(y);o._listenerManager.announceSpace(n(n({},s),{message:n(n({},s.message),{event:o._renameEvent(s.message.event),type:"space"})}))}else if("membership"===e.payload.type){var u=(s=o._renameChannelField(y)).message.data,l=u.uuid,p=u.channel,f=r(u,["uuid","channel"]);f.user=l,f.space=p,o._listenerManager.announceMembership(n(n({},s),{message:n(n({},s.message),{event:o._renameEvent(s.message.event),data:f})}))}}else if(3===e.messageType){(y={}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,y.data={messageTimetoken:e.payload.data.messageTimetoken,actionTimetoken:e.payload.data.actionTimetoken,type:e.payload.data.type,uuid:e.issuingClientId,value:e.payload.data.value},y.event=e.payload.event,o._listenerManager.announceMessageAction(y)}else if(4===e.messageType){(y={}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId;var h=e.payload;if(o._cryptoModule){var d=void 0;try{d=(g=o._cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(o._decoder.decode(g)):g}catch(e){d=null,y.error="Error while decrypting message content: ".concat(e.message)}null!==d&&(h=d)}e.userMetadata&&(y.userMetadata=e.userMetadata),y.message=h.message,y.file={id:h.file.id,name:h.file.name,url:o._getFileUrl({id:h.file.id,name:h.file.name,channel:t})},o._listenerManager.announceFile(y)}else{var y;if((y={channel:null,subscription:null}).actualChannel=null!=i?t:null,y.subscribedChannel=null!=i?i:t,y.channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),o._cryptoModule){d=void 0;try{var g;d=(g=o._cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(o._decoder.decode(g)):g}catch(e){d=null,y.error="Error while decrypting message content: ".concat(e.message)}y.message=null!=d?d:e.payload}else y.message=e.payload;o._listenerManager.announceMessage(y)}})),this._region=t.metadata.region,this._startSubscribeLoop()}},e.prototype._stopSubscribeLoop=function(){this._subscribeCall&&("function"==typeof this._subscribeCall.abort&&this._subscribeCall.abort(),this._subscribeCall=null)},e.prototype._renameEvent=function(e){return"set"===e?"updated":"removed"},e.prototype._renameChannelField=function(e){var t=e.channel,n=r(e,["channel"]);return n.spaceId=t,n},e}(),I={PNTimeOperation:"PNTimeOperation",PNHistoryOperation:"PNHistoryOperation",PNDeleteMessagesOperation:"PNDeleteMessagesOperation",PNFetchMessagesOperation:"PNFetchMessagesOperation",PNMessageCounts:"PNMessageCountsOperation",PNSubscribeOperation:"PNSubscribeOperation",PNUnsubscribeOperation:"PNUnsubscribeOperation",PNPublishOperation:"PNPublishOperation",PNSignalOperation:"PNSignalOperation",PNAddMessageActionOperation:"PNAddActionOperation",PNRemoveMessageActionOperation:"PNRemoveMessageActionOperation",PNGetMessageActionsOperation:"PNGetMessageActionsOperation",PNCreateUserOperation:"PNCreateUserOperation",PNUpdateUserOperation:"PNUpdateUserOperation",PNDeleteUserOperation:"PNDeleteUserOperation",PNGetUserOperation:"PNGetUsersOperation",PNGetUsersOperation:"PNGetUsersOperation",PNCreateSpaceOperation:"PNCreateSpaceOperation",PNUpdateSpaceOperation:"PNUpdateSpaceOperation",PNDeleteSpaceOperation:"PNDeleteSpaceOperation",PNGetSpaceOperation:"PNGetSpacesOperation",PNGetSpacesOperation:"PNGetSpacesOperation",PNGetMembersOperation:"PNGetMembersOperation",PNUpdateMembersOperation:"PNUpdateMembersOperation",PNGetMembershipsOperation:"PNGetMembershipsOperation",PNUpdateMembershipsOperation:"PNUpdateMembershipsOperation",PNListFilesOperation:"PNListFilesOperation",PNGenerateUploadUrlOperation:"PNGenerateUploadUrlOperation",PNPublishFileOperation:"PNPublishFileOperation",PNGetFileUrlOperation:"PNGetFileUrlOperation",PNDownloadFileOperation:"PNDownloadFileOperation",PNGetAllUUIDMetadataOperation:"PNGetAllUUIDMetadataOperation",PNGetUUIDMetadataOperation:"PNGetUUIDMetadataOperation",PNSetUUIDMetadataOperation:"PNSetUUIDMetadataOperation",PNRemoveUUIDMetadataOperation:"PNRemoveUUIDMetadataOperation",PNGetAllChannelMetadataOperation:"PNGetAllChannelMetadataOperation",PNGetChannelMetadataOperation:"PNGetChannelMetadataOperation",PNSetChannelMetadataOperation:"PNSetChannelMetadataOperation",PNRemoveChannelMetadataOperation:"PNRemoveChannelMetadataOperation",PNSetMembersOperation:"PNSetMembersOperation",PNSetMembershipsOperation:"PNSetMembershipsOperation",PNPushNotificationEnabledChannelsOperation:"PNPushNotificationEnabledChannelsOperation",PNRemoveAllPushNotificationsOperation:"PNRemoveAllPushNotificationsOperation",PNWhereNowOperation:"PNWhereNowOperation",PNSetStateOperation:"PNSetStateOperation",PNHereNowOperation:"PNHereNowOperation",PNGetStateOperation:"PNGetStateOperation",PNHeartbeatOperation:"PNHeartbeatOperation",PNChannelGroupsOperation:"PNChannelGroupsOperation",PNRemoveGroupOperation:"PNRemoveGroupOperation",PNChannelsForGroupOperation:"PNChannelsForGroupOperation",PNAddChannelsToGroupOperation:"PNAddChannelsToGroupOperation",PNRemoveChannelsFromGroupOperation:"PNRemoveChannelsFromGroupOperation",PNAccessManagerGrant:"PNAccessManagerGrant",PNAccessManagerGrantToken:"PNAccessManagerGrantToken",PNAccessManagerAudit:"PNAccessManagerAudit",PNAccessManagerRevokeToken:"PNAccessManagerRevokeToken",PNHandshakeOperation:"PNHandshakeOperation",PNReceiveMessagesOperation:"PNReceiveMessagesOperation"},x=function(){function e(e){this._maximumSamplesCount=100,this._trackedLatencies={},this._latencies={},this._maximumSamplesCount=e.maximumSamplesCount||this._maximumSamplesCount}return e.prototype.operationsLatencyForRequest=function(){var e=this,t={};return Object.keys(this._latencies).forEach((function(n){var r=e._latencies[n],o=e._averageLatency(r);o>0&&(t["l_".concat(n)]=o)})),t},e.prototype.startLatencyMeasure=function(e,t){e!==I.PNSubscribeOperation&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(e!==I.PNSubscribeOperation&&t){var n=this._endpointName(e),r=this._latencies[n],o=this._trackedLatencies[t];r||(this._latencies[n]=[],r=this._latencies[n]),r.push(Date.now()-o),r.length>this._maximumSamplesCount&&r.splice(0,r.length-this._maximumSamplesCount),delete this._trackedLatencies[t]}},e.prototype._averageLatency=function(e){return Math.floor(e.reduce((function(e,t){return e+t}),0)/e.length)},e.prototype._endpointName=function(e){var t=null;switch(e){case I.PNPublishOperation:t="pub";break;case I.PNSignalOperation:t="sig";break;case I.PNHistoryOperation:case I.PNFetchMessagesOperation:case I.PNDeleteMessagesOperation:case I.PNMessageCounts:t="hist";break;case I.PNUnsubscribeOperation:case I.PNWhereNowOperation:case I.PNHereNowOperation:case I.PNHeartbeatOperation:case I.PNSetStateOperation:case I.PNGetStateOperation:t="pres";break;case I.PNAddChannelsToGroupOperation:case I.PNRemoveChannelsFromGroupOperation:case I.PNChannelGroupsOperation:case I.PNRemoveGroupOperation:case I.PNChannelsForGroupOperation:t="cg";break;case I.PNPushNotificationEnabledChannelsOperation:case I.PNRemoveAllPushNotificationsOperation:t="push";break;case I.PNCreateUserOperation:case I.PNUpdateUserOperation:case I.PNDeleteUserOperation:case I.PNGetUserOperation:case I.PNGetUsersOperation:case I.PNCreateSpaceOperation:case I.PNUpdateSpaceOperation:case I.PNDeleteSpaceOperation:case I.PNGetSpaceOperation:case I.PNGetSpacesOperation:case I.PNGetMembersOperation:case I.PNUpdateMembersOperation:case I.PNGetMembershipsOperation:case I.PNUpdateMembershipsOperation:t="obj";break;case I.PNAddMessageActionOperation:case I.PNRemoveMessageActionOperation:case I.PNGetMessageActionsOperation:t="msga";break;case I.PNAccessManagerGrant:case I.PNAccessManagerAudit:t="pam";break;case I.PNAccessManagerGrantToken:case I.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),D=function(){function e(e,t,n){this._payload=e,this._setDefaultPayloadStructure(),this.title=t,this.body=n}return Object.defineProperty(e.prototype,"payload",{get:function(){return this._payload},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{set:function(e){this._title=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{set:function(e){this._subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{set:function(e){this._body=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{set:function(e){this._badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{set:function(e){this._sound=e},enumerable:!1,configurable:!0}),e.prototype._setDefaultPayloadStructure=function(){},e.prototype.toObject=function(){return{}},e}(),F=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"configurations",{set:function(e){e&&e.length&&(this._configurations=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"notification",{get:function(){return this._payload.aps},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.aps.alert.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){e&&e.length&&(this._payload.aps.alert.subtitle=e,this._subtitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.aps.alert.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this._badge},set:function(e){null!=e&&(this._payload.aps.badge=e,this._badge=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.aps.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),r.prototype._setDefaultPayloadStructure=function(){this._payload.aps={alert:{}}},r.prototype.toObject=function(){var e=this,t=n({},this._payload),r=t.aps,o=r.alert;if(this._isSilent&&(r["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");var i=[];this._configurations.forEach((function(t){i.push(e._objectFromAPNS2Configuration(t))})),i.length&&(t.pn_push=i)}return o&&Object.keys(o).length||delete r.alert,this._isSilent&&(delete r.alert,delete r.badge,delete r.sound,o={}),this._isSilent||Object.keys(o).length?t:null},r.prototype._objectFromAPNS2Configuration=function(e){var t=this;if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");var n=[];e.targets.forEach((function(e){n.push(t._objectFromAPNSTarget(e))}));var r=e.collapseId,o=e.expirationDate,i={auth_method:"token",targets:n,version:"v2"};return r&&r.length&&(i.collapse_id=r),o&&(i.expiration=o.toISOString()),i},r.prototype._objectFromAPNSTarget=function(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");var t=e.topic,n=e.environment,r=void 0===n?"development":n,o=e.excludedDevices,i=void 0===o?[]:o,a={topic:t,environment:r};return i.length&&(a.excluded_devices=i),a},r}(D),G=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"backContent",{get:function(){return this._backContent},set:function(e){e&&e.length&&(this._payload.back_content=e,this._backContent=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"backTitle",{get:function(){return this._backTitle},set:function(e){e&&e.length&&(this._payload.back_title=e,this._backTitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},set:function(e){null!=e&&(this._payload.count=e,this._count=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"type",{get:function(){return this._type},set:function(e){e&&e.length&&(this._payload.type=e,this._type=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this.backTitle},set:function(e){this.backTitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this.backContent},set:function(e){this.backContent=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this.count},set:function(e){this.count=e},enumerable:!1,configurable:!0}),r.prototype.toObject=function(){return Object.keys(this._payload).length?n({},this._payload):null},r}(D),L=function(e){function o(){return null!==e&&e.apply(this,arguments)||this}return t(o,e),Object.defineProperty(o.prototype,"notification",{get:function(){return this._payload.notification},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"data",{get:function(){return this._payload.data},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.notification.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.notification.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.notification.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"icon",{get:function(){return this._icon},set:function(e){e&&e.length&&(this._payload.notification.icon=e,this._icon=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"tag",{get:function(){return this._tag},set:function(e){e&&e.length&&(this._payload.notification.tag=e,this._tag=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),o.prototype._setDefaultPayloadStructure=function(){this._payload.notification={},this._payload.data={}},o.prototype.toObject=function(){var e=n({},this._payload.data),t=null,o={};if(Object.keys(this._payload).length>2){var i=this._payload;i.notification,i.data;var a=r(i,["notification","data"]);e=n(n({},e),a)}return this._isSilent?e.notification=this._payload.notification:t=this._payload.notification,Object.keys(e).length&&(o.data=e),t&&Object.keys(t).length&&(o.notification=t),Object.keys(o).length?o:null},o}(D),K=function(){function e(e,t){this._payload={apns:{},mpns:{},fcm:{}},this._title=e,this._body=t,this.apns=new F(this._payload.apns,e,t),this.mpns=new G(this._payload.mpns,e,t),this.fcm=new L(this._payload.fcm,e,t)}return Object.defineProperty(e.prototype,"debugging",{set:function(e){this._debugging=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{get:function(){return this._title},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{get:function(){return this._body},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){this._subtitle=e,this.apns.subtitle=e,this.mpns.subtitle=e,this.fcm.subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{get:function(){return this._badge},set:function(e){this._badge=e,this.apns.badge=e,this.mpns.badge=e,this.fcm.badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{get:function(){return this._sound},set:function(e){this._sound=e,this.apns.sound=e,this.mpns.sound=e,this.fcm.sound=e},enumerable:!1,configurable:!0}),e.prototype.buildPayload=function(e){var t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";var n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("mpns")){var r=this.mpns.toObject();r&&Object.keys(r).length&&(t.pn_mpns=r)}if(e.includes("fcm")){var o=this.fcm.toObject();o&&Object.keys(o).length&&(t.pn_gcm=o)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t},e}(),B=function(){function e(){this._listeners=[]}return e.prototype.addListener=function(e){this._listeners.push(e)},e.prototype.removeListener=function(e){var t=[];this._listeners.forEach((function(n){n!==e&&t.push(n)})),this._listeners=t},e.prototype.removeAllListeners=function(){this._listeners=[]},e.prototype.announcePresence=function(e){this._listeners.forEach((function(t){t.presence&&t.presence(e)}))},e.prototype.announceStatus=function(e){this._listeners.forEach((function(t){t.status&&t.status(e)}))},e.prototype.announceMessage=function(e){this._listeners.forEach((function(t){t.message&&t.message(e)}))},e.prototype.announceSignal=function(e){this._listeners.forEach((function(t){t.signal&&t.signal(e)}))},e.prototype.announceMessageAction=function(e){this._listeners.forEach((function(t){t.messageAction&&t.messageAction(e)}))},e.prototype.announceFile=function(e){this._listeners.forEach((function(t){t.file&&t.file(e)}))},e.prototype.announceObjects=function(e){this._listeners.forEach((function(t){t.objects&&t.objects(e)}))},e.prototype.announceUser=function(e){this._listeners.forEach((function(t){t.user&&t.user(e)}))},e.prototype.announceSpace=function(e){this._listeners.forEach((function(t){t.space&&t.space(e)}))},e.prototype.announceMembership=function(e){this._listeners.forEach((function(t){t.membership&&t.membership(e)}))},e.prototype.announceNetworkUp=function(){var e={};e.category=R.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=R.PNNetworkDownCategory,this.announceStatus(e)},e}(),H=function(){function e(e,t){this._config=e,this._cbor=t}return e.prototype.setToken=function(e){e&&e.length>0?this._token=e:this._token=void 0},e.prototype.getToken=function(){return this._token},e.prototype.extractPermissions=function(e){var t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128==(128&e)&&(t.join=!0),64==(64&e)&&(t.update=!0),32==(32&e)&&(t.get=!0),8==(8&e)&&(t.delete=!0),4==(4&e)&&(t.manage=!0),2==(2&e)&&(t.write=!0),1==(1&e)&&(t.read=!0),t},e.prototype.parseToken=function(e){var t=this,n=this._cbor.decodeToken(e);if(void 0!==n){var r=n.res.uuid?Object.keys(n.res.uuid):[],o=Object.keys(n.res.chan),i=Object.keys(n.res.grp),a=n.pat.uuid?Object.keys(n.pat.uuid):[],s=Object.keys(n.pat.chan),u=Object.keys(n.pat.grp),c={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid},l=r.length>0,p=o.length>0,f=i.length>0;(l||p||f)&&(c.resources={},l&&(c.resources.uuids={},r.forEach((function(e){c.resources.uuids[e]=t.extractPermissions(n.res.uuid[e])}))),p&&(c.resources.channels={},o.forEach((function(e){c.resources.channels[e]=t.extractPermissions(n.res.chan[e])}))),f&&(c.resources.groups={},i.forEach((function(e){c.resources.groups[e]=t.extractPermissions(n.res.grp[e])}))));var h=a.length>0,d=s.length>0,y=u.length>0;return(h||d||y)&&(c.patterns={},h&&(c.patterns.uuids={},a.forEach((function(e){c.patterns.uuids[e]=t.extractPermissions(n.pat.uuid[e])}))),d&&(c.patterns.channels={},s.forEach((function(e){c.patterns.channels[e]=t.extractPermissions(n.pat.chan[e])}))),y&&(c.patterns.groups={},u.forEach((function(e){c.patterns.groups[e]=t.extractPermissions(n.pat.grp[e])})))),Object.keys(n.meta).length>0&&(c.meta=n.meta),c.signature=n.sig,c}},e}(),q=function(e){function n(t,n){var r=this.constructor,o=e.call(this,t)||this;return o.name=o.constructor.name,o.status=n,o.message=t,Object.setPrototypeOf(o,r.prototype),o}return t(n,e),n}(Error);function z(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}function V(e,t,n){return e.usePost&&e.usePost(t,n)?e.postURL(t,n):e.usePatch&&e.usePatch(t,n)?e.patchURL(t,n):e.useGetFile&&e.useGetFile(t,n)?e.getFileURL(t,n):e.getURL(t,n)}function W(e){if(e.sdkName)return e.sdkName;var t="PubNub-JS-".concat(e.sdkFamily);e.partnerId&&(t+="-".concat(e.partnerId)),t+="/".concat(e.getVersion());var n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}function J(e,t,n){return t.usePost&&t.usePost(e,n)?"POST":t.usePatch&&t.usePatch(e,n)?"PATCH":t.useDelete&&t.useDelete(e,n)?"DELETE":t.useGetFile&&t.useGetFile(e,n)?"GETFILE":"GET"}function $(e,t,n,r,o){var i=e.config,a=e.crypto,s=J(e,o,r);n.timestamp=Math.floor((new Date).getTime()/1e3),"PNPublishOperation"===o.getOperation()&&o.usePost&&o.usePost(e,r)&&(s="GET"),"GETFILE"===s&&(s="GET");var u="".concat(s,"\n").concat(i.publishKey,"\n").concat(t,"\n").concat(M.signPamFromParams(n),"\n");if("POST"===s)u+="string"==typeof(c=o.postPayload(e,r))?c:JSON.stringify(c);else if("PATCH"===s){var c;u+="string"==typeof(c=o.patchPayload(e,r))?c:JSON.stringify(c)}var l="v2.".concat(a.HMACSHA256(u));l=(l=(l=l.replace(/\+/g,"-")).replace(/\//g,"_")).replace(/=+$/,""),n.signature=l}function Q(e,t){for(var r=[],o=2;o0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(i),"/leave")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o={};return r.length>0&&(o["channel-group"]=r.join(",")),o},handleResponse:function(){return{}}});var se=Object.freeze({__proto__:null,getOperation:function(){return I.PNWhereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,o=void 0===r?n.UUID:r;return"/v2/presence/sub-key/".concat(n.subscribeKey,"/uuid/").concat(M.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return t.payload?{channels:t.payload.channels}:{channels:[]}}});var ue=Object.freeze({__proto__:null,getOperation:function(){return I.PNHeartbeatOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(i),"/heartbeat")},isAuthSupported:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o=t.state,i=void 0===o?{}:o,a=e.config,s={};return r.length>0&&(s["channel-group"]=r.join(",")),s.state=JSON.stringify(i),s.heartbeat=a.getPresenceTimeout(),s},handleResponse:function(){return{}}});var ce=Object.freeze({__proto__:null,getOperation:function(){return I.PNGetStateOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,o=void 0===r?n.UUID:r,i=t.channels,a=void 0===i?[]:i,s=a.length>0?a.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(s),"/uuid/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o={};return r.length>0&&(o["channel-group"]=r.join(",")),o},handleResponse:function(e,t,n){var r=n.channels,o=void 0===r?[]:r,i=n.channelGroups,a=void 0===i?[]:i,s={};return 1===o.length&&0===a.length?s[o[0]]=t.payload:s=t.payload,{channels:s}}});var le=Object.freeze({__proto__:null,getOperation:function(){return I.PNSetStateOperation},validateParams:function(e,t){var n=e.config,r=t.state,o=t.channels,i=void 0===o?[]:o,a=t.channelGroups,s=void 0===a?[]:a;return r?n.subscribeKey?0===i.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key":"Missing State"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(i),"/uuid/").concat(M.encodeString(n.UUID),"/data")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.state,r=t.channelGroups,o=void 0===r?[]:r,i={};return i.state=JSON.stringify(n),o.length>0&&(i["channel-group"]=o.join(",")),i},handleResponse:function(e,t){return{state:t.payload}}});var pe=Object.freeze({__proto__:null,getOperation:function(){return I.PNHereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=t.channelGroups,a=void 0===i?[]:i,s="/v2/presence/sub-key/".concat(n.subscribeKey);if(o.length>0||a.length>0){var u=o.length>0?o.join(","):",";s+="/channel/".concat(M.encodeString(u))}return s},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var r=t.channelGroups,o=void 0===r?[]:r,i=t.includeUUIDs,a=void 0===i||i,s=t.includeState,u=void 0!==s&&s,c=t.queryParameters,l=void 0===c?{}:c,p={};return a||(p.disable_uuids=1),u&&(p.state=1),o.length>0&&(p["channel-group"]=o.join(",")),p=n(n({},p),l)},handleResponse:function(e,t,n){var r=n.channels,o=void 0===r?[]:r,i=n.channelGroups,a=void 0===i?[]:i,s=n.includeUUIDs,u=void 0===s||s,c=n.includeState,l=void 0!==c&&c;return o.length>1||a.length>0||0===a.length&&0===o.length?function(){var e={};return e.totalChannels=t.payload.total_channels,e.totalOccupancy=t.payload.total_occupancy,e.channels={},Object.keys(t.payload.channels).forEach((function(n){var r=t.payload.channels[n],o=[];return e.channels[n]={occupants:o,name:n,occupancy:r.occupancy},u&&r.uuids.forEach((function(e){l?o.push({state:e.state,uuid:e.uuid}):o.push({state:null,uuid:e})})),e})),e}():function(){var e={},n=[];return e.totalChannels=1,e.totalOccupancy=t.occupancy,e.channels={},e.channels[o[0]]={occupants:n,name:o[0],occupancy:t.occupancy},u&&t.uuids&&t.uuids.forEach((function(e){l?n.push({state:e.state,uuid:e.uuid}):n.push({state:null,uuid:e})})),e}()},handleError:function(e,t,n){402!==n.statusCode||this.getURL(e,t).includes("channel")||(n.errorData.message="You have tried to perform a Global Here Now operation, your keyset configuration does not support that. Please provide a channel, or enable the Global Here Now feature from the Portal.")}});var fe=Object.freeze({__proto__:null,getOperation:function(){return I.PNAddMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.action,o=t.channel;return t.messageTimetoken?n.subscribeKey?o?r?r.value?r.type?r.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message channel":"Missing Subscribe Key":"Missing message timetoken"},usePost:function(){return!0},postURL:function(e,t){var n=e.config,r=t.channel,o=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(r),"/message/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},getRequestHeaders:function(){return{"Content-Type":"application/json"}},isAuthSupported:function(){return!0},prepareParams:function(){return{}},postPayload:function(e,t){return t.action},handleResponse:function(e,t){return{data:t.data}}});var he=Object.freeze({__proto__:null,getOperation:function(){return I.PNRemoveMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.channel,o=t.actionTimetoken;return t.messageTimetoken?o?n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key":"Missing action timetoken":"Missing message timetoken"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config,r=t.channel,o=t.actionTimetoken,i=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(r),"/message/").concat(i,"/action/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{data:t.data}}});var de=Object.freeze({__proto__:null,getOperation:function(){return I.PNGetMessageActionsOperation},validateParams:function(e,t){var n=e.config,r=t.channel;return n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channel;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(M.encodeString(r))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.limit,r=t.start,o=t.end,i={};return n&&(i.limit=n),r&&(i.start=r),o&&(i.end=o),i},handleResponse:function(e,t){var n={data:t.data,start:null,end:null};return n.data.length&&(n.end=n.data[n.data.length-1].actionTimetoken,n.start=n.data[0].actionTimetoken),n}}),ye={getOperation:function(){return I.PNListFilesOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel can't be empty"},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel),"/files")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.limit&&(n.limit=t.limit),t.next&&(n.next=t.next),n},handleResponse:function(e,t){return{status:t.status,data:t.data,next:t.next,count:t.count}}},ge={getOperation:function(){return I.PNGenerateUploadUrlOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?void 0:"name can't be empty":"channel can't be empty"},usePost:function(){return!0},postURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel),"/generate-upload-url")},postPayload:function(e,t){return{name:t.name}},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data,file_upload_request:t.file_upload_request}}},be={getOperation:function(){return I.PNPublishFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.fileId)?(null==t?void 0:t.fileName)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},getURL:function(e,t){var n=e.config,r=n.publishKey,o=n.subscribeKey,i=function(e,t){var n=JSON.stringify(t);if(e.cryptoModule){var r=e.cryptoModule.encrypt(n);n="string"==typeof r?r:v(r),n=JSON.stringify(n)}return n||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(i))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.ttl&&(n.ttl=t.ttl),void 0!==t.storeInHistory&&(n.store=t.storeInHistory?"1":"0"),t.meta&&"object"==typeof t.meta&&(n.meta=JSON.stringify(t.meta)),n},handleResponse:function(e,t){return{timetoken:t[2]}}},ve=function(e){var t=function(e){var t=this,n=e.generateUploadUrl,r=e.publishFile,a=e.modules,s=a.PubNubFile,u=a.config,c=a.cryptography,l=a.cryptoModule,p=a.networking;return function(e){var a=e.channel,f=e.file,h=e.message,d=e.cipherKey,y=e.meta,g=e.ttl,b=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,v,m,_,S,O,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K,B,H;return i(this,(function(i){switch(i.label){case 0:if(!a)throw new q("Validation failed, check status for details",z("channel can't be empty"));if(!f)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(f),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,v=o.url,m=o.form_fields,_=t.data,S=_.id,O=_.name,s.supportsEncryptFile&&(d||l)?null!=d?[3,3]:[4,l.encryptFile(e,s)]:[3,6];case 2:return P=i.sent(),[3,5];case 3:return[4,c.encryptFile(d,e,s)];case 4:P=i.sent(),i.label=5;case 5:e=P,i.label=6;case 6:w=m,e.mimeType&&(w=m.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=7;case 7:return i.trys.push([7,21,,22]),s.supportsFileUri&&f.uri?(A=(T=p).POSTFILE,N=[v,w],[4,e.toFileUri()]):[3,10];case 8:return[4,A.apply(T,N.concat([i.sent()]))];case 9:return E=i.sent(),[3,20];case 10:return s.supportsFile?(C=(k=p).POSTFILE,j=[v,w],[4,e.toFile()]):[3,13];case 11:return[4,C.apply(k,j.concat([i.sent()]))];case 12:return E=i.sent(),[3,20];case 13:return s.supportsBuffer?(R=(M=p).POSTFILE,U=[v,w],[4,e.toBuffer()]):[3,16];case 14:return[4,R.apply(M,U.concat([i.sent()]))];case 15:return E=i.sent(),[3,20];case 16:return s.supportsBlob?(x=(I=p).POSTFILE,D=[v,w],[4,e.toBlob()]):[3,19];case 17:return[4,x.apply(I,D.concat([i.sent()]))];case 18:return E=i.sent(),[3,20];case 19:throw new Error("Unsupported environment");case 20:return[3,22];case 21:throw(F=i.sent()).response&&"string"==typeof F.response.text?(G=F.response.text,L=/(.*)<\/Message>/gi.exec(G),new q(L?"Upload to bucket failed: ".concat(L[1]):"Upload to bucket failed.",F)):new q("Upload to bucket failed.",F);case 22:if(204!==E.status)throw new q("Upload to bucket was unsuccessful",E);K=u.fileUploadPublishRetryLimit,B=!1,H={timetoken:"0"},i.label=23;case 23:return i.trys.push([23,25,,26]),[4,r({channel:a,message:h,fileId:S,fileName:O,meta:y,storeInHistory:b,ttl:g})];case 24:return H=i.sent(),B=!0,[3,26];case 25:return i.sent(),K-=1,[3,26];case 26:if(!B&&K>0)return[3,23];i.label=27;case 27:if(B)return[2,{timetoken:H.timetoken,id:S,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:S,name:O})}}))}))}}(e);return function(e,n){var r=t(e);return"function"==typeof n?(r.then((function(e){return n(null,e)})).catch((function(e){return n(e,null)})),r):r}},me=function(e,t){var n=t.channel,r=t.id,o=t.name,i=e.config,a=e.networking,s=e.tokenManager;if(!n)throw new q("Validation failed, check status for details",z("channel can't be empty"));if(!r)throw new q("Validation failed, check status for details",z("file id can't be empty"));if(!o)throw new q("Validation failed, check status for details",z("file name can't be empty"));var u="/v1/files/".concat(i.subscribeKey,"/channels/").concat(M.encodeString(n),"/files/").concat(r,"/").concat(o),c={};c.uuid=i.getUUID(),c.pnsdk=W(i);var l=s.getToken()||i.getAuthKey();l&&(c.auth=l),i.secretKey&&$(e,u,c,{},{getOperation:function(){return"PubNubGetFileUrlOperation"}});var p=Object.keys(c).map((function(e){return"".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(c[e]))})).join("&");return""!==p?"".concat(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},_e={getOperation:function(){return I.PNDownloadFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?(null==t?void 0:t.id)?void 0:"id can't be empty":"name can't be empty":"channel can't be empty"},useGetFile:function(){return!0},getFileURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},ignoreBody:function(){return!0},forceBuffered:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t,n){var r=e.PubNubFile,a=e.config,s=e.cryptography,u=e.cryptoModule;return o(void 0,void 0,void 0,(function(){var e,o,c,l;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(n.cipherKey||u)?null!=n.cipherKey?[3,2]:[4,u.decryptFile(r.create({data:e,name:n.name}),r)]:[3,5];case 1:return o=i.sent().data,[3,4];case 2:return[4,s.decrypt(null!==(c=n.cipherKey)&&void 0!==c?c:a.cipherKey,e)];case 3:o=i.sent(),i.label=4;case 4:e=o,i.label=5;case 5:return[2,r.create({data:e,name:null!==(l=t.response.name)&&void 0!==l?l:n.name,mimeType:t.response.type})]}}))}))}},Se={getOperation:function(){return I.PNListFilesOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.id)?(null==t?void 0:t.name)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status}}},Oe={getOperation:function(){return I.PNGetAllUUIDMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,f={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&f.include.push("custom"),f.include=f.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(f.count=null===(o=t.include)||void 0===o?void 0:o.totalCount),(null===(i=null==t?void 0:t.page)||void 0===i?void 0:i.next)&&(f.start=null===(a=t.page)||void 0===a?void 0:a.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(f.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(f.filter=t.filter),f.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(f.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),f},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,next:t.next,prev:t.prev}}},Pe={getOperation:function(){return I.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(M.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o=e.config,i={};return i.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:o.getUUID(),i.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&i.include.pop(),i.include=i.include.join(","),i},handleResponse:function(e,t){return{status:t.status,data:t.data}}},we={getOperation:function(){return I.PNSetUUIDMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.data))return"Data cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(M.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o=e.config,i={};return i.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:o.getUUID(),i.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&i.include.pop(),i.include=i.include.join(","),i},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ee={getOperation:function(){return I.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(M.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r=e.config;return{uuid:null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Te={getOperation:function(){return I.PNGetAllChannelMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,f={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&f.include.push("custom"),f.include=f.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(f.count=null===(o=t.include)||void 0===o?void 0:o.totalCount),(null===(i=null==t?void 0:t.page)||void 0===i?void 0:i.next)&&(f.start=null===(a=t.page)||void 0===a?void 0:a.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(f.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(f.filter=t.filter),f.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(f.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),f},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Ae={getOperation:function(){return I.PNGetChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ne={getOperation:function(){return I.PNSetChannelMetadataOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.data)?void 0:"Data cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},ke={getOperation:function(){return I.PNRemoveChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ce={getOperation:function(){return I.PNGetMembersOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel),"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,f,h,d,y,g,b={include:[]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.statusField)&&b.include.push("status"),(null===(r=t.include)||void 0===r?void 0:r.customFields)&&b.include.push("custom"),(null===(o=t.include)||void 0===o?void 0:o.UUIDFields)&&b.include.push("uuid"),(null===(i=t.include)||void 0===i?void 0:i.customUUIDFields)&&b.include.push("uuid.custom"),(null===(a=t.include)||void 0===a?void 0:a.UUIDStatusField)&&b.include.push("uuid.status"),(null===(u=t.include)||void 0===u?void 0:u.UUIDTypeField)&&b.include.push("uuid.type")),b.include=b.include.join(","),(null===(c=null==t?void 0:t.include)||void 0===c?void 0:c.totalCount)&&(b.count=null===(l=t.include)||void 0===l?void 0:l.totalCount),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.next)&&(b.start=null===(f=t.page)||void 0===f?void 0:f.next),(null===(h=null==t?void 0:t.page)||void 0===h?void 0:h.prev)&&(b.end=null===(d=t.page)||void 0===d?void 0:d.prev),(null==t?void 0:t.filter)&&(b.filter=t.filter),b.limit=null!==(y=null==t?void 0:t.limit)&&void 0!==y?y:100,(null==t?void 0:t.sort)&&(b.sort=Object.entries(null!==(g=t.sort)&&void 0!==g?g:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),b},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},je={getOperation:function(){return I.PNSetMembersOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.uuids)&&0!==(null==t?void 0:t.uuids.length)?void 0:"UUIDs cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(M.encodeString(t.channel),"/uuids")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.uuids.map((function(e){return"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,f={include:["uuid.status","uuid.type","type"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&f.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customUUIDFields)&&f.include.push("uuid.custom"),(null===(o=t.include)||void 0===o?void 0:o.UUIDFields)&&f.include.push("uuid")),f.include=f.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(f.count=!0),(null===(a=null==t?void 0:t.page)||void 0===a?void 0:a.next)&&(f.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(f.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(f.filter=t.filter),null!=t.limit&&(f.limit=t.limit),(null==t?void 0:t.sort)&&(f.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),f},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Me={getOperation:function(){return I.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(M.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,f,h,d,y,g,b={include:[]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.statusField)&&b.include.push("status"),(null===(r=t.include)||void 0===r?void 0:r.customFields)&&b.include.push("custom"),(null===(o=t.include)||void 0===o?void 0:o.channelFields)&&b.include.push("channel"),(null===(i=t.include)||void 0===i?void 0:i.customChannelFields)&&b.include.push("channel.custom"),(null===(a=t.include)||void 0===a?void 0:a.channelStatusField)&&b.include.push("channel.status"),(null===(u=t.include)||void 0===u?void 0:u.channelTypeField)&&b.include.push("channel.type")),b.include=b.include.join(","),(null===(c=null==t?void 0:t.include)||void 0===c?void 0:c.totalCount)&&(b.count=null===(l=t.include)||void 0===l?void 0:l.totalCount),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.next)&&(b.start=null===(f=t.page)||void 0===f?void 0:f.next),(null===(h=null==t?void 0:t.page)||void 0===h?void 0:h.prev)&&(b.end=null===(d=t.page)||void 0===d?void 0:d.prev),(null==t?void 0:t.filter)&&(b.filter=t.filter),b.limit=null!==(y=null==t?void 0:t.limit)&&void 0!==y?y:100,(null==t?void 0:t.sort)&&(b.sort=Object.entries(null!==(g=t.sort)&&void 0!==g?g:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),b},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Re={getOperation:function(){return I.PNSetMembershipsOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)||0===(null==t?void 0:t.channels.length))return"Channels cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(M.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.channels.map((function(e){return"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,f={include:["channel.status","channel.type","status"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&f.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customChannelFields)&&f.include.push("channel.custom"),(null===(o=t.include)||void 0===o?void 0:o.channelFields)&&f.include.push("channel")),f.include=f.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(f.count=!0),(null===(a=null==t?void 0:t.page)||void 0===a?void 0:a.next)&&(f.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(f.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(f.filter=t.filter),null!=t.limit&&(f.limit=t.limit),(null==t?void 0:t.sort)&&(f.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),f},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}};var Ue=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerAudit},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/audit/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channel,r=t.channelGroup,o=t.authKeys,i=void 0===o?[]:o,a={};return n&&(a.channel=n),r&&(a["channel-group"]=r),i.length>0&&(a.auth=i.join(",")),a},handleResponse:function(e,t){return t.payload}});var Ie=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrant},validateParams:function(e,t){var n=e.config;return n.subscribeKey?n.publishKey?n.secretKey?null==t.uuids||t.authKeys?null==t.uuids||null==t.channels&&null==t.channelGroups?void 0:"Both channel/channelgroup and uuid cannot be used in the same request":"authKeys are required for grant request on uuids":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/grant/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channels,r=void 0===n?[]:n,o=t.channelGroups,i=void 0===o?[]:o,a=t.uuids,s=void 0===a?[]:a,u=t.ttl,c=t.read,l=void 0!==c&&c,p=t.write,f=void 0!==p&&p,h=t.manage,d=void 0!==h&&h,y=t.get,g=void 0!==y&&y,b=t.join,v=void 0!==b&&b,m=t.update,_=void 0!==m&&m,S=t.authKeys,O=void 0===S?[]:S,P=t.delete,w={};return w.r=l?"1":"0",w.w=f?"1":"0",w.m=d?"1":"0",w.d=P?"1":"0",w.g=g?"1":"0",w.j=v?"1":"0",w.u=_?"1":"0",r.length>0&&(w.channel=r.join(",")),i.length>0&&(w["channel-group"]=i.join(",")),O.length>0&&(w.auth=O.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function xe(e){var t,n,r,o,i=void 0!==(null==e?void 0:e.authorizedUserId),a=void 0!==(null===(t=null==e?void 0:e.resources)||void 0===t?void 0:t.users),s=void 0!==(null===(n=null==e?void 0:e.resources)||void 0===n?void 0:n.spaces),u=void 0!==(null===(r=null==e?void 0:e.patterns)||void 0===r?void 0:r.users),c=void 0!==(null===(o=null==e?void 0:e.patterns)||void 0===o?void 0:o.spaces);return u||a||c||s||i}function De(e){var t=0;return e.join&&(t|=128),e.update&&(t|=64),e.get&&(t|=32),e.delete&&(t|=8),e.manage&&(t|=4),e.write&&(t|=2),e.read&&(t|=1),t}function Fe(e,t){if(xe(t))return function(e,t){var n=t.ttl,r=t.resources,o=t.patterns,i=t.meta,a=t.authorizedUserId,s={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.users,c=r.spaces,l=r.groups;u&&Object.keys(u).forEach((function(e){s.permissions.resources.uuids[e]=De(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=De(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=De(l[e])}))}if(o){var p=o.users,f=o.spaces,h=o.groups;p&&Object.keys(p).forEach((function(e){s.permissions.patterns.uuids[e]=De(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=De(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=De(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}(0,t);var n=t.ttl,r=t.resources,o=t.patterns,i=t.meta,a=t.authorized_uuid,s={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.uuids,c=r.channels,l=r.groups;u&&Object.keys(u).forEach((function(e){s.permissions.resources.uuids[e]=De(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=De(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=De(l[e])}))}if(o){var p=o.uuids,f=o.channels,h=o.groups;p&&Object.keys(p).forEach((function(e){s.permissions.patterns.uuids[e]=De(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=De(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=De(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Ge=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:De,validateParams:function(e,t){var n,r,o,i,a,s,u=e.config;if(!u.subscribeKey)return"Missing Subscribe Key";if(!u.publishKey)return"Missing Publish Key";if(!u.secretKey)return"Missing Secret Key";if(!t.resources&&!t.patterns)return"Missing either Resources or Patterns.";var c=void 0!==(null==t?void 0:t.authorized_uuid),l=void 0!==(null===(n=null==t?void 0:t.resources)||void 0===n?void 0:n.uuids),p=void 0!==(null===(r=null==t?void 0:t.resources)||void 0===r?void 0:r.channels),f=void 0!==(null===(o=null==t?void 0:t.resources)||void 0===o?void 0:o.groups),h=void 0!==(null===(i=null==t?void 0:t.patterns)||void 0===i?void 0:i.uuids),d=void 0!==(null===(a=null==t?void 0:t.patterns)||void 0===a?void 0:a.channels),y=void 0!==(null===(s=null==t?void 0:t.patterns)||void 0===s?void 0:s.groups),g=c||l||h||p||d||f||y;return xe(t)&&g?"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`":(!t.resources||t.resources.uuids&&0!==Object.keys(t.resources.uuids).length||t.resources.channels&&0!==Object.keys(t.resources.channels).length||t.resources.groups&&0!==Object.keys(t.resources.groups).length||t.resources.users&&0!==Object.keys(t.resources.users).length||t.resources.spaces&&0!==Object.keys(t.resources.spaces).length)&&(!t.patterns||t.patterns.uuids&&0!==Object.keys(t.patterns.uuids).length||t.patterns.channels&&0!==Object.keys(t.patterns.channels).length||t.patterns.groups&&0!==Object.keys(t.patterns.groups).length||t.patterns.users&&0!==Object.keys(t.patterns.users).length||t.patterns.spaces&&0!==Object.keys(t.patterns.spaces).length)?void 0:"Missing values for either Resources or Patterns."},postURL:function(e){var t=e.config;return"/v3/pam/".concat(t.subscribeKey,"/grant")},usePost:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(){return{}},postPayload:function(e,t){return Fe(0,t)},handleResponse:function(e,t){return t.data.token}}),Le={getOperation:function(){return I.PNAccessManagerRevokeToken},validateParams:function(e,t){return e.config.secretKey?t?void 0:"token can't be empty":"Missing Secret Key"},getURL:function(e,t){var n=e.config;return"/v3/pam/".concat(n.subscribeKey,"/grant/").concat(M.encodeString(t))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e){return{uuid:e.config.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}};function Ke(e,t){var n=JSON.stringify(t);if(e.cryptoModule){var r=e.cryptoModule.encrypt(n);n="string"==typeof r?r:v(r),n=JSON.stringify(n)}return n||""}var Be=Object.freeze({__proto__:null,getOperation:function(){return I.PNPublishOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},usePost:function(e,t){var n=t.sendByPost;return void 0!==n&&n},getURL:function(e,t){var n=e.config,r=t.channel,o=Ke(e,t.message);return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(M.encodeString(r),"/0/").concat(M.encodeString(o))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(M.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},postPayload:function(e,t){return Ke(e,t.message)},prepareParams:function(e,t){var n=t.meta,r=t.replicate,o=void 0===r||r,i=t.storeInHistory,a=t.ttl,s={};return null!=i&&(s.store=i?"1":"0"),a&&(s.ttl=a),!1===o&&(s.norep="true"),n&&"object"==typeof n&&(s.meta=JSON.stringify(n)),s},handleResponse:function(e,t){return{timetoken:t[2]}}});var He=Object.freeze({__proto__:null,getOperation:function(){return I.PNSignalOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},getURL:function(e,t){var n,r=e.config,o=t.channel,i=t.message,a=(n=i,JSON.stringify(n));return"/signal/".concat(r.publishKey,"/").concat(r.subscribeKey,"/0/").concat(M.encodeString(o),"/0/").concat(M.encodeString(a))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});var qe=Object.freeze({__proto__:null,getOperation:function(){return I.PNHistoryOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channel,r=e.config;return"/v2/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(M.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,o=t.reverse,i=t.count,a=void 0===i?100:i,s=t.stringifiedTimeToken,u=void 0!==s&&s,c=t.includeMeta,l=void 0!==c&&c,p={include_token:"true"};return p.count=a,n&&(p.start=n),r&&(p.end=r),u&&(p.string_message_token="true"),null!=o&&(p.reverse=o.toString()),l&&(p.include_meta="true"),p},handleResponse:function(e,t){var n={messages:[],startTimeToken:t[1],endTimeToken:t[2]};return Array.isArray(t[0])&&t[0].forEach((function(t){var r=function(e,t){var n={};if(!e.cryptoModule)return n.payload=t,n;try{var r=e.cryptoModule.decrypt(t),o=r instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(r)):r;return n.payload=o,n}catch(r){e.config.logVerbosity&&console&&console.log&&console.log("decryption error",r.message),n.payload=t,n.error="Error while decrypting message content: ".concat(r.message)}return n}(e,t.message),o={timetoken:t.timetoken,entry:r.payload};t.meta&&(o.meta=t.meta),r.error&&(o.error=r.error),n.messages.push(o)})),n}});var ze=Object.freeze({__proto__:null,getOperation:function(){return I.PNDeleteMessagesOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},useDelete:function(){return!0},getURL:function(e,t){var n=t.channel,r=e.config;return"/v3/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(M.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,o={};return n&&(o.start=n),r&&(o.end=r),o},handleResponse:function(e,t){return t.payload}});var Ve=Object.freeze({__proto__:null,getOperation:function(){return I.PNMessageCounts},validateParams:function(e,t){var n=t.channels,r=t.timetoken,o=t.channelTimetokens,i=e.config;return n?r&&o?"timetoken and channelTimetokens are incompatible together":o&&o.length>1&&n.length!==o.length?"Length of channelTimetokens and channels do not match":i.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channels,r=e.config,o=n.join(",");return"/v3/history/sub-key/".concat(r.subscribeKey,"/message-counts/").concat(M.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.timetoken,r=t.channelTimetokens,o={};if(r&&1===r.length){var i=s(r,1)[0];o.timetoken=i}else r?o.channelsTimetoken=r.join(","):n&&(o.timetoken=n);return o},handleResponse:function(e,t){return{channels:t.channels}}});var We=Object.freeze({__proto__:null,getOperation:function(){return I.PNFetchMessagesOperation},validateParams:function(e,t){var n=t.channels,r=t.includeMessageActions,o=void 0!==r&&r,i=e.config;if(!n||0===n.length)return"Missing channels";if(!i.subscribeKey)return"Missing Subscribe Key";if(o&&n.length>1)throw new TypeError("History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.")},getURL:function(e,t){var n=t.channels,r=void 0===n?[]:n,o=t.includeMessageActions,i=void 0!==o&&o,a=e.config,s=i?"history-with-actions":"history",u=r.length>0?r.join(","):",";return"/v3/".concat(s,"/sub-key/").concat(a.subscribeKey,"/channel/").concat(M.encodeString(u))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channels,r=t.start,o=t.end,i=t.includeMessageActions,a=t.count,s=t.stringifiedTimeToken,u=void 0!==s&&s,c=t.includeMeta,l=void 0!==c&&c,p=t.includeUuid,f=t.includeUUID,h=void 0===f||f,d=t.includeMessageType,y=void 0===d||d,g={};return g.max=a||(n.length>1||!0===i?25:100),r&&(g.start=r),o&&(g.end=o),u&&(g.string_message_token="true"),l&&(g.include_meta="true"),h&&!1!==p&&(g.include_uuid="true"),y&&(g.include_message_type="true"),g},handleResponse:function(e,t){var n={channels:{}};return Object.keys(t.channels||{}).forEach((function(r){n.channels[r]=[],(t.channels[r]||[]).forEach((function(t){var o={},i=function(e,t){var n={};if(!e.cryptoModule)return n.payload=t,n;try{var r=e.cryptoModule.decrypt(t),o=r instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(r)):r;return n.payload=o,n}catch(r){e.config.logVerbosity&&console&&console.log&&console.log("decryption error",r.message),n.payload=t,n.error="Error while decrypting message content: ".concat(r.message)}return n}(e,t.message);o.channel=r,o.timetoken=t.timetoken,o.message=i.payload,o.messageType=t.message_type,o.uuid=t.uuid,t.actions&&(o.actions=t.actions,o.data=t.actions),t.meta&&(o.meta=t.meta),i.error&&(o.error=i.error),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Je=Object.freeze({__proto__:null,getOperation:function(){return I.PNTimeOperation},getURL:function(){return"/time/0"},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(){return{}},isAuthSupported:function(){return!1},handleResponse:function(e,t){return{timetoken:t[0]}},validateParams:function(){}});var $e=Object.freeze({__proto__:null,getOperation:function(){return I.PNSubscribeOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(M.encodeString(i),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=e.config,r=t.state,o=t.channelGroups,i=void 0===o?[]:o,a=t.timetoken,s=t.filterExpression,u=t.region,c={heartbeat:n.getPresenceTimeout()};return i.length>0&&(c["channel-group"]=i.join(",")),s&&s.length>0&&(c["filter-expr"]=s),Object.keys(r).length&&(c.state=JSON.stringify(r)),a&&(c.tt=a),u&&(c.tr=u),c},handleResponse:function(e,t){var n=[];t.m.forEach((function(e){var t={publishTimetoken:e.p.t,region:e.p.r},r={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};n.push(r)}));var r={timetoken:t.t.t,region:t.t.r};return{messages:n,metadata:r}}}),Qe={getOperation:function(){return I.PNHandshakeOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)&&!(null==t?void 0:t.channelGroups))return"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels?t.channels.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(M.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),n.tt=0,n},handleResponse:function(e,t){return{region:t.t.r,timetoken:t.t.t}}},Xe={getOperation:function(){return I.PNReceiveMessagesOperation},validateParams:function(e,t){return(null==t?void 0:t.channels)||(null==t?void 0:t.channelGroups)?(null==t?void 0:t.timetoken)?(null==t?void 0:t.region)?void 0:"region can not be empty":"timetoken can not be empty":"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels?t.channels.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(M.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},getAbortSignal:function(e,t){return t.abortSignal},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),n.tt=t.timetoken,n.tr=t.region,n},handleResponse:function(e,t){var n=[];return t.m.forEach((function(e){var t={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,publishMetaData:{timetoken:e.p.t,region:e.p.r}};n.push(t)})),{messages:n,metadata:{region:t.t.r,timetoken:t.t.t}}}},Ye=function(){function e(e){void 0===e&&(e=!1),this.sync=e,this.listeners=new Set}return e.prototype.subscribe=function(e){var t=this;return this.listeners.add(e),function(){t.listeners.delete(e)}},e.prototype.notify=function(e){var t=this,n=function(){t.listeners.forEach((function(t){t(e)}))};this.sync?n():setTimeout(n,0)},e}(),Ze=function(){function e(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}return e.prototype.transition=function(e,t){var n;if(this.transitionMap.has(t.type))return null===(n=this.transitionMap.get(t.type))||void 0===n?void 0:n(e,t)},e.prototype.on=function(e,t){return this.transitionMap.set(e,t),this},e.prototype.with=function(e,t){return[this,e,null!=t?t:[]]},e.prototype.onEnter=function(e){return this.enterEffects.push(e),this},e.prototype.onExit=function(e){return this.exitEffects.push(e),this},e}(),et=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new Ze(e)},n.prototype.start=function(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})},n.prototype.transition=function(e){var t,n,r,o,i,u;if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});var c=this.currentState.transition(this.currentContext,e);if(c){var l=s(c,3),p=l[0],f=l[1],h=l[2];try{for(var d=a(this.currentState.exitEffects),y=d.next();!y.done;y=d.next()){var g=y.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){t={error:e}}finally{try{y&&!y.done&&(n=d.return)&&n.call(d)}finally{if(t)throw t.error}}var b=this.currentState;this.currentState=p;var v=this.currentContext;this.currentContext=f,this.notify({type:"transitionDone",fromState:b,fromContext:v,toState:p,toContext:f,event:e});try{for(var m=a(h),_=m.next();!_.done;_=m.next()){g=_.value;this.notify({type:"invocationDispatched",invocation:g})}}catch(e){r={error:e}}finally{try{_&&!_.done&&(o=m.return)&&o.call(m)}finally{if(r)throw r.error}}try{for(var S=a(this.currentState.enterEffects),O=S.next();!O.done;O=S.next()){g=O.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{O&&!O.done&&(u=S.return)&&u.call(S)}finally{if(i)throw i.error}}}},n}(Ye),tt=function(){function e(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}return e.prototype.on=function(e,t){this.handlers.set(e,t)},e.prototype.dispatch=function(e){if("CANCEL"!==e.type){var t=this.handlers.get(e.type);if(!t)throw new Error("Unhandled invocation '".concat(e.type,"'"));var n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}else if(this.instances.has(e.payload)){var r=this.instances.get(e.payload);null==r||r.cancel(),this.instances.delete(e.payload)}},e}();function nt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(dt.type,lt((function(e,n,a){var s=a.receiveEvents,u=a.shouldRetry,c=a.getRetryDelay,l=a.delay;return o(r,void 0,void 0,(function(){var r,o;return i(this,(function(i){switch(i.label){case 0:return u(e.reason,e.attempts)?(n.throwIfAborted(),[4,l(c(e.attempts))]):[2,t.transition(kt())];case 1:i.sent(),n.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,s({abortSignal:n,channels:e.channels,channelGroups:e.groups,timetoken:e.cursor.timetoken,region:e.cursor.region})];case 3:return r=i.sent(),[2,t.transition(At(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Nt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(yt.type,lt((function(e,n,a){var s=a.handshake,u=a.shouldRetry,c=a.getRetryDelay,l=a.delay;return o(r,void 0,void 0,(function(){var r,o;return i(this,(function(i){switch(i.label){case 0:return u(e.reason,e.attempts)?(n.throwIfAborted(),[4,l(c(e.attempts))]):[2,t.transition(Pt())];case 1:i.sent(),n.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,s({abortSignal:n,channels:e.channels,channelGroups:e.groups})];case 3:return r=i.sent(),[2,t.transition(St(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ot(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(tt),Mt=new Ze("STOPPED");Mt.on(gt.type,(function(e,t){return Mt.with({channels:t.payload.channels,groups:t.payload.groups})})),Mt.on(vt.type,(function(e){return Gt.with(n({},e))}));var Rt=new Ze("HANDSHAKE_FAILURE");Rt.on(wt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Rt.on(bt.type,(function(e){return Mt.with({channels:e.channels,groups:e.groups})}));var Ut=new Ze("STOPPED");Ut.on(gt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Ut.on(vt.type,(function(e){return Dt.with(n({},e))}));var It=new Ze("RECEIVE_FAILURE");It.on(Ct.type,(function(e){return xt.with(n(n({},e),{attempts:0}))})),It.on(bt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var xt=new Ze("RECEIVE_RECONNECTING");xt.onEnter((function(e){return dt(e)})),xt.onExit((function(){return dt.cancel})),xt.on(At.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),xt.on(Nt.type,(function(e,t){return xt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),xt.on(kt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),xt.on(bt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new Ze("RECEIVING");Dt.onEnter((function(e){return ft(e.channels,e.groups,e.cursor)})),Dt.onExit((function(){return ft.cancel})),Dt.on(Et.type,(function(e,t){return Dt.with(n(n({},e),{cursor:t.payload.cursor}),[ht(t.payload.events)])})),Dt.on(gt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Lt.with(void 0):Dt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Dt.on(Tt.type,(function(e,t){return xt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Dt.on(bt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new Ze("HANDSHAKE_RECONNECTING");Ft.onEnter((function(e){return yt(e)})),Ft.onExit((function(){return dt.cancel})),Ft.on(At.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),Ft.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(kt.type,(function(e){return Rt.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Ft.on(bt.type,(function(e){return Mt.with({channels:e.channels,groups:e.groups})}));var Gt=new Ze("HANDSHAKING");Gt.onEnter((function(e){return pt(e.channels,e.groups)})),Gt.onExit((function(){return pt.cancel})),Gt.on(gt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Lt.with(void 0):Gt.with({channels:t.payload.channels,groups:t.payload.groups})})),Gt.on(mt.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Gt.on(_t.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(bt.type,(function(e){return Mt.with({channels:e.channels,groups:e.groups})}));var Lt=new Ze("UNSUBSCRIBED");Lt.on(gt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Kt=function(){function e(e){var t=this;this.engine=new et,this.channels=[],this.groups=[],this.dispatcher=new jt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Lt,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(e){var t=e.channels,n=e.groups;this.channels=u(u([],s(this.channels),!1),s(null!=t?t:[]),!1),this.groups=u(u([],s(this.groups),!1),s(null!=n?n:[]),!1),this.engine.transition(gt(this.channels,this.groups))},e.prototype.unsubscribe=function(e){var t=e.channels,n=e.groups;this.channels=this.channels.filter((function(e){var n;return null===(n=!(null==t?void 0:t.includes(e)))||void 0===n||n})),this.groups=this.groups.filter((function(e){var t;return null===(t=!(null==n?void 0:n.includes(e)))||void 0===t||t})),this.engine.transition(gt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(gt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(vt())},e.prototype.disconnect=function(){this.engine.transition(bt())},e}(),Bt=function(){function e(e){var t=this,r=e.networking,o=e.cbor,i=new g({setup:e});this._config=i;var a=new A({config:i}),c=e.cryptography;r.init(i);var l=new H(i,o);this._tokenManager=l;var p=new x({maximumSamplesCount:6e4});this._telemetryManager=p;var f=this._config.cryptoModule,h={config:i,networking:r,crypto:a,cryptography:c,tokenManager:l,telemetryManager:p,PubNubFile:e.PubNubFile,cryptoModule:f};this.File=e.PubNubFile,this.encryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&h.cryptoModule?(t=e,h.cryptoModule.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&h.cryptoModule?(t=e,h.cryptoModule.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Je),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,$e),S=new B;if(this._listenerManager=S,this.iAmHere=Q.bind(this,h,ue),this.iAmAway=Q.bind(this,h,ae),this.setPresenceState=Q.bind(this,h,le),this.handshake=Q.bind(this,h,Qe),this.receiveMessages=Q.bind(this,h,Xe),!0===i.enableSubscribeBeta){var O=new Kt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=O.subscribe.bind(O),this.unsubscribe=O.unsubscribe.bind(O),this.eventEngine=O}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:S,getFileUrl:function(e){return me(h,e)},cryptoModule:h.cryptoModule});this.subscribe=P.adaptSubscribeChange.bind(P),this.unsubscribe=P.adaptUnsubscribeChange.bind(P),this.disconnect=P.disconnect.bind(P),this.reconnect=P.reconnect.bind(P),this.unsubscribeAll=P.unsubscribeAll.bind(P),this.getSubscribedChannels=P.getSubscribedChannels.bind(P),this.getSubscribedChannelGroups=P.getSubscribedChannelGroups.bind(P),this.setState=P.adaptStateChange.bind(P),this.presence=P.adaptPresenceChange.bind(P),this.destroy=function(e){P.unsubscribeAll(e),P.disconnect()}}this.addListener=S.addListener.bind(S),this.removeListener=S.removeListener.bind(S),this.removeAllListeners=S.removeAllListeners.bind(S),this.parseToken=l.parseToken.bind(l),this.setToken=l.setToken.bind(l),this.getToken=l.getToken.bind(l),this.channelGroups={listGroups:Q.bind(this,h,ee),listChannels:Q.bind(this,h,te),addChannels:Q.bind(this,h,X),removeChannels:Q.bind(this,h,Y),deleteGroup:Q.bind(this,h,Z)},this.push={addChannels:Q.bind(this,h,ne),removeChannels:Q.bind(this,h,re),deleteDevice:Q.bind(this,h,ie),listChannels:Q.bind(this,h,oe)},this.hereNow=Q.bind(this,h,pe),this.whereNow=Q.bind(this,h,se),this.getState=Q.bind(this,h,ce),this.grant=Q.bind(this,h,Ie),this.grantToken=Q.bind(this,h,Ge),this.audit=Q.bind(this,h,Ue),this.revokeToken=Q.bind(this,h,Le),this.publish=Q.bind(this,h,Be),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,He),this.history=Q.bind(this,h,qe),this.deleteMessages=Q.bind(this,h,ze),this.messageCounts=Q.bind(this,h,Ve),this.fetchMessages=Q.bind(this,h,We),this.addMessageAction=Q.bind(this,h,fe),this.removeMessageAction=Q.bind(this,h,he),this.getMessageActions=Q.bind(this,h,de),this.listFiles=Q.bind(this,h,ye);var w=Q.bind(this,h,ge);this.publishFile=Q.bind(this,h,be),this.sendFile=ve({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return me(h,e)},this.downloadFile=Q.bind(this,h,_e),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Oe),getUUIDMetadata:Q.bind(this,h,Pe),setUUIDMetadata:Q.bind(this,h,we),removeUUIDMetadata:Q.bind(this,h,Ee),getAllChannelMetadata:Q.bind(this,h,Te),getChannelMetadata:Q.bind(this,h,Ae),setChannelMetadata:Q.bind(this,h,Ne),removeChannelMetadata:Q.bind(this,h,ke),getChannelMembers:Q.bind(this,h,Ce),setChannelMembers:function(e){for(var r=[],o=1;o=this._config.origin.length&&(this._currentSubDomain=0);var t=this._config.origin[this._currentSubDomain];return"".concat(e).concat(t)},e.prototype.hasModule=function(e){return e in this._modules},e.prototype.shiftStandardOrigin=function(){return this._standardOrigin=this.nextOrigin(),this._standardOrigin},e.prototype.getStandardOrigin=function(){return this._standardOrigin},e.prototype.POSTFILE=function(e,t,n){return this._modules.postfile(e,t,n)},e.prototype.GETFILE=function(e,t,n){return this._modules.getfile(e,t,n)},e.prototype.POST=function(e,t,n,r){return this._modules.post(e,t,n,r)},e.prototype.PATCH=function(e,t,n,r){return this._modules.patch(e,t,n,r)},e.prototype.GET=function(e,t,n){return this._modules.get(e,t,n)},e.prototype.DELETE=function(e,t,n){return this._modules.del(e,t,n)},e.prototype._detectErrorCategory=function(e){if("ENOTFOUND"===e.code)return R.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return R.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return R.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return R.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return R.PNNetworkIssuesCategory;if(e.timeout)return R.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return R.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return R.PNBadRequestCategory;if(e.response.forbidden)return R.PNAccessDeniedCategory}return R.PNUnknownCategory},e}();function qt(e){var t=function(e){return e&&"object"==typeof e&&e.constructor===Object};if(!t(e))return e;var n={};return Object.keys(e).forEach((function(r){var o=function(e){return"string"==typeof e||e instanceof String}(r),i=r,a=e[r];Array.isArray(r)||o&&r.indexOf(",")>=0?i=(o?r.split(","):r).reduce((function(e,t){return e+=String.fromCharCode(t)}),""):(function(e){return"number"==typeof e&&isFinite(e)}(r)||o&&!isNaN(r))&&(i=String.fromCharCode(o?parseInt(r,10):10));n[i]=t(a)?qt(a):a})),n}var zt=function(){function e(e,t){this._base64ToBinary=t,this._decode=e}return e.prototype.decodeToken=function(e){var t="";e.length%4==3?t="=":e.length%4==2&&(t="==");var n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,r=this._decode(this._base64ToBinary(n));if("object"==typeof r)return r},e}(),Vt={exports:{}},Wt={exports:{}};!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;oa.depthLimit)return void tn($t,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn($t,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function on(e,t,n,r){void 0===r&&(r=Zt());var o,i=an(e,"",0,[],void 0,0,r)||e;try{o=0===Yt.length?JSON.stringify(i,t,n):JSON.stringify(i,sn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Xt.length;){var a=Xt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function an(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void tn($t,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn($t,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new _n('"allowMissing" argument must be a boolean');var n=Ln(e),r=n.length>0?n[0]:"",o=Kn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],In(n,Un([0,1],u)));for(var c=1,l=!0;c=n.length){var d=On(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Rn(a,p),a=a[p];l&&!s&&(kn[i]=a)}}return a},Hn={exports:{}};!function(e){var t=gn,n=Bn,r=n("%Function.prototype.apply%"),o=n("%Function.prototype.call%"),i=n("%Reflect.apply%",!0)||t.call(o,r),a=n("%Object.getOwnPropertyDescriptor%",!0),s=n("%Object.defineProperty%",!0),u=n("%Math.max%");if(s)try{s({},"a",{value:1})}catch(e){s=null}e.exports=function(e){var n=i(t,o,arguments);if(a&&s){var r=a(n,"length");r.configurable&&s(n,"length",{value:1+u(0,e.length-(arguments.length-1))})}return n};var c=function(){return i(t,r,arguments)};s?s(e.exports,"apply",{value:c}):e.exports.apply=c}(Hn);var qn=Bn,zn=Hn.exports,Vn=zn(qn("String.prototype.indexOf")),Wn=l(Object.freeze({__proto__:null,default:{}})),Jn="function"==typeof Map&&Map.prototype,$n=Object.getOwnPropertyDescriptor&&Jn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Qn=Jn&&$n&&"function"==typeof $n.get?$n.get:null,Xn=Jn&&Map.prototype.forEach,Yn="function"==typeof Set&&Set.prototype,Zn=Object.getOwnPropertyDescriptor&&Yn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,er=Yn&&Zn&&"function"==typeof Zn.get?Zn.get:null,tr=Yn&&Set.prototype.forEach,nr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,rr="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,or="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ir=Boolean.prototype.valueOf,ar=Object.prototype.toString,sr=Function.prototype.toString,ur=String.prototype.match,cr=String.prototype.slice,lr=String.prototype.replace,pr=String.prototype.toUpperCase,fr=String.prototype.toLowerCase,hr=RegExp.prototype.test,dr=Array.prototype.concat,yr=Array.prototype.join,gr=Array.prototype.slice,br=Math.floor,vr="function"==typeof BigInt?BigInt.prototype.valueOf:null,mr=Object.getOwnPropertySymbols,_r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Or="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,Pr=Object.prototype.propertyIsEnumerable,wr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Er(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||hr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-br(-e):br(e);if(r!==e){var o=String(r),i=cr.call(t,o.length+1);return lr.call(o,n,"$&_")+"."+lr.call(lr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return lr.call(t,n,"$&_")}var Tr=Wn,Ar=Tr.custom,Nr=Rr(Ar)?Ar:null;function kr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Cr(e){return lr.call(String(e),/"/g,""")}function jr(e){return!("[object Array]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}function Mr(e){return!("[object RegExp]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}function Rr(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}var Ur=Object.prototype.hasOwnProperty||function(e){return e in this};function Ir(e,t){return Ur.call(e,t)}function xr(e){return ar.call(e)}function Dr(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;nt.maxStringLength){var n=e.length-t.maxStringLength,r="... "+n+" more character"+(n>1?"s":"");return Fr(cr.call(e,0,t.maxStringLength),t)+r}return kr(lr.call(lr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Gr),"single",t)}function Gr(e){var t=e.charCodeAt(0),n={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return n?"\\"+n:"\\x"+(t<16?"0":"")+pr.call(t.toString(16))}function Lr(e){return"Object("+e+")"}function Kr(e){return e+" { ? }"}function Br(e,t,n,r){return e+" ("+t+") {"+(r?Hr(n,r):yr.call(n,", "))+"}"}function Hr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+yr.call(e,","+n)+"\n"+t.prev}function qr(e,t){var n=jr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?zn(n):n},Wr=function e(t,n,r,o){var i=n||{};if(Ir(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Ir(i,"maxStringLength")&&("number"==typeof i.maxStringLength?i.maxStringLength<0&&i.maxStringLength!==1/0:null!==i.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var a=!Ir(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Ir(i,"indent")&&null!==i.indent&&"\t"!==i.indent&&!(parseInt(i.indent,10)===i.indent&&i.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Ir(i,"numericSeparator")&&"boolean"!=typeof i.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var s=i.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return Fr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Er(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Er(t,c):c}var l=void 0===i.depth?5:i.depth;if(void 0===r&&(r=0),r>=l&&l>0&&"object"==typeof t)return jr(t)?"[Array]":"[Object]";var p=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;n=yr.call(Array(e.indent+1)," ")}return{base:n,prev:yr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Dr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=gr.call(o)).push(n),a){var s={depth:i.depth};return Ir(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Mr(t)){var h=function(e){if(e.name)return e.name;var t=ur.call(sr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=qr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+yr.call(d,", ")+" }":"")}if(Rr(t)){var y=Sr?lr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):_r.call(t);return"object"!=typeof t||Sr?y:Lr(y)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var g="<"+fr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(jr(t)){if(0===t.length)return"[]";var m=qr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+Hr(m,p)+"]":"[ "+yr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}(t)){var _=qr(t,f);return"cause"in Error.prototype||!("cause"in t)||Pr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+yr.call(_,", ")+" }":"{ ["+String(t)+"] "+yr.call(dr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Nr&&"function"==typeof t[Nr]&&Tr)return Tr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Qn||!e||"object"!=typeof e)return!1;try{Qn.call(e);try{er.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var S=[];return Xn&&Xn.call(t,(function(e,n){S.push(f(n,t,!0)+" => "+f(e,t))})),Br("Map",Qn.call(t),S,p)}if(function(e){if(!er||!e||"object"!=typeof e)return!1;try{er.call(e);try{Qn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var O=[];return tr&&tr.call(t,(function(e){O.push(f(e,t))})),Br("Set",er.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e,nr);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Kr("WeakMap");if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{nr.call(e,nr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Kr("WeakSet");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{return or.call(e),!0}catch(e){}return!1}(t))return Kr("WeakRef");if(function(e){return!("[object Number]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}(t))return Lr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!vr)return!1;try{return vr.call(e),!0}catch(e){}return!1}(t))return Lr(f(vr.call(t)));if(function(e){return!("[object Boolean]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}(t))return Lr(ir.call(t));if(function(e){return!("[object String]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}(t))return Lr(f(String(t)));if(!function(e){return!("[object Date]"!==xr(e)||Or&&"object"==typeof e&&Or in e)}(t)&&!Mr(t)){var P=qr(t,f),w=wr?wr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Or&&Object(t)===t&&Or in t?cr.call(xr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+yr.call(dr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+Hr(P,p)+"}":A+"{ "+yr.call(P,", ")+" }"}return String(t)},Jr=zr("%TypeError%"),$r=zr("%WeakMap%",!0),Qr=zr("%Map%",!0),Xr=Vr("WeakMap.prototype.get",!0),Yr=Vr("WeakMap.prototype.set",!0),Zr=Vr("WeakMap.prototype.has",!0),eo=Vr("Map.prototype.get",!0),to=Vr("Map.prototype.set",!0),no=Vr("Map.prototype.has",!0),ro=function(e,t){for(var n,r=e;null!==(n=r.next);r=n)if(n.key===t)return r.next=n.next,n.next=e.next,e.next=n,n},oo=String.prototype.replace,io=/%20/g,ao="RFC3986",so={default:ao,formatters:{RFC1738:function(e){return oo.call(e,io,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:ao},uo=so,co=Object.prototype.hasOwnProperty,lo=Array.isArray,po=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),fo=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r1;){var t=e.pop(),n=t.obj[t.prop];if(lo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===uo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=po[u]:u<2048?a+=po[192|u>>6]+po[128|63&u]:u<55296||u>=57344?a+=po[224|u>>12]+po[128|u>>6&63]+po[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=po[240|u>>18]+po[128|u>>12&63]+po[128|u>>6&63]+po[128|63&u])}return a},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(lo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(_o(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&_o(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Uo=function(e,t,n,r){if(e){var o=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,a=n.depth>0&&/(\[[^[\]]*])/.exec(o),s=a?o.slice(0,a.index):o,u=[];if(s){if(!n.plainObjects&&ko.call(Object.prototype,s)&&!n.allowPrototypes)return;u.push(s)}for(var c=0;n.depth>0&&null!==(a=i.exec(o))&&c=0;--i){var a,s=e[i];if("[]"===s&&n.parseArrays)a=[].concat(o);else{a=n.plainObjects?Object.create(null):{};var u="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,c=parseInt(u,10);n.parseArrays||""!==u?!isNaN(c)&&s!==u&&String(c)===u&&c>=0&&n.parseArrays&&c<=n.arrayLimit?(a=[])[c]=o:"__proto__"!==u&&(a[u]=o):a={0:o}}o=a}return o}(u,t,n,r)}},Io=function(e,t){var n,r=e,o=function(e){if(!e)return Eo;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Eo.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=bo.default;if(void 0!==e.format){if(!vo.call(bo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=bo.formatters[n],o=Eo.filter;return("function"==typeof e.filter||_o(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Eo.addQueryPrefix,allowDots:void 0===e.allowDots?Eo.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Eo.charsetSentinel,delimiter:void 0===e.delimiter?Eo.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Eo.encode,encoder:"function"==typeof e.encoder?e.encoder:Eo.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Eo.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Eo.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Eo.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Eo.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):_o(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in mo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=mo[i];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var u="comma"===s&&t&&t.commaRoundTrip;n||(n=Object.keys(r)),o.sort&&n.sort(o.sort);for(var c=yo(),l=0;l0?h+f:""},xo={formats:so,parse:function(e,t){var n=function(e){if(!e)return jo;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?jo.charset:e.charset;return{allowDots:void 0===e.allowDots?jo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:jo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:jo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:jo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:jo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:jo.comma,decoder:"function"==typeof e.decoder?e.decoder:jo.decoder,delimiter:"string"==typeof e.delimiter||No.isRegExp(e.delimiter)?e.delimiter:jo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:jo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:jo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:jo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:jo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:jo.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var r="string"==typeof e?function(e,t){var n,r={__proto__:null},o=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,a=o.split(t.delimiter,i),s=-1,u=t.charset;if(t.charsetSentinel)for(n=0;n-1&&(l=Co(l)?[l]:l),ko.call(r,c)?r[c]=No.combine(r[c],l):r[c]=l}return r}(e,n):e,o=n.plainObjects?Object.create(null):{},i=Object.keys(r),a=0;a=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){u=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw a}}}}function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.split(/ *; */).shift(),e.params=e=>{const n={};var r,o=t(e.split(/ *; */));try{for(o.s();!(r=o.n()).done;){const e=r.value.split(/ *= */),t=e.shift(),o=e.shift();t&&o&&(n[t]=o)}}catch(e){o.e(e)}finally{o.f()}return n},e.parseLinks=e=>{const n={};var r,o=t(e.split(/ *, */));try{for(o.s();!(r=o.n()).done;){const e=r.value.split(/ *; */),t=e[0].slice(1,-1);n[e[1].split(/ *= */)[1].slice(1,-1)]=t}}catch(e){o.e(e)}finally{o.f()}return n},e.cleanHeader=(e,t)=>(delete e["content-type"],delete e["content-length"],delete e["transfer-encoding"],delete e.host,t&&(delete e.authorization,delete e.cookie),e),e.isObject=e=>null!==e&&"object"==typeof e,e.hasOwn=Object.hasOwn||function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(new Object(e),t)},e.mixin=(t,n)=>{for(const r in n)e.hasOwn(n,r)&&(t[r]=n[r])}}(Do);const Fo=Wn,Go=Do.isObject,Lo=Do.hasOwn;var Ko=Bo;function Bo(){}Bo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Bo.prototype.parse=function(e){return this._parser=e,this},Bo.prototype.responseType=function(e){return this._responseType=e,this},Bo.prototype.serialize=function(e){return this._serializer=e,this},Bo.prototype.timeout=function(e){if(!e||"object"!=typeof e)return this._timeout=e,this._responseTimeout=0,this._uploadTimeout=0,this;for(const t in e)if(Lo(e,t))switch(t){case"deadline":this._timeout=e.deadline;break;case"response":this._responseTimeout=e.response;break;case"upload":this._uploadTimeout=e.upload;break;default:console.warn("Unknown timeout option",t)}return this},Bo.prototype.retry=function(e,t){return 0!==arguments.length&&!0!==e||(e=1),e<=0&&(e=0),this._maxRetries=e,this._retries=0,this._retryCallback=t,this};const Ho=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),qo=new Set([408,413,429,500,502,503,504,521,522,524]);Bo.prototype._shouldRetry=function(e,t){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{const n=this._retryCallback(e,t);if(!0===n)return!0;if(!1===n)return!1}catch(e){console.error(e)}if(t&&t.status&&qo.has(t.status))return!0;if(e){if(e.code&&Ho.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Bo.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this.timedoutError=null,this._end()},Bo.prototype.then=function(e,t){if(!this._fullfilledPromise){const e=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(((t,n)=>{e.on("abort",(()=>{if(this._maxRetries&&this._maxRetries>this._retries)return;if(this.timedout&&this.timedoutError)return void n(this.timedoutError);const e=new Error("Aborted");e.code="ABORTED",e.status=this.status,e.method=this.method,e.url=this.url,n(e)})),e.end(((e,r)=>{e?n(e):t(r)}))}))}return this._fullfilledPromise.then(e,t)},Bo.prototype.catch=function(e){return this.then(void 0,e)},Bo.prototype.use=function(e){return e(this),this},Bo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Bo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Bo.prototype.get=function(e){return this._header[e.toLowerCase()]},Bo.prototype.getHeader=Bo.prototype.get,Bo.prototype.set=function(e,t){if(Go(e)){for(const t in e)Lo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Bo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Bo.prototype.field=function(e,t,n){if(null==e)throw new Error(".field(name, val) name can not be empty");if(this._data)throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");if(Go(e)){for(const t in e)Lo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Lo(t,n)&&this.field(e,t[n]);return this}if(null==t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=String(t)),n?this._getFormData().append(e,t,n):this._getFormData().append(e,t),this},Bo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Fo.gte(process.version,"v13.0.0")&&Fo.lt(process.version,"v14.0.0"))throw new Error("Superagent does not work in v13 properly with abort() due to Node.js core changes");this.req.abort()}return this.clearTimeout(),this.emit("abort"),this},Bo.prototype._auth=function(e,t,n,r){switch(n.type){case"basic":this.set("Authorization",`Basic ${r(`${e}:${t}`)}`);break;case"auto":this.username=e,this.password=t;break;case"bearer":this.set("Authorization",`Bearer ${e}`)}return this},Bo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Bo.prototype.redirects=function(e){return this._maxRedirects=e,this},Bo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Bo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Bo.prototype.send=function(e){const t=Go(e);let n=this._header["content-type"];if(this._formData)throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");if(t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw new Error("Can't merge these send calls");if(t&&Go(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Lo(e,t)&&(this._data[t]=e[t])}else{if("bigint"==typeof e)throw new Error("Cannot send value of type BigInt");"string"==typeof e?(n||this.type("form"),n=this._header["content-type"],n&&(n=n.toLowerCase().trim()),this._data="application/x-www-form-urlencoded"===n?this._data?`${this._data}&${e}`:e:(this._data||"")+e):this._data=e}return!t||this._isHost(e)||n||this.type("json"),this},Bo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Bo.prototype._finalizeQueryString=function(){const e=this._query.join("&");if(e&&(this.url+=(this.url.includes("?")?"&":"?")+e),this._query.length=0,this._sort){const e=this.url.indexOf("?");if(e>=0){const t=this.url.slice(e+1).split("&");"function"==typeof this._sort?t.sort(this._sort):t.sort(),this.url=this.url.slice(0,e)+"?"+t.join("&")}}},Bo.prototype._appendQueryString=()=>{console.warn("Unsupported")},Bo.prototype._timeoutError=function(e,t,n){if(this._aborted)return;const r=new Error(`${e+t}ms exceeded`);r.timeout=t,r.code="ECONNABORTED",r.errno=n,this.timedout=!0,this.timedoutError=r,this.abort(),this.callback(r)},Bo.prototype._setTimeouts=function(){const e=this;this._timeout&&!this._timer&&(this._timer=setTimeout((()=>{e._timeoutError("Timeout of ",e._timeout,"ETIME")}),this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout((()=>{e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")}),this._responseTimeout))};const zo=Do;var Vo=Wo;function Wo(){}function Jo(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return $o(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return $o(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function $o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,u=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){u=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(u)throw a}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{if(o.XMLHttpRequest)return new o.XMLHttpRequest;throw new Error("Browser-only version of superagent could not find XHR")};const g="".trim?e=>e.trim():e=>e.replace(/(^\s*|\s*$)/g,"");function b(e){if(!c(e))return e;const t=[];for(const n in e)p(e,n)&&v(t,n,e[n]);return t.join("&")}function v(e,t,r){if(void 0!==r)if(null!==r)if(Array.isArray(r)){var o,i=n(r);try{for(i.s();!(o=i.n()).done;){v(e,t,o.value)}}catch(e){i.e(e)}finally{i.f()}}else if(c(r))for(const n in r)p(r,n)&&v(e,`${t}[${n}]`,r[n]);else e.push(encodeURI(t)+"="+encodeURIComponent(r));else e.push(encodeURI(t))}function m(e){const t={},n=e.split("&");let r,o;for(let e=0,i=n.length;e{let e,t=null,r=null;try{r=new S(n)}catch(e){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=e,n.xhr?(t.rawResponse=void 0===n.xhr.responseType?n.xhr.responseText:n.xhr.response,t.status=n.xhr.status?n.xhr.status:null,t.statusCode=t.status):(t.rawResponse=null,t.status=null),n.callback(t)}n.emit("response",r);try{n._isResponseOK(r)||(e=new Error(r.statusText||r.text||"Unsuccessful HTTP response"))}catch(t){e=t}e?(e.original=t,e.response=r,e.status=e.status||r.status,n.callback(e,r)):n.callback(null,r)}))}y.serializeObject=b,y.parseString=m,y.types={html:"text/html",json:"application/json",xml:"text/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},y.serialize={"application/x-www-form-urlencoded":s.stringify,"application/json":a},y.parse={"application/x-www-form-urlencoded":m,"application/json":JSON.parse},l(S.prototype,f.prototype),S.prototype._parseBody=function(e){let t=y.parse[this.type];return this.req._parser?this.req._parser(this,e):(!t&&_(this.type)&&(t=y.parse["application/json"]),t&&e&&(e.length>0||e instanceof Object)?t(e):null)},S.prototype.toError=function(){const e=this.req,t=e.method,n=e.url,r=`cannot ${t} ${n} (${this.status})`,o=new Error(r);return o.status=this.status,o.method=t,o.url=n,o},y.Response=S,i(O.prototype),l(O.prototype,u.prototype),O.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},O.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},O.prototype.auth=function(e,t,n){1===arguments.length&&(t=""),"object"==typeof t&&null!==t&&(n=t,t=""),n||(n={type:"function"==typeof btoa?"basic":"auto"});const r=n.encoder?n.encoder:e=>{if("function"==typeof btoa)return btoa(e);throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(e,t,n,r)},O.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},O.prototype.attach=function(e,t,n){if(t){if(this._data)throw new Error("superagent can't mix .send() and .attach()");this._getFormData().append(e,t,n||t.name)}return this},O.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},O.prototype.callback=function(e,t){if(this._shouldRetry(e,t))return this._retry();const n=this._callback;this.clearTimeout(),e&&(this._maxRetries&&(e.retries=this._retries-1),this.emit("error",e)),n(e,t)},O.prototype.crossDomainError=function(){const e=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");e.crossDomain=!0,e.status=this.status,e.method=this.method,e.url=this.url,this.callback(e)},O.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},O.prototype.ca=O.prototype.agent,O.prototype.buffer=O.prototype.ca,O.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},O.prototype.pipe=O.prototype.write,O.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},O.prototype.end=function(e){this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=e||d,this._finalizeQueryString(),this._end()},O.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},O.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));const e=this;this.xhr=y.getXHR();const t=this.xhr;let n=this._formData||this._data;this._setTimeouts(),t.addEventListener("readystatechange",(()=>{const n=t.readyState;if(n>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4!==n)return;let r;try{r=t.status}catch(e){r=0}if(!r){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}));const r=(t,n)=>{n.total>0&&(n.percent=n.loaded/n.total*100,100===n.percent&&clearTimeout(e._uploadTimeoutTimer)),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{t.addEventListener("progress",r.bind(null,"download")),t.upload&&t.upload.addEventListener("progress",r.bind(null,"upload"))}catch(e){}t.upload&&this._setUploadTimeout();try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!==this.method&&"HEAD"!==this.method&&"string"!=typeof n&&!this._isHost(n)){const e=this._header["content-type"];let t=this._serializer||y.serialize[e?e.split(";")[0]:""];!t&&_(e)&&(t=y.serialize["application/json"]),t&&(n=t(n))}for(const e in this.header)null!==this.header[e]&&p(this.header,e)&&t.setRequestHeader(e,this.header[e]);this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send(void 0===n?null:n)},y.agent=()=>new h;for(var P=0,w=["GET","POST","OPTIONS","PATCH","PUT","DELETE"];P{const r=y("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},y.head=(e,t,n)=>{const r=y("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},y.options=(e,t,n)=>{const r=y("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.del=E,y.delete=E,y.patch=(e,t,n)=>{const r=y("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.post=(e,t,n)=>{const r=y("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.put=(e,t,n)=>{const r=y("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}}(Vt,Vt.exports);var ei=Vt.exports;function ti(e){var t=(new Date).getTime(),n=(new Date).toISOString(),r=console&&console.log?console:window&&window.console&&window.console.log?window.console:console;r.log("<<<<<"),r.log("[".concat(n,"]"),"\n",e.url,"\n",e.qs),r.log("-----"),e.on("response",(function(n){var o=(new Date).getTime()-t,i=(new Date).toISOString();r.log(">>>>>>"),r.log("[".concat(i," / ").concat(o,"]"),"\n",e.url,"\n",e.qs,"\n",n.text),r.log("-----")}))}function ni(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ti)),this._config.proxy&&this._modules.proxy&&(e=this._modules.proxy.call(this,e)),this._config.keepAlive&&this._modules.keepAlive&&(e=this._modules.keepAlive(e));var o=e;if(t.abortSignal)var i=t.abortSignal.subscribe((function(){o.abort(),i()}));return!0===t.forceBuffered?o="undefined"==typeof Blob?o.buffer().responseType("arraybuffer"):o.responseType("arraybuffer"):!1===t.forceBuffered&&(o=o.buffer(!1)),(o=o.timeout(t.timeout)).on("abort",(function(){return n({category:R.PNUnknownCategory,error:!0,operation:t.operation,errorData:new Error("Aborted")},null)})),o.end((function(e,o){var i,a={};if(a.error=null!==e,a.operation=t.operation,o&&o.status&&(a.statusCode=o.status),e){if(e.response&&e.response.text&&!r._config.logVerbosity)try{a.errorData=JSON.parse(e.response.text)}catch(t){a.errorData=e}else a.errorData=e;return a.category=r._detectErrorCategory(e),n(a,null)}if(t.ignoreBody)i={headers:o.headers,redirects:o.redirects,response:o};else try{i=JSON.parse(o.text)}catch(e){return a.errorData=o,a.error=!0,n(a,null)}return i.error&&1===i.error&&i.status&&i.message&&i.service?(a.errorData=i,a.statusCode=i.status,a.error=!0,a.category=r._detectErrorCategory(a),n(a,null)):(i.error&&i.error.message&&(a.errorData=i.error),n(a,i))})),o}function ri(e,t,n){return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:return r=ei.post(e),t.forEach((function(e){var t=e.key,n=e.value;r=r.field(t,n)})),r.attach("file",n,{contentType:"application/octet-stream"}),[4,r];case 1:return[2,o.sent()]}}))}))}function oi(e,t,n){var r=ei.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ni.call(this,r,t,n)}function ii(e,t,n){var r=ei.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ni.call(this,r,t,n)}function ai(e,t,n,r){var o=ei.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ni.call(this,o,n,r)}function si(e,t,n,r){var o=ei.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ni.call(this,o,n,r)}function ui(e,t,n){var r=ei.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ni.call(this,r,t,n)}function ci(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}var li,pi=function(){function e(){}return Object.defineProperty(e.prototype,"algo",{get:function(){return"aes-256-cbc"},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.encryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.encryptString(n,t)];throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer")}}))}))},e.prototype.decrypt=function(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.decryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.decryptString(n,t)];throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer")}}))}))},e.prototype.encryptFile=function(e,t,n){return o(this,void 0,void 0,(function(){var r,o,a;return i(this,(function(i){switch(i.label){case 0:if(t.data.byteLength<=0)throw new Error("encryption error. empty content");return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.data.arrayBuffer()];case 2:return o=i.sent(),[4,this.encryptArrayBuffer(r,o)];case 3:return a=i.sent(),[2,n.create({name:t.name,mimeType:"application/octet-stream",data:a})]}}))}))},e.prototype.decryptFile=function(e,t,n){return o(this,void 0,void 0,(function(){var r,o,a;return i(this,(function(i){switch(i.label){case 0:return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.data.arrayBuffer()];case 2:return o=i.sent(),[4,this.decryptArrayBuffer(r,o)];case 3:return a=i.sent(),[2,n.create({name:t.name,data:a})]}}))}))},e.prototype.getKey=function(t){return o(this,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,crypto.subtle.digest("SHA-256",e.encoder.encode(t))];case 1:return n=i.sent(),r=Array.from(new Uint8Array(n)).map((function(e){return e.toString(16).padStart(2,"0")})).join(""),o=e.encoder.encode(r.slice(0,32)).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encryptArrayBuffer=function(e,t){return o(this,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return n=crypto.getRandomValues(new Uint8Array(16)),r=ci,o=[n.buffer],[4,crypto.subtle.encrypt({name:"AES-CBC",iv:n},e,t)];case 1:return[2,r.apply(void 0,o.concat([i.sent()]))]}}))}))},e.prototype.decryptArrayBuffer=function(t,n){return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:if(r=n.slice(0,16),n.slice(e.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return[4,crypto.subtle.decrypt({name:"AES-CBC",iv:r},t,n.slice(e.IV_LENGTH))];case 1:return[2,o.sent()]}}))}))},e.prototype.encryptString=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s;return i(this,(function(i){switch(i.label){case 0:return r=crypto.getRandomValues(new Uint8Array(16)),o=e.encoder.encode(n).buffer,[4,crypto.subtle.encrypt({name:"AES-CBC",iv:r},t,o)];case 1:return a=i.sent(),s=ci(r.buffer,a),[2,e.decoder.decode(s)]}}))}))},e.prototype.decryptString=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s;return i(this,(function(i){switch(i.label){case 0:return r=e.encoder.encode(n).buffer,o=r.slice(0,16),a=r.slice(16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:o},t,a)];case 1:return s=i.sent(),[2,e.decoder.decode(s)]}}))}))},e.IV_LENGTH=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),fi=(li=function(){function e(e){if(e instanceof File)this.data=e,this.name=this.data.name,this.mimeType=this.data.type;else if(e.data){var t=e.data;this.data=new File([t],e.name,{type:e.mimeType}),this.name=e.name,e.mimeType&&(this.mimeType=e.mimeType)}if(void 0===this.data)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===this.name)throw new Error("Couldn't guess filename out of the options. Please provide one.")}return e.create=function(e){return new this(e)},e.prototype.toBuffer=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toStream=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toFileUri=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in react native environments.")}))}))},e.prototype.toBlob=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){return[2,this.data]}))}))},e.prototype.toArrayBuffer=function(){return o(this,void 0,void 0,(function(){var e=this;return i(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if(r.result instanceof ArrayBuffer)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsArrayBuffer(e.data)}))]}))}))},e.prototype.toString=function(){return o(this,void 0,void 0,(function(){var e=this;return i(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if("string"==typeof r.result)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsBinaryString(e.data)}))]}))}))},e.prototype.toFile=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){return[2,this.data]}))}))},e}(),li.supportsFile="undefined"!=typeof File,li.supportsBlob="undefined"!=typeof Blob,li.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,li.supportsBuffer=!1,li.supportsStream=!1,li.supportsString=!0,li.supportsEncryptFile=!0,li.supportsFileUri=!1,li),hi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new pi}return Object.defineProperty(e.prototype,"identifier",{get:function(){return""},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e){var t="string"==typeof e?e:(new TextDecoder).decode(e);return{data:this.cryptor.encrypt(t),metadata:null}},e.prototype.decrypt=function(e){var t="string"==typeof e.data?e.data:v(e.data);return this.cryptor.decrypt(t)},e.prototype.encryptFile=function(e,t){var n;return o(this,void 0,void 0,(function(){return i(this,(function(r){return[2,this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)]}))}))},e.prototype.decryptFile=function(e,t){return o(this,void 0,void 0,(function(){return i(this,(function(n){return[2,this.fileCryptor.decryptFile(this.config.cipherKey,e,t)]}))}))},e}(),di=function(){function e(e){this.cipherKey=e.cipherKey,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(this.cipherKey)}return Object.defineProperty(e.prototype,"algo",{get:function(){return"AES-CBC"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return"ACRH"},enumerable:!1,configurable:!0}),e.prototype.getIv=function(){return crypto.getRandomValues(new Uint8Array(e.BLOCK_SIZE))},e.prototype.getKey=function(){return o(this,void 0,void 0,(function(){var t,n;return i(this,(function(r){switch(r.label){case 0:return t=e.encoder.encode(this.cipherKey),[4,crypto.subtle.digest("SHA-256",t.buffer)];case 1:return n=r.sent(),[2,crypto.subtle.importKey("raw",n,this.algo,!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(t){if(0===("string"==typeof t?t:e.decoder.decode(t)).length)throw new Error("encryption error. empty content");var n=this.getIv();return{metadata:n,data:b(this.CryptoJS.AES.encrypt(t,this.encryptedKey,{iv:this.bufferToWordArray(n),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}},e.prototype.decrypt=function(t){var n=this.bufferToWordArray(new Uint8ClampedArray(t.metadata)),r=this.bufferToWordArray(new Uint8ClampedArray(t.data));return e.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:r},this.encryptedKey,{iv:n,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer},e.prototype.encryptFileData=function(e){return o(this,void 0,void 0,(function(){var t,n,r;return i(this,(function(o){switch(o.label){case 0:return[4,this.getKey()];case 1:return t=o.sent(),n=this.getIv(),r={},[4,crypto.subtle.encrypt({name:this.algo,iv:n},t,e)];case 2:return[2,(r.data=o.sent(),r.metadata=n,r)]}}))}))},e.prototype.decryptFileData=function(e){return o(this,void 0,void 0,(function(){var t;return i(this,(function(n){switch(n.label){case 0:return[4,this.getKey()];case 1:return t=n.sent(),[2,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)]}}))}))},e.prototype.bufferToWordArray=function(e){var t,n=[];for(t=0;t0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return r.decrypt({data:t.slice(n.length),metadata:o})},e.prototype.encryptFile=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return i(this,(function(o){switch(o.label){case 0:return this.defaultCryptor.identifier===gi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:[4,this.getFileData(e.data)];case 1:return n=o.sent(),[4,this.defaultCryptor.encryptFileData(n)];case 2:return r=o.sent(),[2,t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(r),r.data)})]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u,c,l,p;return i(this,(function(i){switch(i.label){case 0:return[4,t.data.arrayBuffer()];case 1:return r=i.sent(),o=gi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:[4,this.getFileData(r)];case 2:return s=i.sent(),u=s.slice(o.length-o.metadataLength,o.length),l=(c=n).create,p={name:t.name},[4,this.defaultCryptor.decryptFileData({data:r.slice(o.length),metadata:u})];case 3:return[2,l.apply(c,[(p.data=i.sent(),p)])]}}))}))},e.prototype.getCryptor=function(e){if(""===e){var t=this.getAllCryptors().find((function(e){return""===e.identifier}));if(t)return t;throw new Error("unknown cryptor error")}if(e instanceof bi)return this.getCryptorFromId(e.identifier)},e.prototype.getCryptorFromId=function(e){var t=this.getAllCryptors().find((function(t){return e===t.identifier}));if(t)return t;throw Error("unknown cryptor error")},e.prototype.concatArrayBuffer=function(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer},e.prototype.getHeaderData=function(e){if(e.metadata){var t=gi.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length),r=0;return n.set(t.data,r),r+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),r),n.buffer}},e.prototype.getFileData=function(t){return o(this,void 0,void 0,(function(){return i(this,(function(n){switch(n.label){case 0:return t instanceof Blob?[4,t.arrayBuffer()]:[3,2];case 1:return[2,n.sent()];case 2:if(t instanceof ArrayBuffer)return[2,t];if("string"==typeof t)return[2,e.encoder.encode(t)];throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}}))}))},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),gi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new bi(t,n.byteLength)},e.tryParse=function(t){var n=new Uint8Array(t),r="";if(n.byteLength>=4&&(r=n.slice(0,4),this.decoder.decode(r)!==e.SENTINEL))return"";if(!(n.byteLength>=5))throw new Error("decryption error. invalid header version");if(n[4]>e.MAX_VERSION)throw new Error("unknown cryptor error");var o="",i=5+e.IDENTIFIER_LENGTH;if(!(n.byteLength>=i))throw new Error("decryption error. invalid crypto identifier");o=n.slice(5,i);var a=null;if(!(n.byteLength>=i+1))throw new Error("decryption error. invalid metadata length");return a=n[i],i+=1,255===a&&n.byteLength>=i+2&&(a=new Uint16Array(n.slice(i,i+2)).reduce((function(e,t){return(e<<8)+t}),0),i+=2),new bi(this.decoder.decode(o),a)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e.decoder=new TextDecoder,e}(),bi=function(){function e(e,t){this._identifier=e,this._metadataLength=t}return Object.defineProperty(e.prototype,"identifier",{get:function(){return this._identifier},set:function(e){this._identifier=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"metadataLength",{get:function(){return this._metadataLength},set:function(e){this._metadataLength=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return gi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return gi.SENTINEL.length+1+gi.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){var e=0,t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(gi.SENTINEL)),t[e+=gi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=gi.IDENTIFIER_LENGTH;var r=this.metadataLength;return r<255?t[e]=r:t.set([255,r>>8,255&r],e),t},enumerable:!1,configurable:!0}),e.IDENTIFIER_LENGTH=4,e.SENTINEL="PNED",e}();function vi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var mi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new Ht({del:ui,get:ii,post:ai,patch:si,sendBeacon:vi,getfile:oi,postfile:ri}),t.cbor=new zt((function(e){return qt(f.decode(e))}),b),t.PubNubFile=fi,t.cryptography=new pi,t.initCryptoModule=function(e){return new yi({default:new hi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new di({cipherKey:e.cipherKey})]})},n=e.call(this,t)||this,o&&(window.addEventListener("offline",(function(){n.networkDownDetected()})),window.addEventListener("online",(function(){n.networkUpDetected()}))),n}return t(n,e),n.CryptoModule=yi,n}(Bt);return mi})); diff --git a/karma/web.config.js b/karma/web.config.js index cf1fa285c..40f4299e4 100644 --- a/karma/web.config.js +++ b/karma/web.config.js @@ -42,7 +42,7 @@ module.exports = (config) => { // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['PhantomJS'], + browsers: ['ChromeHeadless'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits diff --git a/lib/core/components/base64_codec.js b/lib/core/components/base64_codec.js index 73b8a4c91..157dd3b04 100644 --- a/lib/core/components/base64_codec.js +++ b/lib/core/components/base64_codec.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.decode = void 0; +exports.encode = exports.decode = void 0; var BASE64_CHARMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; /** * Decode a Base64 encoded string. @@ -48,3 +48,43 @@ function decode(paddedInput) { return data; } exports.decode = decode; +function encode(input) { + var base64 = ''; + var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var bytes = new Uint8Array(input); + var byteLength = bytes.byteLength; + var byteRemainder = byteLength % 3; + var mainLength = byteLength - byteRemainder; + var a, b, c, d; + var chunk; + // Main loop deals with bytes in chunks of 3 + for (var i = 0; i < mainLength; i = i + 3) { + // Combine the three bytes into a single integer + chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + // Use bitmasks to extract 6-bit segments from the triplet + a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 + b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 + c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 + d = chunk & 63; // 63 = 2^6 - 1 + // Convert the raw binary segments to the appropriate ASCII encoding + base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; + } + // Deal with the remaining bytes and padding + if (byteRemainder == 1) { + chunk = bytes[mainLength]; + a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 + // Set the 4 least significant bits to zero + b = (chunk & 3) << 4; // 3 = 2^2 - 1 + base64 += encodings[a] + encodings[b] + '=='; + } + else if (byteRemainder == 2) { + chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; + a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 + b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 + // Set the 2 least significant bits to zero + c = (chunk & 15) << 2; // 15 = 2^4 - 1 + base64 += encodings[a] + encodings[b] + encodings[c] + '='; + } + return base64; +} +exports.encode = encode; diff --git a/lib/core/components/config.js b/lib/core/components/config.js index 5935a795c..599032bff 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -22,7 +22,7 @@ var default_1 = /** @class */ (function () { this.sdkFamily = setup.sdkFamily; this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); - this.setCipherKey(setup.cipherKey); + this.cryptoModule = setup.cryptoModule; this.setFilterExpression(setup.filterExpression); if (typeof setup.origin !== 'string' && !Array.isArray(setup.origin) && setup.origin !== undefined) { throw new Error('Origin must be either undefined, a string or a list of strings.'); @@ -84,6 +84,7 @@ var default_1 = /** @class */ (function () { } this.setUUID(setup.uuid); } + this.setCipherKey(setup.cipherKey, setup); } // exposed setters default_1.prototype.getAuthKey = function () { @@ -93,8 +94,15 @@ var default_1 = /** @class */ (function () { this.authKey = val; return this; }; - default_1.prototype.setCipherKey = function (val) { + default_1.prototype.setCipherKey = function (val, setup, modules) { + var _a; this.cipherKey = val; + if (this.cipherKey) { + this.cryptoModule = + (_a = setup.cryptoModule) !== null && _a !== void 0 ? _a : setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + if (modules) + modules.cryptoModule = this.cryptoModule; + } return this; }; default_1.prototype.getUUID = function () { @@ -172,7 +180,7 @@ var default_1 = /** @class */ (function () { return this; }; default_1.prototype.getVersion = function () { - return '7.2.3'; + return '7.4.5'; }; default_1.prototype.setRetryConfiguration = function (configuration) { if (configuration.minimumdelay < 2) { diff --git a/lib/core/components/subscription_manager.js b/lib/core/components/subscription_manager.js index 6e5bdc4ca..28166718e 100644 --- a/lib/core/components/subscription_manager.js +++ b/lib/core/components/subscription_manager.js @@ -31,7 +31,7 @@ var utils_1 = __importDefault(require("../utils")); var categories_1 = __importDefault(require("../constants/categories")); var default_1 = /** @class */ (function () { function default_1(_a) { - var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager; + var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule; this._listenerManager = listenerManager; this._config = config; this._leaveEndpoint = leaveEndpoint; @@ -40,6 +40,7 @@ var default_1 = /** @class */ (function () { this._subscribeEndpoint = subscribeEndpoint; this._getFileUrl = getFileUrl; this._crypto = crypto; + this._cryptoModule = cryptoModule; this._channels = {}; this._presenceChannels = {}; this._heartbeatChannels = {}; @@ -55,6 +56,8 @@ var default_1 = /** @class */ (function () { this._isOnline = true; this._reconnectionManager = new reconnection_manager_1.default({ timeEndpoint: timeEndpoint }); this._dedupingManager = new deduping_manager_1.default({ config: config }); + if (this._cryptoModule) + this._decoder = new TextDecoder(); } default_1.prototype.adaptStateChange = function (args, callback) { var _this = this; @@ -522,9 +525,18 @@ var default_1 = /** @class */ (function () { announce.timetoken = publishMetaData.publishTimetoken; announce.publisher = message.issuingClientId; var msgPayload = message.payload; - if (_this._config.cipherKey) { - var decryptedPayload = _this._crypto.decrypt(message.payload); - if (typeof decryptedPayload === 'object' && decryptedPayload !== null) { + if (_this._cryptoModule) { + var decryptedPayload = void 0; + try { + var decryptedData = _this._cryptoModule.decrypt(message.payload); + decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; + } + catch (e) { + decryptedPayload = null; + announce.error = "Error while decrypting message content: ".concat(e.message); + } + if (decryptedPayload !== null) { msgPayload = decryptedPayload; } } @@ -558,8 +570,23 @@ var default_1 = /** @class */ (function () { if (message.userMetadata) { announce.userMetadata = message.userMetadata; } - if (_this._config.cipherKey) { - announce.message = _this._crypto.decrypt(message.payload); + if (_this._cryptoModule) { + var decryptedPayload = void 0; + try { + var decryptedData = _this._cryptoModule.decrypt(message.payload); + decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; + } + catch (e) { + decryptedPayload = null; + announce.error = "Error while decrypting message content: ".concat(e.message); + } + if (decryptedPayload != null) { + announce.message = decryptedPayload; + } + else { + announce.message = message.payload; + } } else { announce.message = message.payload; diff --git a/lib/core/endpoints/fetch_messages.js b/lib/core/endpoints/fetch_messages.js index 771bd7792..364e6b698 100644 --- a/lib/core/endpoints/fetch_messages.js +++ b/lib/core/endpoints/fetch_messages.js @@ -8,15 +8,24 @@ exports.handleResponse = exports.prepareParams = exports.isAuthSupported = expor var operations_1 = __importDefault(require("../constants/operations")); var utils_1 = __importDefault(require("../utils")); function __processMessage(modules, message) { - var config = modules.config, crypto = modules.crypto; - if (!config.cipherKey) - return message; + var result = {}; + if (!modules.cryptoModule) { + result.payload = message; + return result; + } try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + result.payload = decryptedPayload; + return result; } catch (e) { - return message; + if (modules.config.logVerbosity && console && console.log) + console.log('decryption error', e.message); + result.payload = message; + result.error = "Error while decrypting message content: ".concat(e.message); } + return result; } function getOperation() { return operations_1.default.PNFetchMessagesOperation; @@ -84,9 +93,10 @@ function handleResponse(modules, serverResponse) { response.channels[channelName] = []; (serverResponse.channels[channelName] || []).forEach(function (messageEnvelope) { var announce = {}; + var processedMessgeResult = __processMessage(modules, messageEnvelope.message); announce.channel = channelName; announce.timetoken = messageEnvelope.timetoken; - announce.message = __processMessage(modules, messageEnvelope.message); + announce.message = processedMessgeResult.payload; announce.messageType = messageEnvelope.message_type; announce.uuid = messageEnvelope.uuid; if (messageEnvelope.actions) { @@ -97,6 +107,8 @@ function handleResponse(modules, serverResponse) { if (messageEnvelope.meta) { announce.meta = messageEnvelope.meta; } + if (processedMessgeResult.error) + announce.error = processedMessgeResult.error; response.channels[channelName].push(announce); }); }); diff --git a/lib/core/endpoints/file_upload/download_file.js b/lib/core/endpoints/file_upload/download_file.js index 7e1621b51..65d4c6ee4 100644 --- a/lib/core/endpoints/file_upload/download_file.js +++ b/lib/core/endpoints/file_upload/download_file.js @@ -1,5 +1,5 @@ "use strict"; -/** */ +// Download_file.js var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -40,6 +40,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); +/** */ var operations_1 = __importDefault(require("../../constants/operations")); var utils_1 = __importDefault(require("../../utils")); var endpoint = { @@ -69,20 +70,28 @@ var endpoint = { forceBuffered: function () { return true; }, prepareParams: function () { return ({}); }, handleResponse: function (_a, res, params) { - var PubNubFile = _a.PubNubFile, config = _a.config, cryptography = _a.cryptography; + var PubNubFile = _a.PubNubFile, config = _a.config, cryptography = _a.cryptography, cryptoModule = _a.cryptoModule; return __awaiter(void 0, void 0, void 0, function () { - var body; - var _b, _c, _d; + var body, _b; + var _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: body = res.response.body; - if (!(PubNubFile.supportsEncryptFile && ((_b = params.cipherKey) !== null && _b !== void 0 ? _b : config.cipherKey))) return [3 /*break*/, 2]; - return [4 /*yield*/, cryptography.decrypt((_c = params.cipherKey) !== null && _c !== void 0 ? _c : config.cipherKey, body)]; + if (!(PubNubFile.supportsEncryptFile && (params.cipherKey || cryptoModule))) return [3 /*break*/, 5]; + if (!(params.cipherKey == null)) return [3 /*break*/, 2]; + return [4 /*yield*/, cryptoModule.decryptFile(PubNubFile.create({ data: body, name: params.name }), PubNubFile)]; case 1: - body = _e.sent(); - _e.label = 2; - case 2: return [2 /*return*/, PubNubFile.create({ + _b = (_e.sent()).data; + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, cryptography.decrypt((_c = params.cipherKey) !== null && _c !== void 0 ? _c : config.cipherKey, body)]; + case 3: + _b = _e.sent(); + _e.label = 4; + case 4: + body = _b; + _e.label = 5; + case 5: return [2 /*return*/, PubNubFile.create({ data: body, name: (_d = res.response.name) !== null && _d !== void 0 ? _d : params.name, mimeType: res.response.type, diff --git a/lib/core/endpoints/file_upload/publish_file.js b/lib/core/endpoints/file_upload/publish_file.js index e03aa7543..9a0a5584a 100644 --- a/lib/core/endpoints/file_upload/publish_file.js +++ b/lib/core/endpoints/file_upload/publish_file.js @@ -6,11 +6,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); var operations_1 = __importDefault(require("../../constants/operations")); var utils_1 = __importDefault(require("../../utils")); -var preparePayload = function (_a, payload) { - var crypto = _a.crypto, config = _a.config; +var base64_codec_1 = require("../../components/base64_codec"); +var preparePayload = function (modules, payload) { var stringifiedPayload = JSON.stringify(payload); - if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + if (modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : (0, base64_codec_1.encode)(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; diff --git a/lib/core/endpoints/file_upload/send_file.js b/lib/core/endpoints/file_upload/send_file.js index ab6bc6873..34aba2be1 100644 --- a/lib/core/endpoints/file_upload/send_file.js +++ b/lib/core/endpoints/file_upload/send_file.js @@ -37,26 +37,15 @@ var __generator = (this && this.__generator) || function (thisArg, body) { }; Object.defineProperty(exports, "__esModule", { value: true }); var endpoint_1 = require("../../components/endpoint"); -var getErrorFromResponse = function (response) { - return new Promise(function (resolve) { - var result = ''; - response.on('data', function (data) { - result += data.toString('utf8'); - }); - response.on('end', function () { - resolve(result); - }); - }); -}; var sendFile = function (_a) { var _this = this; - var generateUploadUrl = _a.generateUploadUrl, publishFile = _a.publishFile, _b = _a.modules, PubNubFile = _b.PubNubFile, config = _b.config, cryptography = _b.cryptography, networking = _b.networking; + var generateUploadUrl = _a.generateUploadUrl, publishFile = _a.publishFile, _b = _a.modules, PubNubFile = _b.PubNubFile, config = _b.config, cryptography = _b.cryptography, cryptoModule = _b.cryptoModule, networking = _b.networking; return function (_a) { var channel = _a.channel, input = _a.file, message = _a.message, cipherKey = _a.cipherKey, meta = _a.meta, ttl = _a.ttl, storeInHistory = _a.storeInHistory; return __awaiter(_this, void 0, void 0, function () { - var file, _b, _c, url, formFields, _d, id, name, formFieldsWithMimeType, result, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, e_1, errorBody, reason, retries, wasSuccessful, publishResult, e_2; - return __generator(this, function (_s) { - switch (_s.label) { + var file, _b, _c, url, formFields, _d, id, name, _e, formFieldsWithMimeType, result, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, e_1, errorBody, reason, retries, wasSuccessful, publishResult, e_2; + return __generator(this, function (_t) { + switch (_t.label) { case 0: if (!channel) { throw new endpoint_1.PubNubError('Validation failed, check status for details', (0, endpoint_1.createValidationError)("channel can't be empty")); @@ -67,13 +56,21 @@ var sendFile = function (_a) { file = PubNubFile.create(input); return [4 /*yield*/, generateUploadUrl({ channel: channel, name: file.name })]; case 1: - _b = _s.sent(), _c = _b.file_upload_request, url = _c.url, formFields = _c.form_fields, _d = _b.data, id = _d.id, name = _d.name; - if (!(PubNubFile.supportsEncryptFile && (cipherKey !== null && cipherKey !== void 0 ? cipherKey : config.cipherKey))) return [3 /*break*/, 3]; - return [4 /*yield*/, cryptography.encryptFile(cipherKey !== null && cipherKey !== void 0 ? cipherKey : config.cipherKey, file, PubNubFile)]; + _b = _t.sent(), _c = _b.file_upload_request, url = _c.url, formFields = _c.form_fields, _d = _b.data, id = _d.id, name = _d.name; + if (!(PubNubFile.supportsEncryptFile && (cipherKey || cryptoModule))) return [3 /*break*/, 6]; + if (!(cipherKey == null)) return [3 /*break*/, 3]; + return [4 /*yield*/, cryptoModule.encryptFile(file, PubNubFile)]; case 2: - file = _s.sent(); - _s.label = 3; - case 3: + _e = _t.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, cryptography.encryptFile(cipherKey, file, PubNubFile)]; + case 4: + _e = _t.sent(); + _t.label = 5; + case 5: + file = _e; + _t.label = 6; + case 6: formFieldsWithMimeType = formFields; if (file.mimeType) { formFieldsWithMimeType = formFields.map(function (entry) { @@ -82,56 +79,57 @@ var sendFile = function (_a) { return entry; }); } - _s.label = 4; - case 4: - _s.trys.push([4, 18, , 22]); - if (!(PubNubFile.supportsFileUri && input.uri)) return [3 /*break*/, 7]; - _f = (_e = networking).POSTFILE; - _g = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toFileUri()]; - case 5: return [4 /*yield*/, _f.apply(_e, _g.concat([_s.sent()]))]; - case 6: - result = _s.sent(); - return [3 /*break*/, 17]; + _t.label = 7; case 7: - if (!PubNubFile.supportsFile) return [3 /*break*/, 10]; - _j = (_h = networking).POSTFILE; - _k = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toFile()]; - case 8: return [4 /*yield*/, _j.apply(_h, _k.concat([_s.sent()]))]; + _t.trys.push([7, 21, , 22]); + if (!(PubNubFile.supportsFileUri && input.uri)) return [3 /*break*/, 10]; + _g = (_f = networking).POSTFILE; + _h = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toFileUri()]; + case 8: return [4 /*yield*/, _g.apply(_f, _h.concat([_t.sent()]))]; case 9: - result = _s.sent(); - return [3 /*break*/, 17]; + result = _t.sent(); + return [3 /*break*/, 20]; case 10: - if (!PubNubFile.supportsBuffer) return [3 /*break*/, 13]; - _m = (_l = networking).POSTFILE; - _o = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toBuffer()]; - case 11: return [4 /*yield*/, _m.apply(_l, _o.concat([_s.sent()]))]; + if (!PubNubFile.supportsFile) return [3 /*break*/, 13]; + _k = (_j = networking).POSTFILE; + _l = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toFile()]; + case 11: return [4 /*yield*/, _k.apply(_j, _l.concat([_t.sent()]))]; case 12: - result = _s.sent(); - return [3 /*break*/, 17]; + result = _t.sent(); + return [3 /*break*/, 20]; case 13: - if (!PubNubFile.supportsBlob) return [3 /*break*/, 16]; - _q = (_p = networking).POSTFILE; - _r = [url, formFieldsWithMimeType]; - return [4 /*yield*/, file.toBlob()]; - case 14: return [4 /*yield*/, _q.apply(_p, _r.concat([_s.sent()]))]; + if (!PubNubFile.supportsBuffer) return [3 /*break*/, 16]; + _o = (_m = networking).POSTFILE; + _p = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toBuffer()]; + case 14: return [4 /*yield*/, _o.apply(_m, _p.concat([_t.sent()]))]; case 15: - result = _s.sent(); - return [3 /*break*/, 17]; - case 16: throw new Error('Unsupported environment'); - case 17: return [3 /*break*/, 22]; + result = _t.sent(); + return [3 /*break*/, 20]; + case 16: + if (!PubNubFile.supportsBlob) return [3 /*break*/, 19]; + _r = (_q = networking).POSTFILE; + _s = [url, formFieldsWithMimeType]; + return [4 /*yield*/, file.toBlob()]; + case 17: return [4 /*yield*/, _r.apply(_q, _s.concat([_t.sent()]))]; case 18: - e_1 = _s.sent(); - if (!e_1.response) return [3 /*break*/, 20]; - return [4 /*yield*/, getErrorFromResponse(e_1.response)]; - case 19: - errorBody = _s.sent(); - reason = /(.*)<\/Message>/gi.exec(errorBody); - throw new endpoint_1.PubNubError(reason ? "Upload to bucket failed: ".concat(reason[1]) : 'Upload to bucket failed.', e_1); - case 20: throw new endpoint_1.PubNubError('Upload to bucket failed.', e_1); - case 21: return [3 /*break*/, 22]; + result = _t.sent(); + return [3 /*break*/, 20]; + case 19: throw new Error('Unsupported environment'); + case 20: return [3 /*break*/, 22]; + case 21: + e_1 = _t.sent(); + if (e_1.response && typeof e_1.response.text === 'string') { + errorBody = e_1.response.text; + reason = /(.*)<\/Message>/gi.exec(errorBody); + throw new endpoint_1.PubNubError(reason ? "Upload to bucket failed: ".concat(reason[1]) : 'Upload to bucket failed.', e_1); + } + else { + throw new endpoint_1.PubNubError('Upload to bucket failed.', e_1); + } + return [3 /*break*/, 22]; case 22: if (result.status !== 204) { throw new endpoint_1.PubNubError('Upload to bucket was unsuccessful', result); @@ -139,9 +137,9 @@ var sendFile = function (_a) { retries = config.fileUploadPublishRetryLimit; wasSuccessful = false; publishResult = { timetoken: '0' }; - _s.label = 23; + _t.label = 23; case 23: - _s.trys.push([23, 25, , 26]); + _t.trys.push([23, 25, , 26]); return [4 /*yield*/, publishFile({ channel: channel, message: message, @@ -153,16 +151,16 @@ var sendFile = function (_a) { })]; case 24: /* eslint-disable-next-line no-await-in-loop */ - publishResult = _s.sent(); + publishResult = _t.sent(); wasSuccessful = true; return [3 /*break*/, 26]; case 25: - e_2 = _s.sent(); + e_2 = _t.sent(); retries -= 1; return [3 /*break*/, 26]; case 26: if (!wasSuccessful && retries > 0) return [3 /*break*/, 23]; - _s.label = 27; + _t.label = 27; case 27: if (!wasSuccessful) { throw new endpoint_1.PubNubError('Publish failed. You may want to execute that operation manually using pubnub.publishFile', { diff --git a/lib/core/endpoints/history/get_history.js b/lib/core/endpoints/history/get_history.js index 239653806..25b636160 100644 --- a/lib/core/endpoints/history/get_history.js +++ b/lib/core/endpoints/history/get_history.js @@ -8,15 +8,24 @@ exports.handleResponse = exports.prepareParams = exports.isAuthSupported = expor var operations_1 = __importDefault(require("../../constants/operations")); var utils_1 = __importDefault(require("../../utils")); function __processMessage(modules, message) { - var config = modules.config, crypto = modules.crypto; - if (!config.cipherKey) - return message; + var result = {}; + if (!modules.cryptoModule) { + result.payload = message; + return result; + } try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + result.payload = decryptedPayload; + return result; } catch (e) { - return message; + if (modules.config.logVerbosity && console && console.log) + console.log('decryption error', e.message); + result.payload = message; + result.error = "Error while decrypting message content: ".concat(e.message); } + return result; } function getOperation() { return operations_1.default.PNHistoryOperation; @@ -73,13 +82,16 @@ function handleResponse(modules, serverResponse) { }; if (Array.isArray(serverResponse[0])) { serverResponse[0].forEach(function (serverHistoryItem) { + var processedMessgeResult = __processMessage(modules, serverHistoryItem.message); var item = { timetoken: serverHistoryItem.timetoken, - entry: __processMessage(modules, serverHistoryItem.message), + entry: processedMessgeResult.payload, }; if (serverHistoryItem.meta) { item.meta = serverHistoryItem.meta; } + if (processedMessgeResult.error) + item.error = processedMessgeResult.error; response.messages.push(item); }); } diff --git a/lib/core/endpoints/history/message_counts.js b/lib/core/endpoints/history/message_counts.js index 5c68dcc51..7beb84974 100644 --- a/lib/core/endpoints/history/message_counts.js +++ b/lib/core/endpoints/history/message_counts.js @@ -1,5 +1,4 @@ "use strict"; -/* */ var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; @@ -34,7 +33,7 @@ function validateParams(modules, incomingParams) { return 'Missing channel'; if (timetoken && channelTimetokens) return 'timetoken and channelTimetokens are incompatible together'; - if (timetoken && channelTimetokens && channelTimetokens.length > 1 && channels.length !== channelTimetokens.length) { + if (channelTimetokens && channelTimetokens.length > 1 && channels.length !== channelTimetokens.length) { return 'Length of channelTimetokens and channels do not match'; } if (!config.subscribeKey) diff --git a/lib/core/endpoints/objects/member/get.js b/lib/core/endpoints/objects/member/get.js index d4b48f70a..e24405856 100644 --- a/lib/core/endpoints/objects/member/get.js +++ b/lib/core/endpoints/objects/member/get.js @@ -26,7 +26,7 @@ var endpoint = { getOperation: function () { return operations_1.default.PNGetMembersOperation; }, validateParams: function (_, params) { if (!(params === null || params === void 0 ? void 0 : params.channel)) { - return 'UUID cannot be empty'; + return 'channel cannot be empty'; } }, getURL: function (_a, params) { @@ -39,36 +39,45 @@ var endpoint = { }, isAuthSupported: function () { return true; }, prepareParams: function (_modules, params) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var queryParams = {}; - queryParams.include = ['uuid.status', 'uuid.type', 'type']; + queryParams.include = []; if (params === null || params === void 0 ? void 0 : params.include) { - if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.customFields) { + if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.statusField) { + queryParams.include.push('status'); + } + if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customFields) { queryParams.include.push('custom'); } - if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customUUIDFields) { + if ((_c = params.include) === null || _c === void 0 ? void 0 : _c.UUIDFields) { + queryParams.include.push('uuid'); + } + if ((_d = params.include) === null || _d === void 0 ? void 0 : _d.customUUIDFields) { queryParams.include.push('uuid.custom'); } - if ((_d = (_c = params.include) === null || _c === void 0 ? void 0 : _c.UUIDFields) !== null && _d !== void 0 ? _d : true) { - queryParams.include.push('uuid'); + if ((_e = params.include) === null || _e === void 0 ? void 0 : _e.UUIDStatusField) { + queryParams.include.push('uuid.status'); + } + if ((_f = params.include) === null || _f === void 0 ? void 0 : _f.UUIDTypeField) { + queryParams.include.push('uuid.type'); } } queryParams.include = queryParams.include.join(','); - if ((_e = params === null || params === void 0 ? void 0 : params.include) === null || _e === void 0 ? void 0 : _e.totalCount) { - queryParams.count = (_f = params.include) === null || _f === void 0 ? void 0 : _f.totalCount; + if ((_g = params === null || params === void 0 ? void 0 : params.include) === null || _g === void 0 ? void 0 : _g.totalCount) { + queryParams.count = (_h = params.include) === null || _h === void 0 ? void 0 : _h.totalCount; } - if ((_g = params === null || params === void 0 ? void 0 : params.page) === null || _g === void 0 ? void 0 : _g.next) { - queryParams.start = (_h = params.page) === null || _h === void 0 ? void 0 : _h.next; + if ((_j = params === null || params === void 0 ? void 0 : params.page) === null || _j === void 0 ? void 0 : _j.next) { + queryParams.start = (_k = params.page) === null || _k === void 0 ? void 0 : _k.next; } - if ((_j = params === null || params === void 0 ? void 0 : params.page) === null || _j === void 0 ? void 0 : _j.prev) { - queryParams.end = (_k = params.page) === null || _k === void 0 ? void 0 : _k.prev; + if ((_l = params === null || params === void 0 ? void 0 : params.page) === null || _l === void 0 ? void 0 : _l.prev) { + queryParams.end = (_m = params.page) === null || _m === void 0 ? void 0 : _m.prev; } if (params === null || params === void 0 ? void 0 : params.filter) { queryParams.filter = params.filter; } - queryParams.limit = (_l = params === null || params === void 0 ? void 0 : params.limit) !== null && _l !== void 0 ? _l : 100; + queryParams.limit = (_o = params === null || params === void 0 ? void 0 : params.limit) !== null && _o !== void 0 ? _o : 100; if (params === null || params === void 0 ? void 0 : params.sort) { - queryParams.sort = Object.entries((_m = params.sort) !== null && _m !== void 0 ? _m : {}).map(function (_a) { + queryParams.sort = Object.entries((_p = params.sort) !== null && _p !== void 0 ? _p : {}).map(function (_a) { var _b = __read(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); diff --git a/lib/core/endpoints/objects/membership/get.js b/lib/core/endpoints/objects/membership/get.js index 329aab48b..0e674260f 100644 --- a/lib/core/endpoints/objects/membership/get.js +++ b/lib/core/endpoints/objects/membership/get.js @@ -37,36 +37,45 @@ var endpoint = { }, isAuthSupported: function () { return true; }, prepareParams: function (_modules, params) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var queryParams = {}; - queryParams.include = ['channel.status', 'channel.type', 'status']; + queryParams.include = []; if (params === null || params === void 0 ? void 0 : params.include) { - if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.customFields) { - queryParams.include.push('custom'); + if ((_a = params.include) === null || _a === void 0 ? void 0 : _a.statusField) { + queryParams.include.push('status'); } - if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customChannelFields) { - queryParams.include.push('channel.custom'); + if ((_b = params.include) === null || _b === void 0 ? void 0 : _b.customFields) { + queryParams.include.push('custom'); } if ((_c = params.include) === null || _c === void 0 ? void 0 : _c.channelFields) { queryParams.include.push('channel'); } + if ((_d = params.include) === null || _d === void 0 ? void 0 : _d.customChannelFields) { + queryParams.include.push('channel.custom'); + } + if ((_e = params.include) === null || _e === void 0 ? void 0 : _e.channelStatusField) { + queryParams.include.push('channel.status'); + } + if ((_f = params.include) === null || _f === void 0 ? void 0 : _f.channelTypeField) { + queryParams.include.push('channel.type'); + } } queryParams.include = queryParams.include.join(','); - if ((_d = params === null || params === void 0 ? void 0 : params.include) === null || _d === void 0 ? void 0 : _d.totalCount) { - queryParams.count = (_e = params.include) === null || _e === void 0 ? void 0 : _e.totalCount; + if ((_g = params === null || params === void 0 ? void 0 : params.include) === null || _g === void 0 ? void 0 : _g.totalCount) { + queryParams.count = (_h = params.include) === null || _h === void 0 ? void 0 : _h.totalCount; } - if ((_f = params === null || params === void 0 ? void 0 : params.page) === null || _f === void 0 ? void 0 : _f.next) { - queryParams.start = (_g = params.page) === null || _g === void 0 ? void 0 : _g.next; + if ((_j = params === null || params === void 0 ? void 0 : params.page) === null || _j === void 0 ? void 0 : _j.next) { + queryParams.start = (_k = params.page) === null || _k === void 0 ? void 0 : _k.next; } - if ((_h = params === null || params === void 0 ? void 0 : params.page) === null || _h === void 0 ? void 0 : _h.prev) { - queryParams.end = (_j = params.page) === null || _j === void 0 ? void 0 : _j.prev; + if ((_l = params === null || params === void 0 ? void 0 : params.page) === null || _l === void 0 ? void 0 : _l.prev) { + queryParams.end = (_m = params.page) === null || _m === void 0 ? void 0 : _m.prev; } if (params === null || params === void 0 ? void 0 : params.filter) { queryParams.filter = params.filter; } - queryParams.limit = (_k = params === null || params === void 0 ? void 0 : params.limit) !== null && _k !== void 0 ? _k : 100; + queryParams.limit = (_o = params === null || params === void 0 ? void 0 : params.limit) !== null && _o !== void 0 ? _o : 100; if (params === null || params === void 0 ? void 0 : params.sort) { - queryParams.sort = Object.entries((_l = params.sort) !== null && _l !== void 0 ? _l : {}).map(function (_a) { + queryParams.sort = Object.entries((_p = params.sort) !== null && _p !== void 0 ? _p : {}).map(function (_a) { var _b = __read(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); diff --git a/lib/core/endpoints/publish.js b/lib/core/endpoints/publish.js index 2e45b6db6..6799ecc64 100644 --- a/lib/core/endpoints/publish.js +++ b/lib/core/endpoints/publish.js @@ -7,14 +7,15 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.handleResponse = exports.prepareParams = exports.postPayload = exports.isAuthSupported = exports.getRequestTimeout = exports.postURL = exports.getURL = exports.usePost = exports.validateParams = exports.getOperation = void 0; var operations_1 = __importDefault(require("../constants/operations")); var utils_1 = __importDefault(require("../utils")); +var base64_codec_1 = require("../components/base64_codec"); function prepareMessagePayload(modules, messagePayload) { - var crypto = modules.crypto, config = modules.config; var stringifiedPayload = JSON.stringify(messagePayload); - if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + if (modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : (0, base64_codec_1.encode)(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } - return stringifiedPayload; + return stringifiedPayload || ''; } function getOperation() { return operations_1.default.PNPublishOperation; diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index b37ef62f0..9083aa242 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -75,6 +75,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); var config_1 = __importDefault(require("./components/config")); var index_1 = __importDefault(require("./components/cryptography/index")); +var base64_codec_1 = require("./components/base64_codec"); var subscription_manager_1 = __importDefault(require("./components/subscription_manager")); var telemetry_manager_1 = __importDefault(require("./components/telemetry_manager")); var push_payload_1 = __importDefault(require("./components/push_payload")); @@ -158,6 +159,7 @@ var default_1 = /** @class */ (function () { maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; + var cryptoModule = this._config.cryptoModule; var modules = { config: config, networking: networking, @@ -166,10 +168,23 @@ var default_1 = /** @class */ (function () { tokenManager: tokenManager, telemetryManager: telemetryManager, PubNubFile: setup.PubNubFile, + cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; - this.encryptFile = function (key, file) { return cryptography.encryptFile(key, file, _this.File); }; - this.decryptFile = function (key, file) { return cryptography.decryptFile(key, file, _this.File); }; + this.encryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { + file = key; + return modules.cryptoModule.encryptFile(file, this.File); + } + return cryptography.encryptFile(key, file, this.File); + }; + this.decryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { + file = key; + return modules.cryptoModule.decryptFile(file, this.File); + } + return cryptography.decryptFile(key, file, this.File); + }; var timeEndpoint = endpoint_1.default.bind(this, modules, timeEndpointConfig); var leaveEndpoint = endpoint_1.default.bind(this, modules, presenceLeaveEndpointConfig); var heartbeatEndpoint = endpoint_1.default.bind(this, modules, presenceHeartbeatEndpointConfig); @@ -260,6 +275,7 @@ var default_1 = /** @class */ (function () { config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, + cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -488,6 +504,9 @@ var default_1 = /** @class */ (function () { customFields: params.include.customFields, UUIDFields: params.include.userFields, customUUIDFields: params.include.customUserFields, + statusField: params.include.statusField, + UUIDStatusField: params.include.userStatusField, + UUIDTypeField: params.include.userTypeField, totalCount: params.include.totalCount, }, sort: params.sort != null @@ -521,6 +540,9 @@ var default_1 = /** @class */ (function () { customFields: params.include.customFields, channelFields: params.include.spaceFields, customChannelFields: params.include.customSpaceFields, + statusField: params.include.statusField, + channelStatusField: params.include.spaceStatusField, + channelTypeField: params.include.spaceTypeField, totalCount: params.include.totalCount, }, sort: params.sort != null @@ -549,16 +571,35 @@ var default_1 = /** @class */ (function () { this.stop = this.destroy; // -------- // --- deprecated ------------------ // mount crypto - this.encrypt = crypto.encrypt.bind(crypto); - this.decrypt = crypto.decrypt.bind(crypto); + this.encrypt = function (data, key) { + if (typeof key === 'undefined' && modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(data); + return typeof encrypted === 'string' ? encrypted : (0, base64_codec_1.encode)(encrypted); + } + else { + return crypto.encrypt(data, key); + } + }; + this.decrypt = function (data, key) { + if (typeof key === 'undefined' && cryptoModule) { + var decrypted = modules.cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decrypted)) : decrypted; + } + else { + return crypto.decrypt(data, key); + } + }; /* config */ this.getAuthKey = modules.config.getAuthKey.bind(modules.config); this.setAuthKey = modules.config.setAuthKey.bind(modules.config); - this.setCipherKey = modules.config.setCipherKey.bind(modules.config); this.getUUID = modules.config.getUUID.bind(modules.config); this.setUUID = modules.config.setUUID.bind(modules.config); + this.getUserId = modules.config.getUserId.bind(modules.config); + this.setUserId = modules.config.setUserId.bind(modules.config); this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config); this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config); + // this.setCipherKey = modules.config.setCipherKey.bind(modules.config); + this.setCipherKey = function (key) { return modules.config.setCipherKey(key, setup, modules); }; this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { this.setProxy = function (proxy) { diff --git a/lib/core/utils.js b/lib/core/utils.js index 7c14a4a87..3859102bc 100644 --- a/lib/core/utils.js +++ b/lib/core/utils.js @@ -26,9 +26,18 @@ function createPromise() { }); return { promise: promise, reject: failureResolve, fulfill: successResolve }; } +function stringToArrayBuffer(str) { + var buf = new ArrayBuffer(str.length * 2); + var bufView = new Uint16Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; +} module.exports = { signPamFromParams: signPamFromParams, endsWith: endsWith, createPromise: createPromise, encodeString: encodeString, + stringToArrayBuffer: stringToArrayBuffer, }; diff --git a/lib/crypto/modules/NodeCryptoModule/ICryptor.js b/lib/crypto/modules/NodeCryptoModule/ICryptor.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/ICryptor.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js new file mode 100644 index 000000000..fdaef2d94 --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -0,0 +1,446 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; +var stream_1 = require("stream"); +var base64_codec_1 = require("../../../core/components/base64_codec"); +var legacyCryptor_1 = __importDefault(require("./legacyCryptor")); +exports.LegacyCryptor = legacyCryptor_1.default; +var aesCbcCryptor_1 = __importDefault(require("./aesCbcCryptor")); +exports.AesCbcCryptor = aesCbcCryptor_1.default; +var CryptoModule = /** @class */ (function () { + function CryptoModule(cryptoModuleConfiguration) { + var _a; + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: type detection issue with old Config type assignment + CryptoModule.legacyCryptoModule = function (config) { + var _a; + return new this({ + default: new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + var _a; + return new this({ + default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), + cryptors: [ + new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], + }); + }; + CryptoModule.withDefaultCryptor = function (defaultCryptor) { + return new this({ default: defaultCryptor }); + }; + CryptoModule.prototype.getAllCryptors = function () { + return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); + }; + CryptoModule.prototype.getLegacyCryptor = function () { + return this.getAllCryptors().find(function (c) { return c.identifier === ''; }); + }; + CryptoModule.prototype.encrypt = function (data) { + var encrypted = this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) + return encrypted.data; + var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + var headerData = new Uint8Array(header.length); + var pos = 0; + headerData.set(header.data, pos); + pos = header.length - encrypted.metadata.length; + headerData.set(encrypted.metadata, pos); + return Buffer.concat([headerData, Buffer.from(encrypted.data)]); + }; + CryptoModule.prototype.decrypt = function (data) { + var encryptedData = Buffer.from(typeof data === 'string' ? (0, base64_codec_1.decode)(data) : data); + var header = CryptorHeader.tryParse(encryptedData); + var cryptor = this.getCryptor(header); + var metadata = header.length > 0 + ? encryptedData.slice(header.length - header.metadataLength, header.length) + : null; + if (encryptedData.slice(header.length).byteLength <= 0) + throw new Error('decryption error. empty content'); + return cryptor.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + }; + CryptoModule.prototype.encryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var encryptedStream, header, payload, pos, output; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on intsance type) + */ + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + if (file.data instanceof Buffer) { + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: Buffer.from(this.encrypt(file.data)), + })]; + } + if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 2]; + if (file.contentLength === 0) + throw new Error('encryption error. empty content'); + return [4 /*yield*/, this.defaultCryptor.encryptStream(file.data)]; + case 1: + encryptedStream = _a.sent(); + header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); + payload = new Uint8Array(header.length); + pos = 0; + payload.set(header.data, pos); + pos += header.length; + if (encryptedStream.metadata) { + pos -= encryptedStream.metadata.length; + payload.set(encryptedStream.metadata, pos); + } + output = new stream_1.PassThrough(); + output.write(payload); + encryptedStream.stream.pipe(output); + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: output, + })]; + case 2: return [2 /*return*/]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var header, cryptor, stream_2; + var _this = this; + return __generator(this, function (_a) { + if ((file === null || file === void 0 ? void 0 : file.data) instanceof Buffer) { + header = CryptorHeader.tryParse(file.data); + cryptor = this.getCryptor(header); + /** + * If It's legacyone then redirect it. + * (as long as we support legacy need to check on instance type) + */ + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) + return [2 /*return*/, cryptor.decryptFile(file, File)]; + return [2 /*return*/, File.create({ + name: file.name, + data: Buffer.from(this.decrypt(file === null || file === void 0 ? void 0 : file.data)), + })]; + } + if (file.data instanceof stream_1.Readable) { + stream_2 = file.data; + return [2 /*return*/, new Promise(function (resolve) { + stream_2.on('readable', function () { return resolve(_this.onStreamReadable(stream_2, file, File)); }); + })]; + } + return [2 /*return*/]; + }); + }); + }; + CryptoModule.prototype.onStreamReadable = function (stream, file, File) { + return __awaiter(this, void 0, void 0, function () { + var magicBytes, versionByte, identifier, cryptor, headerSize, _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + stream.removeAllListeners('readable'); + magicBytes = stream.read(4); + if (!CryptorHeader.isSentinel(magicBytes)) { + if (magicBytes === null) + throw new Error('decryption error. empty content'); + stream.unshift(magicBytes); + return [2 /*return*/, this.decryptLegacyFileStream(stream, file, File)]; + } + versionByte = stream.read(1); + CryptorHeader.validateVersion(versionByte[0]); + identifier = stream.read(4); + cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier)); + headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream); + if (file.contentLength <= CryptorHeader.MIN_HEADER_LEGTH + headerSize) + throw new Error('decryption error. empty content'); + _b = (_a = File).create; + _c = { + name: file.name, + mimeType: 'application/octet-stream' + }; + return [4 /*yield*/, cryptor.decryptStream({ stream: stream, metadataLength: headerSize })]; + case 1: return [2 /*return*/, _b.apply(_a, [(_c.stream = _d.sent(), + _c)])]; + } + }); + }); + }; + CryptoModule.prototype.decryptLegacyFileStream = function (stream, file, File) { + return __awaiter(this, void 0, void 0, function () { + var cryptor; + return __generator(this, function (_a) { + if (file.contentLength <= 16) + throw new Error('decryption error: empty content'); + cryptor = this.getLegacyCryptor(); + if (cryptor) { + return [2 /*return*/, cryptor.decryptFile(File.create({ + name: file.name, + stream: stream, + }), File)]; + } + else { + throw new Error('unknown cryptor error'); + } + return [2 /*return*/]; + }); + }); + }; + CryptoModule.prototype.getCryptor = function (header) { + if (header === '') { + var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); + if (cryptor) + return cryptor; + throw new Error('unknown cryptor error'); + } + else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + }; + CryptoModule.prototype.getCryptorFromId = function (id) { + var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; }); + if (cryptor) { + return cryptor; + } + throw new Error('unknown cryptor error'); + }; + CryptoModule.LEGACY_IDENTIFIER = ''; + return CryptoModule; +}()); +exports.CryptoModule = CryptoModule; +// CryptorHeader Utility +var CryptorHeader = /** @class */ (function () { + function CryptorHeader() { + } + CryptorHeader.from = function (id, metadata) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) + return; + return new CryptorHeaderV1(id, metadata.length); + }; + CryptorHeader.isSentinel = function (bytes) { + if (bytes && bytes.byteLength >= 4) { + if (bytes.toString('utf8') == CryptorHeader.SENTINEL) + return true; + } + }; + CryptorHeader.validateVersion = function (data) { + if (data && data > CryptorHeader.MAX_VERSION) + throw new Error('decryption error. invalid header version'); + return data; + }; + CryptorHeader.tryGetIdentifier = function (data) { + if (data.byteLength < 4) { + throw new Error('unknown cryptor error. decryption failed'); + } + else { + return data.toString('utf8'); + } + }; + CryptorHeader.tryGetMetadataSizeFromStream = function (stream) { + var sizeBuf = stream.read(1); + if (sizeBuf && sizeBuf[0] < 255) { + return sizeBuf[0]; + } + if (sizeBuf[0] === 255) { + var nextBuf = stream.read(2); + if (nextBuf.length >= 2) { + return new Uint16Array([nextBuf[0], nextBuf[1]]).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + } + } + throw new Error('decryption error. Invalid metadata size'); + }; + CryptorHeader.tryParse = function (encryptedData) { + var sentinel = ''; + var version = null; + if (encryptedData.length >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) + return ''; + } + if (encryptedData.length >= 5) { + version = encryptedData[4]; + } + else { + throw new Error('decryption error. invalid header version'); + } + if (version > CryptorHeader.MAX_VERSION) + throw new Error('unknown cryptor error'); + var identifier; + var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.length >= pos) { + identifier = encryptedData.slice(5, pos); + } + else { + throw new Error('decryption error. invalid crypto identifier'); + } + var metadataLength = null; + if (encryptedData.length >= pos + 1) { + metadataLength = encryptedData[pos]; + } + else { + throw new Error('decryption error. invalid metadata length'); + } + pos += 1; + if (metadataLength === 255 && encryptedData.length >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + CryptorHeader.MIN_HEADER_LEGTH = 10; + return CryptorHeader; +}()); +// v1 CryptorHeader +var CryptorHeaderV1 = /** @class */ (function () { + function CryptorHeaderV1(id, metadataLength) { + this._identifier = id; + this._metadataLength = metadataLength; + } + Object.defineProperty(CryptorHeaderV1.prototype, "identifier", { + get: function () { + return this._identifier; + }, + set: function (value) { + this._identifier = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "metadataLength", { + get: function () { + return this._metadataLength; + }, + set: function (value) { + this._metadataLength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "version", { + get: function () { + return CryptorHeader.VERSION; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "length", { + get: function () { + return (CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "data", { + get: function () { + var pos = 0; + var header = new Uint8Array(this.length); + header.set(Buffer.from(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(Buffer.from(this.identifier), pos); + pos += CryptorHeader.IDENTIFIER_LENGTH; + var metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; + } + else { + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + } + return header; + }, + enumerable: false, + configurable: true + }); + return CryptorHeaderV1; +}()); diff --git a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js new file mode 100644 index 000000000..613e8cfec --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js @@ -0,0 +1,146 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var stream_1 = require("stream"); +var crypto_1 = require("crypto"); +var AesCbcCryptor = /** @class */ (function () { + function AesCbcCryptor(configuration) { + this.cipherKey = configuration.cipherKey; + } + Object.defineProperty(AesCbcCryptor.prototype, "algo", { + get: function () { + return 'aes-256-cbc'; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AesCbcCryptor.prototype, "identifier", { + get: function () { + return 'ACRH'; + }, + enumerable: false, + configurable: true + }); + AesCbcCryptor.prototype.getIv = function () { + return (0, crypto_1.randomBytes)(AesCbcCryptor.BLOCK_SIZE); + }; + AesCbcCryptor.prototype.getKey = function () { + var sha = (0, crypto_1.createHash)('sha256'); + sha.update(Buffer.from(this.cipherKey, 'utf8')); + return Buffer.from(sha.digest()); + }; + AesCbcCryptor.prototype.encrypt = function (data) { + var iv = this.getIv(); + var key = this.getKey(); + var plainData = typeof data === 'string' ? new TextEncoder().encode(data) : data; + var bPlain = Buffer.from(plainData); + if (bPlain.byteLength === 0) + throw new Error('encryption error. empty content'); + var aes = (0, crypto_1.createCipheriv)(this.algo, key, iv); + return { + metadata: iv, + data: Buffer.concat([aes.update(bPlain), aes.final()]), + }; + }; + AesCbcCryptor.prototype.decrypt = function (encryptedData) { + var data = typeof encryptedData.data === 'string' ? new TextEncoder().encode(encryptedData.data) : encryptedData.data; + if (data.byteLength <= 0) + throw new Error('decryption error: empty content'); + var aes = (0, crypto_1.createDecipheriv)(this.algo, this.getKey(), encryptedData.metadata); + return Uint8Array.from(Buffer.concat([aes.update(data), aes.final()])).buffer; + }; + AesCbcCryptor.prototype.encryptStream = function (stream) { + return __awaiter(this, void 0, void 0, function () { + var output, bIv, aes; + return __generator(this, function (_a) { + output = new stream_1.PassThrough(); + bIv = this.getIv(); + if (stream.readable === false) + throw new Error('encryption error. empty stream'); + aes = (0, crypto_1.createCipheriv)(this.algo, this.getKey(), bIv); + stream.pipe(aes).pipe(output); + return [2 /*return*/, { + stream: output, + metadata: bIv, + metadataLength: AesCbcCryptor.BLOCK_SIZE, + }]; + }); + }); + }; + AesCbcCryptor.prototype.decryptStream = function (encryptedStream) { + return __awaiter(this, void 0, void 0, function () { + var decryptedStream, bIv, aes, onReadable; + var _this = this; + return __generator(this, function (_a) { + decryptedStream = new stream_1.PassThrough(); + bIv = Buffer.alloc(0); + aes = null; + onReadable = function () { + var data = encryptedStream.stream.read(); + while (data !== null) { + if (data) { + var bChunk = Buffer.from(data); + var sliceLen = encryptedStream.metadataLength - bIv.byteLength; + if (bChunk.byteLength < sliceLen) { + bIv = Buffer.concat([bIv, bChunk]); + } + else { + bIv = Buffer.concat([bIv, bChunk.slice(0, sliceLen)]); + aes = (0, crypto_1.createDecipheriv)(_this.algo, _this.getKey(), bIv); + aes.pipe(decryptedStream); + aes.write(bChunk.slice(sliceLen)); + } + } + data = encryptedStream.stream.read(); + } + }; + encryptedStream.stream.on('readable', onReadable); + encryptedStream.stream.on('end', function () { + if (aes) { + aes.end(); + } + decryptedStream.end(); + }); + return [2 /*return*/, decryptedStream]; + }); + }); + }; + AesCbcCryptor.BLOCK_SIZE = 16; + return AesCbcCryptor; +}()); +exports.default = AesCbcCryptor; diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js new file mode 100644 index 000000000..21273869f --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -0,0 +1,86 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var index_1 = __importDefault(require("../../../core/components/cryptography/index")); +var base64_codec_1 = require("../../../core/components/base64_codec"); +var node_1 = __importDefault(require("../node")); +var LegacyCryptor = /** @class */ (function () { + function LegacyCryptor(config) { + this.config = config; + this.cryptor = new index_1.default({ config: config }); + this.fileCryptor = new node_1.default(); + } + Object.defineProperty(LegacyCryptor.prototype, "identifier", { + get: function () { + return ''; + }, + enumerable: false, + configurable: true + }); + LegacyCryptor.prototype.encrypt = function (data) { + if (data.length === 0) + throw new Error('encryption error. empty content'); + return { + data: this.cryptor.encrypt(data), + metadata: null, + }; + }; + LegacyCryptor.prototype.decrypt = function (encryptedData) { + var data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data); + return this.cryptor.decrypt(data); + }; + LegacyCryptor.prototype.encryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, this.fileCryptor.encryptFile(this.config.cipherKey, file, File)]; + }); + }); + }; + LegacyCryptor.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)]; + }); + }); + }; + return LegacyCryptor; +}()); +exports.default = LegacyCryptor; diff --git a/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js new file mode 100644 index 000000000..fdaef2d94 --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js @@ -0,0 +1,446 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; +var stream_1 = require("stream"); +var base64_codec_1 = require("../../../core/components/base64_codec"); +var legacyCryptor_1 = __importDefault(require("./legacyCryptor")); +exports.LegacyCryptor = legacyCryptor_1.default; +var aesCbcCryptor_1 = __importDefault(require("./aesCbcCryptor")); +exports.AesCbcCryptor = aesCbcCryptor_1.default; +var CryptoModule = /** @class */ (function () { + function CryptoModule(cryptoModuleConfiguration) { + var _a; + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: type detection issue with old Config type assignment + CryptoModule.legacyCryptoModule = function (config) { + var _a; + return new this({ + default: new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + var _a; + return new this({ + default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), + cryptors: [ + new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], + }); + }; + CryptoModule.withDefaultCryptor = function (defaultCryptor) { + return new this({ default: defaultCryptor }); + }; + CryptoModule.prototype.getAllCryptors = function () { + return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); + }; + CryptoModule.prototype.getLegacyCryptor = function () { + return this.getAllCryptors().find(function (c) { return c.identifier === ''; }); + }; + CryptoModule.prototype.encrypt = function (data) { + var encrypted = this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) + return encrypted.data; + var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + var headerData = new Uint8Array(header.length); + var pos = 0; + headerData.set(header.data, pos); + pos = header.length - encrypted.metadata.length; + headerData.set(encrypted.metadata, pos); + return Buffer.concat([headerData, Buffer.from(encrypted.data)]); + }; + CryptoModule.prototype.decrypt = function (data) { + var encryptedData = Buffer.from(typeof data === 'string' ? (0, base64_codec_1.decode)(data) : data); + var header = CryptorHeader.tryParse(encryptedData); + var cryptor = this.getCryptor(header); + var metadata = header.length > 0 + ? encryptedData.slice(header.length - header.metadataLength, header.length) + : null; + if (encryptedData.slice(header.length).byteLength <= 0) + throw new Error('decryption error. empty content'); + return cryptor.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + }; + CryptoModule.prototype.encryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var encryptedStream, header, payload, pos, output; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on intsance type) + */ + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + if (file.data instanceof Buffer) { + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: Buffer.from(this.encrypt(file.data)), + })]; + } + if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 2]; + if (file.contentLength === 0) + throw new Error('encryption error. empty content'); + return [4 /*yield*/, this.defaultCryptor.encryptStream(file.data)]; + case 1: + encryptedStream = _a.sent(); + header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); + payload = new Uint8Array(header.length); + pos = 0; + payload.set(header.data, pos); + pos += header.length; + if (encryptedStream.metadata) { + pos -= encryptedStream.metadata.length; + payload.set(encryptedStream.metadata, pos); + } + output = new stream_1.PassThrough(); + output.write(payload); + encryptedStream.stream.pipe(output); + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: output, + })]; + case 2: return [2 /*return*/]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var header, cryptor, stream_2; + var _this = this; + return __generator(this, function (_a) { + if ((file === null || file === void 0 ? void 0 : file.data) instanceof Buffer) { + header = CryptorHeader.tryParse(file.data); + cryptor = this.getCryptor(header); + /** + * If It's legacyone then redirect it. + * (as long as we support legacy need to check on instance type) + */ + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) + return [2 /*return*/, cryptor.decryptFile(file, File)]; + return [2 /*return*/, File.create({ + name: file.name, + data: Buffer.from(this.decrypt(file === null || file === void 0 ? void 0 : file.data)), + })]; + } + if (file.data instanceof stream_1.Readable) { + stream_2 = file.data; + return [2 /*return*/, new Promise(function (resolve) { + stream_2.on('readable', function () { return resolve(_this.onStreamReadable(stream_2, file, File)); }); + })]; + } + return [2 /*return*/]; + }); + }); + }; + CryptoModule.prototype.onStreamReadable = function (stream, file, File) { + return __awaiter(this, void 0, void 0, function () { + var magicBytes, versionByte, identifier, cryptor, headerSize, _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + stream.removeAllListeners('readable'); + magicBytes = stream.read(4); + if (!CryptorHeader.isSentinel(magicBytes)) { + if (magicBytes === null) + throw new Error('decryption error. empty content'); + stream.unshift(magicBytes); + return [2 /*return*/, this.decryptLegacyFileStream(stream, file, File)]; + } + versionByte = stream.read(1); + CryptorHeader.validateVersion(versionByte[0]); + identifier = stream.read(4); + cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier)); + headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream); + if (file.contentLength <= CryptorHeader.MIN_HEADER_LEGTH + headerSize) + throw new Error('decryption error. empty content'); + _b = (_a = File).create; + _c = { + name: file.name, + mimeType: 'application/octet-stream' + }; + return [4 /*yield*/, cryptor.decryptStream({ stream: stream, metadataLength: headerSize })]; + case 1: return [2 /*return*/, _b.apply(_a, [(_c.stream = _d.sent(), + _c)])]; + } + }); + }); + }; + CryptoModule.prototype.decryptLegacyFileStream = function (stream, file, File) { + return __awaiter(this, void 0, void 0, function () { + var cryptor; + return __generator(this, function (_a) { + if (file.contentLength <= 16) + throw new Error('decryption error: empty content'); + cryptor = this.getLegacyCryptor(); + if (cryptor) { + return [2 /*return*/, cryptor.decryptFile(File.create({ + name: file.name, + stream: stream, + }), File)]; + } + else { + throw new Error('unknown cryptor error'); + } + return [2 /*return*/]; + }); + }); + }; + CryptoModule.prototype.getCryptor = function (header) { + if (header === '') { + var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); + if (cryptor) + return cryptor; + throw new Error('unknown cryptor error'); + } + else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + }; + CryptoModule.prototype.getCryptorFromId = function (id) { + var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; }); + if (cryptor) { + return cryptor; + } + throw new Error('unknown cryptor error'); + }; + CryptoModule.LEGACY_IDENTIFIER = ''; + return CryptoModule; +}()); +exports.CryptoModule = CryptoModule; +// CryptorHeader Utility +var CryptorHeader = /** @class */ (function () { + function CryptorHeader() { + } + CryptorHeader.from = function (id, metadata) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) + return; + return new CryptorHeaderV1(id, metadata.length); + }; + CryptorHeader.isSentinel = function (bytes) { + if (bytes && bytes.byteLength >= 4) { + if (bytes.toString('utf8') == CryptorHeader.SENTINEL) + return true; + } + }; + CryptorHeader.validateVersion = function (data) { + if (data && data > CryptorHeader.MAX_VERSION) + throw new Error('decryption error. invalid header version'); + return data; + }; + CryptorHeader.tryGetIdentifier = function (data) { + if (data.byteLength < 4) { + throw new Error('unknown cryptor error. decryption failed'); + } + else { + return data.toString('utf8'); + } + }; + CryptorHeader.tryGetMetadataSizeFromStream = function (stream) { + var sizeBuf = stream.read(1); + if (sizeBuf && sizeBuf[0] < 255) { + return sizeBuf[0]; + } + if (sizeBuf[0] === 255) { + var nextBuf = stream.read(2); + if (nextBuf.length >= 2) { + return new Uint16Array([nextBuf[0], nextBuf[1]]).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + } + } + throw new Error('decryption error. Invalid metadata size'); + }; + CryptorHeader.tryParse = function (encryptedData) { + var sentinel = ''; + var version = null; + if (encryptedData.length >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) + return ''; + } + if (encryptedData.length >= 5) { + version = encryptedData[4]; + } + else { + throw new Error('decryption error. invalid header version'); + } + if (version > CryptorHeader.MAX_VERSION) + throw new Error('unknown cryptor error'); + var identifier; + var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.length >= pos) { + identifier = encryptedData.slice(5, pos); + } + else { + throw new Error('decryption error. invalid crypto identifier'); + } + var metadataLength = null; + if (encryptedData.length >= pos + 1) { + metadataLength = encryptedData[pos]; + } + else { + throw new Error('decryption error. invalid metadata length'); + } + pos += 1; + if (metadataLength === 255 && encryptedData.length >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + CryptorHeader.MIN_HEADER_LEGTH = 10; + return CryptorHeader; +}()); +// v1 CryptorHeader +var CryptorHeaderV1 = /** @class */ (function () { + function CryptorHeaderV1(id, metadataLength) { + this._identifier = id; + this._metadataLength = metadataLength; + } + Object.defineProperty(CryptorHeaderV1.prototype, "identifier", { + get: function () { + return this._identifier; + }, + set: function (value) { + this._identifier = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "metadataLength", { + get: function () { + return this._metadataLength; + }, + set: function (value) { + this._metadataLength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "version", { + get: function () { + return CryptorHeader.VERSION; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "length", { + get: function () { + return (CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "data", { + get: function () { + var pos = 0; + var header = new Uint8Array(this.length); + header.set(Buffer.from(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(Buffer.from(this.identifier), pos); + pos += CryptorHeader.IDENTIFIER_LENGTH; + var metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; + } + else { + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + } + return header; + }, + enumerable: false, + configurable: true + }); + return CryptorHeaderV1; +}()); diff --git a/lib/crypto/modules/WebCryptoModule/ICryptor.js b/lib/crypto/modules/WebCryptoModule/ICryptor.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/ICryptor.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/crypto/modules/WebCryptoModule/ILegacyCryptor.js b/lib/crypto/modules/WebCryptoModule/ILegacyCryptor.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/ILegacyCryptor.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js new file mode 100644 index 000000000..d80cbbb15 --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js @@ -0,0 +1,148 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var hmac_sha256_1 = __importDefault(require("../../../core/components/cryptography/hmac-sha256")); +var base64_codec_1 = require("../../../core/components/base64_codec"); +var AesCbcCryptor = /** @class */ (function () { + function AesCbcCryptor(configuration) { + this.cipherKey = configuration.cipherKey; + this.CryptoJS = hmac_sha256_1.default; + this.encryptedKey = this.CryptoJS.SHA256(this.cipherKey); + } + Object.defineProperty(AesCbcCryptor.prototype, "algo", { + get: function () { + return 'AES-CBC'; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AesCbcCryptor.prototype, "identifier", { + get: function () { + return 'ACRH'; + }, + enumerable: false, + configurable: true + }); + AesCbcCryptor.prototype.getIv = function () { + return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); + }; + AesCbcCryptor.prototype.getKey = function () { + return __awaiter(this, void 0, void 0, function () { + var bKey, abHash; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + bKey = AesCbcCryptor.encoder.encode(this.cipherKey); + return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; + case 1: + abHash = _a.sent(); + return [2 /*return*/, crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt'])]; + } + }); + }); + }; + AesCbcCryptor.prototype.encrypt = function (data) { + var stringData = typeof data === 'string' ? data : AesCbcCryptor.decoder.decode(data); + if (stringData.length === 0) + throw new Error('encryption error. empty content'); + var abIv = this.getIv(); + return { + metadata: abIv, + data: (0, base64_codec_1.decode)(this.CryptoJS.AES.encrypt(data, this.encryptedKey, { + iv: this.bufferToWordArray(abIv), + mode: this.CryptoJS.mode.CBC, + }).ciphertext.toString(this.CryptoJS.enc.Base64)), + }; + }; + AesCbcCryptor.prototype.decrypt = function (encryptedData) { + var iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata)); + var data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); + return AesCbcCryptor.encoder.encode(this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { + iv: iv, + mode: this.CryptoJS.mode.CBC, + }).toString(this.CryptoJS.enc.Utf8)).buffer; + }; + AesCbcCryptor.prototype.encryptFileData = function (data) { + return __awaiter(this, void 0, void 0, function () { + var key, iv; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this.getKey()]; + case 1: + key = _b.sent(); + iv = this.getIv(); + _a = {}; + return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: iv }, key, data)]; + case 2: return [2 /*return*/, (_a.data = _b.sent(), + _a.metadata = iv, + _a)]; + } + }); + }); + }; + AesCbcCryptor.prototype.decryptFileData = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + var key; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.getKey()]; + case 1: + key = _a.sent(); + return [2 /*return*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)]; + } + }); + }); + }; + AesCbcCryptor.prototype.bufferToWordArray = function (b) { + var wa = []; + var i; + for (i = 0; i < b.length; i += 1) { + wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); + } + return this.CryptoJS.lib.WordArray.create(wa, b.length); + }; + AesCbcCryptor.BLOCK_SIZE = 16; + AesCbcCryptor.encoder = new TextEncoder(); + AesCbcCryptor.decoder = new TextDecoder(); + return AesCbcCryptor; +}()); +exports.default = AesCbcCryptor; diff --git a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js new file mode 100644 index 000000000..9b318e359 --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js @@ -0,0 +1,90 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var index_1 = __importDefault(require("../../../core/components/cryptography/index")); +var web_1 = __importDefault(require("../web")); +var base64_codec_1 = require("../../../core/components/base64_codec"); +var LegacyCryptor = /** @class */ (function () { + function LegacyCryptor(config) { + this.config = config; + this.cryptor = new index_1.default({ config: config }); + this.fileCryptor = new web_1.default(); + } + Object.defineProperty(LegacyCryptor.prototype, "identifier", { + get: function () { + return ''; + }, + enumerable: false, + configurable: true + }); + LegacyCryptor.prototype.encrypt = function (data) { + var stringData = typeof data === 'string' ? data : new TextDecoder().decode(data); + return { + data: this.cryptor.encrypt(stringData), + metadata: null, + }; + }; + LegacyCryptor.prototype.decrypt = function (encryptedData) { + var data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data); + return this.cryptor.decrypt(data); + }; + LegacyCryptor.prototype.encryptFile = function (file, File) { + var _a; + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_b) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: can not detect cipherKey from old Config + return [2 /*return*/, this.fileCryptor.encryptFile((_a = this.config) === null || _a === void 0 ? void 0 : _a.cipherKey, file, File)]; + }); + }); + }; + LegacyCryptor.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: can not detect cipherKey from old Config + return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)]; + }); + }); + }; + return LegacyCryptor; +}()); +exports.default = LegacyCryptor; diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js new file mode 100644 index 000000000..f4c7ccabf --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -0,0 +1,376 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; +var legacyCryptor_1 = __importDefault(require("./legacyCryptor")); +exports.LegacyCryptor = legacyCryptor_1.default; +var aesCbcCryptor_1 = __importDefault(require("./aesCbcCryptor")); +exports.AesCbcCryptor = aesCbcCryptor_1.default; +var base64_codec_1 = require("../../../core/components/base64_codec"); +var CryptoModule = /** @class */ (function () { + function CryptoModule(cryptoModuleConfiguration) { + var _a; + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: type detection issue with old Config type assignment + CryptoModule.legacyCryptoModule = function (config) { + var _a; + return new this({ + default: new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + var _a; + return new this({ + default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), + cryptors: [ + new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], + }); + }; + CryptoModule.withDefaultCryptor = function (defaultCryptor) { + return new this({ default: defaultCryptor }); + }; + CryptoModule.prototype.getAllCryptors = function () { + return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); + }; + CryptoModule.prototype.encrypt = function (data) { + var encrypted = this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) + return encrypted.data; + var headerData = this.getHeaderData(encrypted); + return this.concatArrayBuffer(headerData, encrypted.data); + }; + CryptoModule.prototype.decrypt = function (data) { + var encryptedData = typeof data === 'string' ? (0, base64_codec_1.decode)(data) : data; + var header = CryptorHeader.tryParse(encryptedData); + var cryptor = this.getCryptor(header); + var metadata = header.length > 0 + ? encryptedData.slice(header.length - header.metadataLength, header.length) + : null; + if (encryptedData.slice(header.length).byteLength <= 0) + throw new Error('decryption error. empty content'); + return cryptor.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + }; + CryptoModule.prototype.encryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var fileData, encrypted; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + return [4 /*yield*/, this.getFileData(file.data)]; + case 1: + fileData = _a.sent(); + return [4 /*yield*/, this.defaultCryptor.encryptFileData(fileData)]; + case 2: + encrypted = _a.sent(); + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: this.concatArrayBuffer(this.getHeaderData(encrypted), encrypted.data), + })]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var data, header, cryptor, fileData, metadata, _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: return [4 /*yield*/, file.data.arrayBuffer()]; + case 1: + data = _d.sent(); + header = CryptorHeader.tryParse(data); + cryptor = this.getCryptor(header); + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) { + return [2 /*return*/, cryptor.decryptFile(file, File)]; + } + return [4 /*yield*/, this.getFileData(data)]; + case 2: + fileData = _d.sent(); + metadata = fileData.slice(header.length - header.metadataLength, header.length); + _b = (_a = File).create; + _c = { + name: file.name + }; + return [4 /*yield*/, this.defaultCryptor.decryptFileData({ + data: data.slice(header.length), + metadata: metadata, + })]; + case 3: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + _c)])]; + } + }); + }); + }; + CryptoModule.prototype.getCryptor = function (header) { + if (header === '') { + var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); + if (cryptor) + return cryptor; + throw new Error('unknown cryptor error'); + } + else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + }; + CryptoModule.prototype.getCryptorFromId = function (id) { + var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; }); + if (cryptor) { + return cryptor; + } + throw Error('unknown cryptor error'); + }; + CryptoModule.prototype.concatArrayBuffer = function (ab1, ab2) { + var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); + tmp.set(new Uint8Array(ab1), 0); + tmp.set(new Uint8Array(ab2), ab1.byteLength); + return tmp.buffer; + }; + CryptoModule.prototype.getHeaderData = function (encrypted) { + if (!encrypted.metadata) + return; + var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + var headerData = new Uint8Array(header.length); + var pos = 0; + headerData.set(header.data, pos); + pos += header.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + return headerData.buffer; + }; + CryptoModule.prototype.getFileData = function (input) { + return __awaiter(this, void 0, void 0, function () { + var fileData; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(input instanceof Blob)) return [3 /*break*/, 2]; + return [4 /*yield*/, input.arrayBuffer()]; + case 1: + fileData = _a.sent(); + return [2 /*return*/, fileData]; + case 2: + if (input instanceof ArrayBuffer) { + return [2 /*return*/, input]; + } + if (typeof input === 'string') { + return [2 /*return*/, CryptoModule.encoder.encode(input)]; + } + throw new Error('Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob'); + } + }); + }); + }; + CryptoModule.LEGACY_IDENTIFIER = ''; + CryptoModule.encoder = new TextEncoder(); + CryptoModule.decoder = new TextDecoder(); + return CryptoModule; +}()); +exports.CryptoModule = CryptoModule; +// CryptorHeader Utility +var CryptorHeader = /** @class */ (function () { + function CryptorHeader() { + } + CryptorHeader.from = function (id, metadata) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) + return; + return new CryptorHeaderV1(id, metadata.byteLength); + }; + CryptorHeader.tryParse = function (data) { + var encryptedData = new Uint8Array(data); + var sentinel = ''; + var version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) + return ''; + } + if (encryptedData.byteLength >= 5) { + version = encryptedData[4]; + } + else { + throw new Error('decryption error. invalid header version'); + } + if (version > CryptorHeader.MAX_VERSION) + throw new Error('unknown cryptor error'); + var identifier = ''; + var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) { + identifier = encryptedData.slice(5, pos); + } + else { + throw new Error('decryption error. invalid crypto identifier'); + } + var metadataLength = null; + if (encryptedData.byteLength >= pos + 1) { + metadataLength = encryptedData[pos]; + } + else { + throw new Error('decryption error. invalid metadata length'); + } + pos += 1; + if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + pos += 2; + } + return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + CryptorHeader.decoder = new TextDecoder(); + return CryptorHeader; +}()); +// v1 CryptorHeader +var CryptorHeaderV1 = /** @class */ (function () { + function CryptorHeaderV1(id, metadataLength) { + this._identifier = id; + this._metadataLength = metadataLength; + } + Object.defineProperty(CryptorHeaderV1.prototype, "identifier", { + get: function () { + return this._identifier; + }, + set: function (value) { + this._identifier = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "metadataLength", { + get: function () { + return this._metadataLength; + }, + set: function (value) { + this._metadataLength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "version", { + get: function () { + return CryptorHeader.VERSION; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "length", { + get: function () { + return (CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "data", { + get: function () { + var pos = 0; + var header = new Uint8Array(this.length); + var encoder = new TextEncoder(); + header.set(encoder.encode(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(encoder.encode(this.identifier), pos); + pos += CryptorHeader.IDENTIFIER_LENGTH; + var metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; + } + else { + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + } + return header; + }, + enumerable: false, + configurable: true + }); + CryptorHeaderV1.IDENTIFIER_LENGTH = 4; + CryptorHeaderV1.SENTINEL = 'PNED'; + return CryptorHeaderV1; +}()); diff --git a/lib/crypto/modules/node.js b/lib/crypto/modules/node.js index 4250597d9..cb3968452 100644 --- a/lib/crypto/modules/node.js +++ b/lib/crypto/modules/node.js @@ -94,6 +94,8 @@ var NodeCryptography = /** @class */ (function () { case 0: bKey = this.getKey(key); if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; + if (file.data.byteLength <= 0) + throw new Error('encryption error. empty content'); _b = (_a = File).create; _e = { name: file.name, @@ -104,6 +106,8 @@ var NodeCryptography = /** @class */ (function () { _e)])]; case 2: if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 4]; + if (file.contentLength === 0) + throw new Error('encryption error. empty content'); _d = (_c = File).create; _f = { name: file.name, @@ -176,16 +180,32 @@ var NodeCryptography = /** @class */ (function () { NodeCryptography.prototype.decryptBuffer = function (key, ciphertext) { var bIv = ciphertext.slice(0, NodeCryptography.IV_LENGTH); var bCiphertext = ciphertext.slice(NodeCryptography.IV_LENGTH); + if (bCiphertext.byteLength <= 0) + throw new Error('decryption error: empty content'); var aes = (0, crypto_1.createDecipheriv)(this.algo, key, bIv); return Buffer.concat([aes.update(bCiphertext), aes.final()]); }; NodeCryptography.prototype.encryptStream = function (key, stream) { - var output = new stream_1.PassThrough(); - var bIv = this.getIv(); - var aes = (0, crypto_1.createCipheriv)(this.algo, key, bIv); - output.write(bIv); - stream.pipe(aes).pipe(output); - return output; + return __awaiter(this, void 0, void 0, function () { + var bIv, aes, inited; + return __generator(this, function (_a) { + bIv = this.getIv(); + aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, bIv).setAutoPadding(true); + inited = false; + return [2 /*return*/, stream.pipe(aes).pipe(new stream_1.Transform({ + transform: function (chunk, _, cb) { + if (!inited) { + inited = true; + this.push(Buffer.concat([bIv, chunk])); + } + else { + this.push(chunk); + } + cb(); + }, + }))]; + }); + }); }; NodeCryptography.prototype.decryptStream = function (key, stream) { var _this = this; diff --git a/lib/crypto/modules/web.js b/lib/crypto/modules/web.js index 77b4eb08a..b7bb887ea 100644 --- a/lib/crypto/modules/web.js +++ b/lib/crypto/modules/web.js @@ -96,10 +96,13 @@ var WebCryptography = /** @class */ (function () { var bKey, abPlaindata, abCipherdata; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.getKey(key)]; + case 0: + if (file.data.byteLength <= 0) + throw new Error('encryption error. empty content'); + return [4 /*yield*/, this.getKey(key)]; case 1: bKey = _a.sent(); - return [4 /*yield*/, file.toArrayBuffer()]; + return [4 /*yield*/, file.data.arrayBuffer()]; case 2: abPlaindata = _a.sent(); return [4 /*yield*/, this.encryptArrayBuffer(bKey, abPlaindata)]; @@ -122,7 +125,7 @@ var WebCryptography = /** @class */ (function () { case 0: return [4 /*yield*/, this.getKey(key)]; case 1: bKey = _a.sent(); - return [4 /*yield*/, file.toArrayBuffer()]; + return [4 /*yield*/, file.data.arrayBuffer()]; case 2: abCipherdata = _a.sent(); return [4 /*yield*/, this.decryptArrayBuffer(bKey, abCipherdata)]; @@ -138,15 +141,16 @@ var WebCryptography = /** @class */ (function () { }; WebCryptography.prototype.getKey = function (key) { return __awaiter(this, void 0, void 0, function () { - var bKey, abHash, abKey; + var digest, hashHex, abKey; return __generator(this, function (_a) { switch (_a.label) { - case 0: - bKey = Buffer.from(key); - return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; + case 0: return [4 /*yield*/, crypto.subtle.digest('SHA-256', WebCryptography.encoder.encode(key))]; case 1: - abHash = _a.sent(); - abKey = Buffer.from(Buffer.from(abHash).toString('hex').slice(0, 32), 'utf8').buffer; + digest = _a.sent(); + hashHex = Array.from(new Uint8Array(digest)) + .map(function (b) { return b.toString(16).padStart(2, '0'); }) + .join(''); + abKey = WebCryptography.encoder.encode(hashHex.slice(0, 32)).buffer; return [2 /*return*/, crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt'])]; } }); @@ -169,10 +173,18 @@ var WebCryptography = /** @class */ (function () { }; WebCryptography.prototype.decryptArrayBuffer = function (key, ciphertext) { return __awaiter(this, void 0, void 0, function () { - var abIv; + var abIv, data; return __generator(this, function (_a) { - abIv = ciphertext.slice(0, 16); - return [2 /*return*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16))]; + switch (_a.label) { + case 0: + abIv = ciphertext.slice(0, 16); + if (ciphertext.slice(WebCryptography.IV_LENGTH).byteLength <= 0) + throw new Error('decryption error: empty content'); + return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(WebCryptography.IV_LENGTH))]; + case 1: + data = _a.sent(); + return [2 /*return*/, data]; + } }); }); }; @@ -183,12 +195,12 @@ var WebCryptography = /** @class */ (function () { switch (_a.label) { case 0: abIv = crypto.getRandomValues(new Uint8Array(16)); - abPlaintext = Buffer.from(plaintext).buffer; + abPlaintext = WebCryptography.encoder.encode(plaintext).buffer; return [4 /*yield*/, crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext)]; case 1: abPayload = _a.sent(); ciphertext = concatArrayBuffer(abIv.buffer, abPayload); - return [2 /*return*/, Buffer.from(ciphertext).toString('utf8')]; + return [2 /*return*/, WebCryptography.decoder.decode(ciphertext)]; } }); }); @@ -199,18 +211,20 @@ var WebCryptography = /** @class */ (function () { return __generator(this, function (_a) { switch (_a.label) { case 0: - abCiphertext = Buffer.from(ciphertext); + abCiphertext = WebCryptography.encoder.encode(ciphertext).buffer; abIv = abCiphertext.slice(0, 16); abPayload = abCiphertext.slice(16); return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload)]; case 1: abPlaintext = _a.sent(); - return [2 /*return*/, Buffer.from(abPlaintext).toString('utf8')]; + return [2 /*return*/, WebCryptography.decoder.decode(abPlaintext)]; } }); }); }; WebCryptography.IV_LENGTH = 16; + WebCryptography.encoder = new TextEncoder(); + WebCryptography.decoder = new TextDecoder(); return WebCryptography; }()); exports.default = WebCryptography; diff --git a/lib/file/modules/node.js b/lib/file/modules/node.js index c3c4b0f6b..bb0988238 100644 --- a/lib/file/modules/node.js +++ b/lib/file/modules/node.js @@ -1,5 +1,4 @@ "use strict"; -/** */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -36,19 +35,23 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; var _a; Object.defineProperty(exports, "__esModule", { value: true }); var stream_1 = require("stream"); -var fs_1 = require("fs"); +var fs_1 = __importDefault(require("fs")); var path_1 = require("path"); var PubNubFile = (_a = /** @class */ (function () { function PubNubFile(_a) { var stream = _a.stream, data = _a.data, encoding = _a.encoding, name = _a.name, mimeType = _a.mimeType; if (stream instanceof stream_1.Readable) { this.data = stream; - if (stream instanceof fs_1.ReadStream) { + if (stream instanceof fs_1.default.ReadStream) { // $FlowFixMe: incomplete flow node definitions this.name = (0, path_1.basename)(stream.path); + this.contentLength = fs_1.default.statSync(stream.path).size; } } else if (data instanceof Buffer) { diff --git a/lib/networking/modules/node.js b/lib/networking/modules/node.js index fc190605c..08fecd318 100644 --- a/lib/networking/modules/node.js +++ b/lib/networking/modules/node.js @@ -5,11 +5,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.keepAlive = exports.proxy = void 0; var superagent_1 = __importDefault(require("superagent")); -var superagent_proxy_1 = __importDefault(require("superagent-proxy")); var agentkeepalive_1 = __importDefault(require("agentkeepalive")); +var proxyAgent_1 = __importDefault(require("../proxyAgent")); var keepAliveAgent = null; var keepAliveSecureAgent = null; -(0, superagent_proxy_1.default)(superagent_1.default); +(0, proxyAgent_1.default)(superagent_1.default); function proxy(superagentConstruct) { return superagentConstruct.proxy(this._config.proxy); } diff --git a/lib/networking/proxyAgent.js b/lib/networking/proxyAgent.js new file mode 100644 index 000000000..dd7feee08 --- /dev/null +++ b/lib/networking/proxyAgent.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var proxy_agent_1 = require("proxy-agent"); +function default_1(superagent) { + var Request = superagent.Request; + Request.prototype.proxy = proxy; + return superagent; +} +exports.default = default_1; +function proxy(proxyConfiguration) { + var agent = new proxy_agent_1.ProxyAgent(proxyConfiguration); + if (agent) + this.agent(agent); + return this; +} diff --git a/lib/node/index.js b/lib/node/index.js index c0a83be52..69ae47a7a 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -17,6 +17,7 @@ var __extends = (this && this.__extends) || (function () { var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; +var _a; var cbor_sync_1 = __importDefault(require("cbor-sync")); var pubnub_common_1 = __importDefault(require("../core/pubnub-common")); var networking_1 = __importDefault(require("../networking")); @@ -26,27 +27,41 @@ var web_node_1 = require("../networking/modules/web-node"); var node_1 = require("../networking/modules/node"); var node_2 = __importDefault(require("../crypto/modules/node")); var node_3 = __importDefault(require("../file/modules/node")); -module.exports = /** @class */ (function (_super) { - __extends(class_1, _super); - function class_1(setup) { - setup.cbor = new common_1.default(function (buffer) { return cbor_sync_1.default.decode(Buffer.from(buffer)); }, base64_codec_1.decode); - setup.networking = new networking_1.default({ - keepAlive: node_1.keepAlive, - del: web_node_1.del, - get: web_node_1.get, - post: web_node_1.post, - patch: web_node_1.patch, - proxy: node_1.proxy, - getfile: web_node_1.getfile, - postfile: web_node_1.postfile, - }); - setup.sdkFamily = 'Nodejs'; - setup.PubNubFile = node_3.default; - setup.cryptography = new node_2.default(); - if (!('ssl' in setup)) { - setup.ssl = true; +var nodeCryptoModule_1 = require("../crypto/modules/NodeCryptoModule/nodeCryptoModule"); +module.exports = (_a = /** @class */ (function (_super) { + __extends(class_1, _super); + function class_1(setup) { + var _this = this; + setup.cbor = new common_1.default(function (buffer) { return cbor_sync_1.default.decode(Buffer.from(buffer)); }, base64_codec_1.decode); + setup.networking = new networking_1.default({ + keepAlive: node_1.keepAlive, + del: web_node_1.del, + get: web_node_1.get, + post: web_node_1.post, + patch: web_node_1.patch, + proxy: node_1.proxy, + getfile: web_node_1.getfile, + postfile: web_node_1.postfile, + }); + setup.sdkFamily = 'Nodejs'; + setup.PubNubFile = node_3.default; + setup.cryptography = new node_2.default(); + setup.initCryptoModule = function (cryptoConfiguration) { + return new nodeCryptoModule_1.CryptoModule({ + default: new nodeCryptoModule_1.LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); + }; + if (!('ssl' in setup)) { + setup.ssl = true; + } + _this = _super.call(this, setup) || this; + return _this; } - return _super.call(this, setup) || this; - } - return class_1; -}(pubnub_common_1.default)); + return class_1; + }(pubnub_common_1.default)), + _a.CryptoModule = nodeCryptoModule_1.CryptoModule, + _a); diff --git a/lib/web/index.js b/lib/web/index.js index e704201ed..fcda537bb 100644 --- a/lib/web/index.js +++ b/lib/web/index.js @@ -29,6 +29,7 @@ var common_1 = __importDefault(require("../cbor/common")); var web_node_1 = require("../networking/modules/web-node"); var web_1 = __importDefault(require("../crypto/modules/web")); var web_2 = __importDefault(require("../file/modules/web")); +var webCryptoModule_1 = require("../crypto/modules/WebCryptoModule/webCryptoModule"); function sendBeacon(url) { if (navigator && navigator.sendBeacon) { navigator.sendBeacon(url); @@ -56,6 +57,15 @@ var default_1 = /** @class */ (function (_super) { setup.cbor = new common_1.default(function (arrayBuffer) { return (0, stringify_buffer_keys_1.stringifyBufferKeys)(cbor_js_1.default.decode(arrayBuffer)); }, base64_codec_1.decode); setup.PubNubFile = web_2.default; setup.cryptography = new web_1.default(); + setup.initCryptoModule = function (cryptoConfiguration) { + return new webCryptoModule_1.CryptoModule({ + default: new webCryptoModule_1.LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); + }; _this = _super.call(this, setup) || this; if (listenToBrowserNetworkEvents) { // mount network events. @@ -68,6 +78,7 @@ var default_1 = /** @class */ (function (_super) { } return _this; } + default_1.CryptoModule = webCryptoModule_1.CryptoModule; return default_1; }(pubnub_common_1.default)); exports.default = default_1; diff --git a/package.json b/package.json index 0a4487cc6..6560cc58a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "7.2.3", + "version": "7.4.5", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { @@ -56,8 +56,8 @@ "cbor-js": "^0.1.0", "cbor-sync": "^1.0.4", "lil-uuid": "^0.1.1", - "superagent": "^6.1.0", - "superagent-proxy": "^3.0.0" + "superagent": "^8.1.2", + "proxy-agent": "^6.3.0" }, "devDependencies": { "@cucumber/cucumber": "^7.3.1", @@ -110,8 +110,8 @@ "typescript": "^4.8.4", "underscore": "^1.9.2" }, - "license": "MIT", + "license": "SEE LICENSE IN LICENSE", "engine": { "node": ">=0.8" } -} +} \ No newline at end of file diff --git a/src/core/components/base64_codec.ts b/src/core/components/base64_codec.ts index 04cfea7f7..7908d5c75 100644 --- a/src/core/components/base64_codec.ts +++ b/src/core/components/base64_codec.ts @@ -53,3 +53,55 @@ export function decode(paddedInput: string): ArrayBuffer { return data; } + +export function encode(input: ArrayBuffer): string { + let base64 = ''; + const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + const bytes = new Uint8Array(input); + const byteLength = bytes.byteLength; + const byteRemainder = byteLength % 3; + const mainLength = byteLength - byteRemainder; + + let a, b, c, d; + let chunk; + + // Main loop deals with bytes in chunks of 3 + for (let i = 0; i < mainLength; i = i + 3) { + // Combine the three bytes into a single integer + chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + + // Use bitmasks to extract 6-bit segments from the triplet + a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 + b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 + c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 + d = chunk & 63; // 63 = 2^6 - 1 + + // Convert the raw binary segments to the appropriate ASCII encoding + base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; + } + + // Deal with the remaining bytes and padding + if (byteRemainder == 1) { + chunk = bytes[mainLength]; + + a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 + + // Set the 4 least significant bits to zero + b = (chunk & 3) << 4; // 3 = 2^2 - 1 + + base64 += encodings[a] + encodings[b] + '=='; + } else if (byteRemainder == 2) { + chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; + + a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 + b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 + + // Set the 2 least significant bits to zero + c = (chunk & 15) << 2; // 15 = 2^4 - 1 + + base64 += encodings[a] + encodings[b] + encodings[c] + '='; + } + + return base64; +} diff --git a/src/core/components/config.js b/src/core/components/config.js index 87417c8ec..5b2156019 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -132,7 +132,7 @@ export default class { maximumCacheSize; /* - support customp encryption and decryption functions. + support custom encryption and decryption functions. */ customEncrypt; // function to support custome encryption of messages @@ -146,6 +146,11 @@ export default class { enableEventEngine; maintainPresenceState; + /* + set cryptoModule to encrypt/decrypt messages and files. + */ + cryptoModule; + constructor({ setup }) { this._PNSDKSuffix = {}; @@ -157,7 +162,7 @@ export default class { this.sdkFamily = setup.sdkFamily; this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); - this.setCipherKey(setup.cipherKey); + this.cryptoModule = setup.cryptoModule; this.setFilterExpression(setup.filterExpression); @@ -235,6 +240,7 @@ export default class { this.setUUID(setup.uuid); } + this.setCipherKey(setup.cipherKey, setup); } // exposed setters @@ -247,8 +253,13 @@ export default class { return this; } - setCipherKey(val) { + setCipherKey(val, setup, modules) { this.cipherKey = val; + if (this.cipherKey) { + this.cryptoModule = + setup.cryptoModule ?? setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + if (modules) modules.cryptoModule = this.cryptoModule; + } return this; } @@ -347,7 +358,7 @@ export default class { } getVersion() { - return '7.2.3'; + return '7.4.5'; } setRetryConfiguration(configuration) { diff --git a/src/core/components/cryptography/index.js b/src/core/components/cryptography/index.js index 1e72663eb..8d6b400e3 100644 --- a/src/core/components/cryptography/index.js +++ b/src/core/components/cryptography/index.js @@ -26,7 +26,6 @@ export default class { constructor({ config }) { this._config = config; - this._iv = '0123456789012345'; this._allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; diff --git a/src/core/components/subscription_manager.js b/src/core/components/subscription_manager.js index 1e0e40165..3480eca7a 100644 --- a/src/core/components/subscription_manager.js +++ b/src/core/components/subscription_manager.js @@ -58,6 +58,10 @@ export default class { _pendingChannelGroupSubscriptions; // + _cryptoModule; + + _decoder; + _dedupingManager; constructor({ @@ -70,6 +74,7 @@ export default class { config, crypto, listenerManager, + cryptoModule, }) { this._listenerManager = listenerManager; this._config = config; @@ -81,6 +86,7 @@ export default class { this._getFileUrl = getFileUrl; this._crypto = crypto; + this._cryptoModule = cryptoModule; this._channels = {}; this._presenceChannels = {}; @@ -104,6 +110,8 @@ export default class { this._reconnectionManager = new ReconnectionManager({ timeEndpoint }); this._dedupingManager = new DedupingManager({ config }); + + if (this._cryptoModule) this._decoder = new TextDecoder(); } adaptStateChange(args, callback) { @@ -683,10 +691,17 @@ export default class { let msgPayload = message.payload; - if (this._config.cipherKey) { - const decryptedPayload = this._crypto.decrypt(message.payload); - - if (typeof decryptedPayload === 'object' && decryptedPayload !== null) { + if (this._cryptoModule) { + let decryptedPayload; + try { + const decryptedData = this._cryptoModule.decrypt(message.payload); + decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(this._decoder.decode(decryptedData)) : decryptedData; + } catch (e) { + decryptedPayload = null; + announce.error = `Error while decrypting message content: ${e.message}`; + } + if (decryptedPayload !== null) { msgPayload = decryptedPayload; } } @@ -727,8 +742,21 @@ export default class { announce.userMetadata = message.userMetadata; } - if (this._config.cipherKey) { - announce.message = this._crypto.decrypt(message.payload); + if (this._cryptoModule) { + let decryptedPayload; + try { + const decryptedData = this._cryptoModule.decrypt(message.payload); + decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(this._decoder.decode(decryptedData)) : decryptedData; + } catch (e) { + decryptedPayload = null; + announce.error = `Error while decrypting message content: ${e.message}`; + } + if (decryptedPayload != null) { + announce.message = decryptedPayload; + } else { + announce.message = message.payload; + } } else { announce.message = message.payload; } diff --git a/src/core/endpoints/fetch_messages.js b/src/core/endpoints/fetch_messages.js index 5ba4f1a29..2e4fca70e 100644 --- a/src/core/endpoints/fetch_messages.js +++ b/src/core/endpoints/fetch_messages.js @@ -11,14 +11,23 @@ import operationConstants from '../constants/operations'; import utils from '../utils'; function __processMessage(modules, message) { - const { config, crypto } = modules; - if (!config.cipherKey) return message; - + const result = {}; + if (!modules.cryptoModule) { + result.payload = message; + return result; + } try { - return crypto.decrypt(message); + const decryptedData = modules.cryptoModule.decrypt(message); + const decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + result.payload = decryptedPayload; + return result; } catch (e) { - return message; + if (modules.config.logVerbosity && console && console.log) console.log('decryption error', e.message); + result.payload = message; + result.error = `Error while decrypting message content: ${e.message}`; } + return result; } export function getOperation() { @@ -97,9 +106,10 @@ export function handleResponse(modules, serverResponse) { (serverResponse.channels[channelName] || []).forEach((messageEnvelope) => { const announce = {}; + const processedMessgeResult = __processMessage(modules, messageEnvelope.message); announce.channel = channelName; announce.timetoken = messageEnvelope.timetoken; - announce.message = __processMessage(modules, messageEnvelope.message); + announce.message = processedMessgeResult.payload; announce.messageType = messageEnvelope.message_type; announce.uuid = messageEnvelope.uuid; @@ -112,6 +122,7 @@ export function handleResponse(modules, serverResponse) { if (messageEnvelope.meta) { announce.meta = messageEnvelope.meta; } + if (processedMessgeResult.error) announce.error = processedMessgeResult.error; response.channels[channelName].push(announce); }); diff --git a/src/core/endpoints/file_upload/download_file.js b/src/core/endpoints/file_upload/download_file.js index 232c8bee2..3668f6336 100644 --- a/src/core/endpoints/file_upload/download_file.js +++ b/src/core/endpoints/file_upload/download_file.js @@ -1,3 +1,5 @@ +// Download_file.js + /** */ import operationConstants from '../../constants/operations'; @@ -34,11 +36,13 @@ const endpoint = { prepareParams: () => ({}), - handleResponse: async ({ PubNubFile, config, cryptography }, res, params) => { + handleResponse: async ({ PubNubFile, config, cryptography, cryptoModule }, res, params) => { let { body } = res.response; - - if (PubNubFile.supportsEncryptFile && (params.cipherKey ?? config.cipherKey)) { - body = await cryptography.decrypt(params.cipherKey ?? config.cipherKey, body); + if (PubNubFile.supportsEncryptFile && (params.cipherKey || cryptoModule)) { + body = + params.cipherKey == null + ? (await cryptoModule.decryptFile(PubNubFile.create({ data: body, name: params.name }), PubNubFile)).data + : await cryptography.decrypt(params.cipherKey ?? config.cipherKey, body); } return PubNubFile.create({ diff --git a/src/core/endpoints/file_upload/publish_file.js b/src/core/endpoints/file_upload/publish_file.js index 9f56f9ded..3a111935f 100644 --- a/src/core/endpoints/file_upload/publish_file.js +++ b/src/core/endpoints/file_upload/publish_file.js @@ -1,17 +1,16 @@ /** */ import operationConstants from '../../constants/operations'; - import utils from '../../utils'; +import { encode } from '../../components/base64_codec'; -const preparePayload = ({ crypto, config }, payload) => { +const preparePayload = (modules, payload) => { let stringifiedPayload = JSON.stringify(payload); - - if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + if (modules.cryptoModule) { + const encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } - return stringifiedPayload || ''; }; diff --git a/src/core/endpoints/file_upload/send_file.js b/src/core/endpoints/file_upload/send_file.js index 6e1a08f8e..f2d2fb810 100644 --- a/src/core/endpoints/file_upload/send_file.js +++ b/src/core/endpoints/file_upload/send_file.js @@ -1,22 +1,9 @@ import { PubNubError, createValidationError } from '../../components/endpoint'; -const getErrorFromResponse = (response) => - new Promise((resolve) => { - let result = ''; - - response.on('data', (data) => { - result += data.toString('utf8'); - }); - - response.on('end', () => { - resolve(result); - }); - }); - const sendFile = function ({ generateUploadUrl, publishFile, - modules: { PubNubFile, config, cryptography, networking }, + modules: { PubNubFile, config, cryptography, cryptoModule, networking }, }) { return async ({ channel, file: input, message, cipherKey, meta, ttl, storeInHistory }) => { if (!channel) { @@ -40,8 +27,11 @@ const sendFile = function ({ data: { id, name }, } = await generateUploadUrl({ channel, name: file.name }); - if (PubNubFile.supportsEncryptFile && (cipherKey ?? config.cipherKey)) { - file = await cryptography.encryptFile(cipherKey ?? config.cipherKey, file, PubNubFile); + if (PubNubFile.supportsEncryptFile && (cipherKey || cryptoModule)) { + file = + cipherKey == null + ? await cryptoModule.encryptFile(file, PubNubFile) + : await cryptography.encryptFile(cipherKey, file, PubNubFile); } let formFieldsWithMimeType = formFields; @@ -68,11 +58,9 @@ const sendFile = function ({ throw new Error('Unsupported environment'); } } catch (e) { - if (e.response) { - const errorBody = await getErrorFromResponse(e.response); - + if (e.response && typeof e.response.text === 'string') { + const errorBody = e.response.text; const reason = /(.*)<\/Message>/gi.exec(errorBody); - throw new PubNubError(reason ? `Upload to bucket failed: ${reason[1]}` : 'Upload to bucket failed.', e); } else { throw new PubNubError('Upload to bucket failed.', e); diff --git a/src/core/endpoints/history/get_history.js b/src/core/endpoints/history/get_history.js index afa3c952e..1b6ca15f6 100644 --- a/src/core/endpoints/history/get_history.js +++ b/src/core/endpoints/history/get_history.js @@ -5,14 +5,23 @@ import operationConstants from '../../constants/operations'; import utils from '../../utils'; function __processMessage(modules, message) { - const { config, crypto } = modules; - if (!config.cipherKey) return message; - + const result = {}; + if (!modules.cryptoModule) { + result.payload = message; + return result; + } try { - return crypto.decrypt(message); + const decryptedData = modules.cryptoModule.decrypt(message); + const decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + result.payload = decryptedPayload; + return result; } catch (e) { - return message; + if (modules.config.logVerbosity && console && console.log) console.log('decryption error', e.message); + result.payload = message; + result.error = `Error while decrypting message content: ${e.message}`; } + return result; } export function getOperation() { @@ -66,14 +75,16 @@ export function handleResponse(modules, serverResponse) { if (Array.isArray(serverResponse[0])) { serverResponse[0].forEach((serverHistoryItem) => { + const processedMessgeResult = __processMessage(modules, serverHistoryItem.message); const item = { timetoken: serverHistoryItem.timetoken, - entry: __processMessage(modules, serverHistoryItem.message), + entry: processedMessgeResult.payload, }; if (serverHistoryItem.meta) { item.meta = serverHistoryItem.meta; } + if (processedMessgeResult.error) item.error = processedMessgeResult.error; response.messages.push(item); }); diff --git a/src/core/endpoints/history/message_counts.js b/src/core/endpoints/history/message_counts.js index c12d7e0b3..6e00cfcc7 100644 --- a/src/core/endpoints/history/message_counts.js +++ b/src/core/endpoints/history/message_counts.js @@ -1,5 +1,3 @@ -/* */ - import operationConstants from '../../constants/operations'; import utils from '../../utils'; @@ -13,7 +11,7 @@ export function validateParams(modules, incomingParams) { if (!channels) return 'Missing channel'; if (timetoken && channelTimetokens) return 'timetoken and channelTimetokens are incompatible together'; - if (timetoken && channelTimetokens && channelTimetokens.length > 1 && channels.length !== channelTimetokens.length) { + if (channelTimetokens && channelTimetokens.length > 1 && channels.length !== channelTimetokens.length) { return 'Length of channelTimetokens and channels do not match'; } if (!config.subscribeKey) return 'Missing Subscribe Key'; diff --git a/src/core/endpoints/objects/member/get.js b/src/core/endpoints/objects/member/get.js index 0e1c3118c..5ce830599 100644 --- a/src/core/endpoints/objects/member/get.js +++ b/src/core/endpoints/objects/member/get.js @@ -9,7 +9,7 @@ const endpoint = { validateParams: (_, params) => { if (!params?.channel) { - return 'UUID cannot be empty'; + return 'channel cannot be empty'; } }, @@ -22,22 +22,33 @@ const endpoint = { prepareParams: (_modules, params) => { const queryParams = {}; - queryParams.include = ['uuid.status', 'uuid.type', 'type']; + queryParams.include = []; if (params?.include) { + if (params.include?.statusField) { + queryParams.include.push('status'); + } + if (params.include?.customFields) { queryParams.include.push('custom'); } + if (params.include?.UUIDFields) { + queryParams.include.push('uuid'); + } + if (params.include?.customUUIDFields) { queryParams.include.push('uuid.custom'); } - if (params.include?.UUIDFields ?? true) { - queryParams.include.push('uuid'); + if (params.include?.UUIDStatusField) { + queryParams.include.push('uuid.status'); } - } + if (params.include?.UUIDTypeField) { + queryParams.include.push('uuid.type'); + } + } queryParams.include = queryParams.include.join(','); if (params?.include?.totalCount) { diff --git a/src/core/endpoints/objects/membership/get.js b/src/core/endpoints/objects/membership/get.js index b83af0ea1..3f3dc94dd 100644 --- a/src/core/endpoints/objects/membership/get.js +++ b/src/core/endpoints/objects/membership/get.js @@ -18,22 +18,33 @@ const endpoint = { prepareParams: (_modules, params) => { const queryParams = {}; - queryParams.include = ['channel.status', 'channel.type', 'status']; + queryParams.include = []; if (params?.include) { + if (params.include?.statusField) { + queryParams.include.push('status'); + } + if (params.include?.customFields) { queryParams.include.push('custom'); } + if (params.include?.channelFields) { + queryParams.include.push('channel'); + } + if (params.include?.customChannelFields) { queryParams.include.push('channel.custom'); } - if (params.include?.channelFields) { - queryParams.include.push('channel'); + if (params.include?.channelStatusField) { + queryParams.include.push('channel.status'); } - } + if (params.include?.channelTypeField) { + queryParams.include.push('channel.type'); + } + } queryParams.include = queryParams.include.join(','); if (params?.include?.totalCount) { diff --git a/src/core/endpoints/publish.js b/src/core/endpoints/publish.js index 3bfc71d9f..2cb90f0e8 100644 --- a/src/core/endpoints/publish.js +++ b/src/core/endpoints/publish.js @@ -3,17 +3,17 @@ import { PublishResponse, PublishArguments, ModulesInject } from '../flow_interfaces'; import operationConstants from '../constants/operations'; import utils from '../utils'; +import { encode } from '../components/base64_codec'; function prepareMessagePayload(modules, messagePayload) { - const { crypto, config } = modules; let stringifiedPayload = JSON.stringify(messagePayload); - if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + if (modules.cryptoModule) { + const encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } - - return stringifiedPayload; + return stringifiedPayload || ''; } export function getOperation() { diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index 29349e596..5456f65f4 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -1,5 +1,6 @@ import Config from './components/config'; import Crypto from './components/cryptography/index'; +import { encode } from './components/base64_codec'; import SubscriptionManager from './components/subscription_manager'; import TelemetryManager from './components/telemetry_manager'; import NotificationsPayload from './components/push_payload'; @@ -256,6 +257,10 @@ export default class { getUUID; + setUserId; + + getUserId; + getFilterExpression; setFilterExpression; @@ -289,6 +294,7 @@ export default class { }); this._telemetryManager = telemetryManager; + const cryptoModule = this._config.cryptoModule; const modules = { config, @@ -298,12 +304,25 @@ export default class { tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, + cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; - this.encryptFile = (key, file) => cryptography.encryptFile(key, file, this.File); - this.decryptFile = (key, file) => cryptography.decryptFile(key, file, this.File); + this.encryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { + file = key; + return modules.cryptoModule.encryptFile(file, this.File); + } + return cryptography.encryptFile(key, file, this.File); + }; + this.decryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { + file = key; + return modules.cryptoModule.decryptFile(file, this.File); + } + return cryptography.decryptFile(key, file, this.File); + }; const timeEndpoint = endpointCreator.bind(this, modules, timeEndpointConfig); const leaveEndpoint = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig); @@ -386,6 +405,7 @@ export default class { config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), + cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); @@ -652,6 +672,9 @@ export default class { customFields: params.include.customFields, UUIDFields: params.include.userFields, customUUIDFields: params.include.customUserFields, + statusField: params.include.statusField, + UUIDStatusField: params.include.userStatusField, + UUIDTypeField: params.include.userTypeField, totalCount: params.include.totalCount, }, sort: @@ -681,6 +704,9 @@ export default class { customFields: params.include.customFields, channelFields: params.include.spaceFields, customChannelFields: params.include.customSpaceFields, + statusField: params.include.statusField, + channelStatusField: params.include.spaceStatusField, + channelTypeField: params.include.spaceTypeField, totalCount: params.include.totalCount, }, sort: @@ -709,18 +735,34 @@ export default class { // --- deprecated ------------------ // mount crypto - this.encrypt = crypto.encrypt.bind(crypto); - this.decrypt = crypto.decrypt.bind(crypto); + this.encrypt = function (data, key) { + if (typeof key === 'undefined' && modules.cryptoModule) { + const encrypted = modules.cryptoModule.encrypt(data); + return typeof encrypted === 'string' ? encrypted : encode(encrypted); + } else { + return crypto.encrypt(data, key); + } + }; + this.decrypt = function (data, key) { + if (typeof key === 'undefined' && cryptoModule) { + const decrypted = modules.cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decrypted)) : decrypted; + } else { + return crypto.decrypt(data, key); + } + }; /* config */ this.getAuthKey = modules.config.getAuthKey.bind(modules.config); this.setAuthKey = modules.config.setAuthKey.bind(modules.config); - this.setCipherKey = modules.config.setCipherKey.bind(modules.config); this.getUUID = modules.config.getUUID.bind(modules.config); this.setUUID = modules.config.setUUID.bind(modules.config); + this.getUserId = modules.config.getUserId.bind(modules.config); + this.setUserId = modules.config.setUserId.bind(modules.config); this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config); this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config); - + // this.setCipherKey = modules.config.setCipherKey.bind(modules.config); + this.setCipherKey = (key) => modules.config.setCipherKey(key, setup, modules); this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { diff --git a/src/core/utils.js b/src/core/utils.js index fd42d4388..5f88aeccc 100644 --- a/src/core/utils.js +++ b/src/core/utils.js @@ -32,9 +32,19 @@ function createPromise() { return { promise, reject: failureResolve, fulfill: successResolve }; } +function stringToArrayBuffer(str) { + var buf = new ArrayBuffer(str.length * 2); + var bufView = new Uint16Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; +} + module.exports = { signPamFromParams, endsWith, createPromise, encodeString, + stringToArrayBuffer, }; diff --git a/src/crypto/modules/NodeCryptoModule/ICryptor.ts b/src/crypto/modules/NodeCryptoModule/ICryptor.ts new file mode 100644 index 000000000..5e73cee31 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/ICryptor.ts @@ -0,0 +1,19 @@ +export type EncryptedDataType = { + data: Buffer | string; + metadata: Buffer | null; +}; + +export type EncryptedStream = { + stream: NodeJS.ReadableStream; + metadataLength: number; + metadata?: Buffer | undefined; +}; + +export interface ICryptor { + get identifier(): string; + encrypt(data: BufferSource | string): EncryptedDataType; + decrypt(data: EncryptedDataType): ArrayBuffer; + + encryptStream(stream: NodeJS.ReadableStream): Promise; + decryptStream(encryptedStream: EncryptedStream): Promise; +} diff --git a/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts new file mode 100644 index 000000000..9a63aa455 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts @@ -0,0 +1,26 @@ +import { EncryptedDataType } from './ICryptor'; + +export type PubNubFileType = { + stream: NodeJS.ReadStream; + data: NodeJS.ReadStream | Buffer; + name: string; + mimeType: string; + contentLength: number; + + create(config: any): PubNubFileType; + + toBuffer(): Buffer; + toArrayBuffer(): ArrayBuffer; + toString(): string; + toStream(): NodeJS.ReadStream; +}; + +export interface ILegacyCryptor { + get identifier(): string; + + encrypt(data: string | ArrayBuffer): EncryptedDataType; + decrypt(data: EncryptedDataType): BufferSource | string; + + encryptFile(file: T, File: T): Promise; + decryptFile(file: T, File: T): Promise; +} diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts new file mode 100644 index 000000000..68cfb89a6 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts @@ -0,0 +1,97 @@ +import { PassThrough } from 'stream'; +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; +import { ICryptor, EncryptedDataType, EncryptedStream } from './ICryptor'; + +export default class AesCbcCryptor implements ICryptor { + static BLOCK_SIZE = 16; + + cipherKey: string; + constructor(configuration: { cipherKey: string }) { + this.cipherKey = configuration.cipherKey; + } + + get algo() { + return 'aes-256-cbc'; + } + + get identifier() { + return 'ACRH'; + } + + getIv() { + return randomBytes(AesCbcCryptor.BLOCK_SIZE); + } + + getKey() { + const sha = createHash('sha256'); + sha.update(Buffer.from(this.cipherKey, 'utf8')); + return Buffer.from(sha.digest()); + } + + encrypt(data: ArrayBuffer | string) { + const iv = this.getIv(); + const key = this.getKey(); + const plainData = typeof data === 'string' ? new TextEncoder().encode(data) : data; + const bPlain = Buffer.from(plainData); + if (bPlain.byteLength === 0) throw new Error('encryption error. empty content'); + const aes = createCipheriv(this.algo, key, iv); + + return { + metadata: iv, + data: Buffer.concat([aes.update(bPlain), aes.final()]), + }; + } + + decrypt(encryptedData: EncryptedDataType) { + const data = + typeof encryptedData.data === 'string' ? new TextEncoder().encode(encryptedData.data) : encryptedData.data; + if (data.byteLength <= 0) throw new Error('decryption error: empty content'); + const aes = createDecipheriv(this.algo, this.getKey(), encryptedData.metadata); + return Uint8Array.from(Buffer.concat([aes.update(data), aes.final()])).buffer; + } + + async encryptStream(stream: NodeJS.ReadableStream) { + const output = new PassThrough(); + const bIv = this.getIv(); + if (stream.readable === false) throw new Error('encryption error. empty stream'); + const aes = createCipheriv(this.algo, this.getKey(), bIv); + stream.pipe(aes).pipe(output); + return { + stream: output, + metadata: bIv, + metadataLength: AesCbcCryptor.BLOCK_SIZE, + }; + } + + async decryptStream(encryptedStream: EncryptedStream) { + const decryptedStream = new PassThrough(); + let bIv = Buffer.alloc(0); + let aes: any = null; + const onReadable = () => { + let data = encryptedStream.stream.read(); + while (data !== null) { + if (data) { + const bChunk = Buffer.from(data); + const sliceLen = encryptedStream.metadataLength - bIv.byteLength; + if (bChunk.byteLength < sliceLen) { + bIv = Buffer.concat([bIv, bChunk]); + } else { + bIv = Buffer.concat([bIv, bChunk.slice(0, sliceLen)]); + aes = createDecipheriv(this.algo, this.getKey(), bIv); + aes.pipe(decryptedStream); + aes.write(bChunk.slice(sliceLen)); + } + } + data = encryptedStream.stream.read(); + } + }; + encryptedStream.stream.on('readable', onReadable); + encryptedStream.stream.on('end', () => { + if (aes) { + aes.end(); + } + decryptedStream.end(); + }); + return decryptedStream; + } +} diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts new file mode 100644 index 000000000..c8a28fc6b --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -0,0 +1,41 @@ +import Crypto from '../../../core/components/cryptography/index'; +import { encode } from '../../../core/components/base64_codec'; +import FileCryptor from '../node'; +import { EncryptedDataType } from './ICryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; + +export default class LegacyCryptor implements ILegacyCryptor { + config; + + cryptor; + fileCryptor; + + constructor(config: any) { + this.config = config; + this.cryptor = new Crypto({ config }); + this.fileCryptor = new FileCryptor(); + } + get identifier() { + return ''; + } + encrypt(data: string) { + if (data.length === 0) throw new Error('encryption error. empty content'); + return { + data: this.cryptor.encrypt(data), + metadata: null, + }; + } + + decrypt(encryptedData: EncryptedDataType) { + const data = typeof encryptedData.data === 'string' ? encryptedData.data : encode(encryptedData.data); + return this.cryptor.decrypt(data); + } + + async encryptFile(file: PubNubFileType, File: PubNubFileType) { + return this.fileCryptor.encryptFile(this.config.cipherKey, file, File); + } + + async decryptFile(file: PubNubFileType, File: PubNubFileType) { + return this.fileCryptor.decryptFile(this.config.cipherKey, file, File); + } +} diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts new file mode 100644 index 000000000..a1d218946 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -0,0 +1,350 @@ +import { Readable, PassThrough } from 'stream'; +import { decode } from '../../../core/components/base64_codec'; +import LegacyCryptor from './legacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; +import { ICryptor } from './ICryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; + +export { LegacyCryptor, AesCbcCryptor }; + +type CryptorType = ICryptor | ILegacyCryptor; + +type CryptoModuleConfiguration = { + default: CryptorType; + cryptors?: Array; +}; + +export class CryptoModule { + static LEGACY_IDENTIFIER = ''; + + defaultCryptor: CryptorType; + cryptors: Array; + + constructor(cryptoModuleConfiguration: CryptoModuleConfiguration) { + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = cryptoModuleConfiguration.cryptors ?? []; + } + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: type detection issue with old Config type assignment + static legacyCryptoModule(config) { + return new this({ + default: new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), + cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], + }); + } + + static aesCbcCryptoModule(config: any) { + return new this({ + default: new AesCbcCryptor({ cipherKey: config.cipherKey }), + cryptors: [ + new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), + ], + }); + } + static withDefaultCryptor(defaultCryptor: CryptorType) { + return new this({ default: defaultCryptor }); + } + + private getAllCryptors() { + return [this.defaultCryptor, ...this.cryptors]; + } + + private getLegacyCryptor() { + return this.getAllCryptors().find((c) => c.identifier === ''); + } + + encrypt(data: ArrayBuffer | string) { + const encrypted = this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) return encrypted.data; + + const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + + const headerData = new Uint8Array(header!.length); + let pos = 0; + headerData.set(header!.data, pos); + pos = header!.length - encrypted.metadata.length; + headerData.set(encrypted.metadata, pos); + return Buffer.concat([headerData, Buffer.from(encrypted.data)]); + } + + decrypt(data: ArrayBuffer | string) { + const encryptedData = Buffer.from(typeof data === 'string' ? decode(data) : data); + const header = CryptorHeader.tryParse(encryptedData); + const cryptor = this.getCryptor(header); + const metadata = + header.length > 0 + ? encryptedData.slice(header.length - (header as CryptorHeaderV1).metadataLength, header.length) + : null; + if (encryptedData.slice(header.length).byteLength <= 0) throw new Error('decryption error. empty content'); + return cryptor!.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + } + + async encryptFile(file: PubNubFileType, File: PubNubFileType) { + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on intsance type) + */ + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return (this.defaultCryptor as ILegacyCryptor).encryptFile(file, File); + if (file.data instanceof Buffer) { + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: Buffer.from(this.encrypt(file.data!) as Buffer), + }); + } + if (file.data instanceof Readable) { + if (file.contentLength === 0) throw new Error('encryption error. empty content'); + const encryptedStream = await (this.defaultCryptor as ICryptor).encryptStream(file.data); + const header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata!); + const payload = new Uint8Array(header!.length); + let pos = 0; + payload.set(header!.data, pos); + pos += header!.length; + if (encryptedStream.metadata) { + pos -= encryptedStream.metadata.length; + payload.set(encryptedStream.metadata, pos); + } + const output = new PassThrough(); + output.write(payload); + encryptedStream.stream.pipe(output); + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: output, + }); + } + } + + async decryptFile(file: PubNubFileType, File: PubNubFileType) { + if (file?.data instanceof Buffer) { + const header = CryptorHeader.tryParse(file.data); + const cryptor = this.getCryptor(header); + /** + * If It's legacyone then redirect it. + * (as long as we support legacy need to check on instance type) + */ + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) + return (cryptor as ILegacyCryptor).decryptFile(file, File); + return File.create({ + name: file.name, + data: Buffer.from(this.decrypt(file?.data) as ArrayBuffer), + }); + } + + if (file.data instanceof Readable) { + const stream = file.data; + return new Promise((resolve) => { + stream.on('readable', () => resolve(this.onStreamReadable(stream, file, File))); + }); + } + } + + private async onStreamReadable(stream: NodeJS.ReadableStream, file: PubNubFileType, File: PubNubFileType) { + stream.removeAllListeners('readable'); + const magicBytes = stream.read(4); + if (!CryptorHeader.isSentinel(magicBytes as Buffer)) { + if (magicBytes === null) throw new Error('decryption error. empty content'); + stream.unshift(magicBytes); + return this.decryptLegacyFileStream(stream, file, File); + } + const versionByte = stream.read(1); + CryptorHeader.validateVersion(versionByte[0] as number); + const identifier = stream.read(4); + const cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier as Buffer)); + const headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream); + if (file.contentLength <= CryptorHeader.MIN_HEADER_LEGTH + headerSize) + throw new Error('decryption error. empty content'); + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: await (cryptor as ICryptor).decryptStream({ stream: stream, metadataLength: headerSize as number }), + }); + } + + private async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubNubFileType, File: PubNubFileType) { + if (file.contentLength <= 16) throw new Error('decryption error: empty content'); + const cryptor = this.getLegacyCryptor(); + if (cryptor) { + return (cryptor as ILegacyCryptor).decryptFile( + File.create({ + name: file.name, + stream: stream, + }), + File, + ); + } else { + throw new Error('unknown cryptor error'); + } + } + + private getCryptor(header: CryptorHeader) { + if (header === '') { + const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); + if (cryptor) return cryptor; + throw new Error('unknown cryptor error'); + } else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + } + + private getCryptorFromId(id: string) { + const cryptor = this.getAllCryptors().find((c) => id === c.identifier); + if (cryptor) { + return cryptor; + } + throw new Error('unknown cryptor error'); + } +} + +// CryptorHeader Utility +class CryptorHeader { + static SENTINEL = 'PNED'; + static LEGACY_IDENTIFIER = ''; + static IDENTIFIER_LENGTH = 4; + static VERSION = 1; + static MAX_VERSION = 1; + static MIN_HEADER_LEGTH = 10; + + static from(id: string, metadata: Buffer) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) return; + return new CryptorHeaderV1(id, metadata.length); + } + + static isSentinel(bytes: Buffer) { + if (bytes && bytes.byteLength >= 4) { + if (bytes.toString('utf8') == CryptorHeader.SENTINEL) return true; + } + } + + static validateVersion(data: number) { + if (data && data > CryptorHeader.MAX_VERSION) throw new Error('decryption error. invalid header version'); + return data; + } + + static tryGetIdentifier(data: Buffer) { + if (data.byteLength < 4) { + throw new Error('unknown cryptor error. decryption failed'); + } else { + return data.toString('utf8'); + } + } + + static tryGetMetadataSizeFromStream(stream: NodeJS.ReadableStream) { + const sizeBuf = stream.read(1); + if (sizeBuf && (sizeBuf[0] as number) < 255) { + return sizeBuf[0] as number; + } + if ((sizeBuf[0] as number) === 255) { + const nextBuf = stream.read(2); + if (nextBuf.length >= 2) { + return new Uint16Array([nextBuf[0] as number, nextBuf[1] as number]).reduce((acc, val) => (acc << 8) + val, 0); + } + } + throw new Error('decryption error. Invalid metadata size'); + } + static tryParse(encryptedData: Buffer) { + let sentinel: any = ''; + let version = null; + if (encryptedData.length >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) return ''; + } + + if (encryptedData.length >= 5) { + version = encryptedData[4]; + } else { + throw new Error('decryption error. invalid header version'); + } + if (version > CryptorHeader.MAX_VERSION) throw new Error('unknown cryptor error'); + + let identifier: Buffer; + let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.length >= pos) { + identifier = encryptedData.slice(5, pos); + } else { + throw new Error('decryption error. invalid crypto identifier'); + } + let metadataLength = null; + if (encryptedData.length >= pos + 1) { + metadataLength = encryptedData[pos]; + } else { + throw new Error('decryption error. invalid metadata length'); + } + pos += 1; + if (metadataLength === 255 && encryptedData.length >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); + } +} + +// v1 CryptorHeader +class CryptorHeaderV1 { + _identifier; + _metadataLength; + + constructor(id: string, metadataLength: number) { + this._identifier = id; + this._metadataLength = metadataLength; + } + + get identifier() { + return this._identifier; + } + + set identifier(value) { + this._identifier = value; + } + + get metadataLength() { + return this._metadataLength; + } + + set metadataLength(value) { + this._metadataLength = value; + } + + get version() { + return CryptorHeader.VERSION; + } + + get length() { + return ( + CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength + ); + } + + get data() { + let pos = 0; + const header = new Uint8Array(this.length); + header.set(Buffer.from(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) header.set(Buffer.from(this.identifier), pos); + pos += CryptorHeader.IDENTIFIER_LENGTH; + const metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; + } else { + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + } + return header; + } +} diff --git a/src/crypto/modules/WebCryptoModule/ICryptor.ts b/src/crypto/modules/WebCryptoModule/ICryptor.ts new file mode 100644 index 000000000..b15709c75 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/ICryptor.ts @@ -0,0 +1,13 @@ +export type EncryptedDataType = { + data: ArrayBuffer; + metadata: ArrayBuffer | null; +}; + +export interface ICryptor { + get identifier(): string; + encrypt(data: ArrayBuffer | string): EncryptedDataType; + decrypt(data: EncryptedDataType): ArrayBuffer; + + encryptFileData(data: ArrayBuffer): Promise; + decryptFileData(data: EncryptedDataType): Promise; +} diff --git a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts new file mode 100644 index 000000000..c9ae022c0 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts @@ -0,0 +1,24 @@ +import { EncryptedDataType } from './ICryptor'; + +export type PubNubFileType = { + data: File | Blob; + name: string; + mimeType: string; + + create(config: any): PubNubFileType; + + toArrayBuffer(): ArrayBuffer; + toBlob(): Blob; + toString(): string; + toFile(): File; +}; + +export interface ILegacyCryptor { + get identifier(): string; + + encrypt(data: ArrayBuffer | string): EncryptedDataType; + decrypt(data: EncryptedDataType): ArrayBuffer | string; + + encryptFile(file: T, File: T): Promise; + decryptFile(file: T, File: T): Promise; +} diff --git a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts new file mode 100644 index 000000000..78bda2175 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -0,0 +1,86 @@ +import { ICryptor, EncryptedDataType } from './ICryptor'; +import cryptoJS from '../../../core/components/cryptography/hmac-sha256'; +import { decode } from '../../../core/components/base64_codec'; + +export default class AesCbcCryptor implements ICryptor { + static BLOCK_SIZE = 16; + static encoder = new TextEncoder(); + static decoder = new TextDecoder(); + + cipherKey: string; + encryptedKey: any; + CryptoJS: any; + + constructor(configuration: { cipherKey: string }) { + this.cipherKey = configuration.cipherKey; + this.CryptoJS = cryptoJS; + this.encryptedKey = this.CryptoJS.SHA256(this.cipherKey); + } + + get algo() { + return 'AES-CBC'; + } + + get identifier() { + return 'ACRH'; + } + + private getIv() { + return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); + } + + private async getKey() { + const bKey = AesCbcCryptor.encoder.encode(this.cipherKey); + const abHash = await crypto.subtle.digest('SHA-256', bKey.buffer); + return crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt']); + } + + encrypt(data: ArrayBuffer | string) { + const stringData = typeof data === 'string' ? data : AesCbcCryptor.decoder.decode(data); + if (stringData.length === 0) throw new Error('encryption error. empty content'); + const abIv = this.getIv(); + return { + metadata: abIv, + data: decode( + this.CryptoJS.AES.encrypt(data, this.encryptedKey, { + iv: this.bufferToWordArray(abIv), + mode: this.CryptoJS.mode.CBC, + }).ciphertext.toString(this.CryptoJS.enc.Base64), + ), + }; + } + + decrypt(encryptedData: EncryptedDataType) { + const iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata!)); + const data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); + return AesCbcCryptor.encoder.encode( + this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { + iv, + mode: this.CryptoJS.mode.CBC, + }).toString(this.CryptoJS.enc.Utf8), + ).buffer; + } + + async encryptFileData(data: ArrayBuffer): Promise { + const key = await this.getKey(); + const iv = this.getIv(); + return { + data: await crypto.subtle.encrypt({ name: this.algo, iv: iv }, key, data), + metadata: iv, + }; + } + + async decryptFileData(encryptedData: EncryptedDataType): Promise { + const key = await this.getKey(); + return crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata! }, key, encryptedData.data); + } + + private bufferToWordArray(b: any) { + const wa: any[] = []; + let i; + for (i = 0; i < b.length; i += 1) { + wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); + } + return this.CryptoJS.lib.WordArray.create(wa, b.length); + } +} diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts new file mode 100644 index 000000000..db4b96bed --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -0,0 +1,46 @@ +import Crypto from '../../../core/components/cryptography/index'; +import FileCryptor from '../web'; +import { EncryptedDataType } from './ICryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; +import { encode } from '../../../core/components/base64_codec'; + +export default class LegacyCryptor implements ILegacyCryptor { + config; + + cryptor; + fileCryptor; + + constructor(config: any) { + this.config = config; + this.cryptor = new Crypto({ config }); + this.fileCryptor = new FileCryptor(); + } + + get identifier() { + return ''; + } + encrypt(data: ArrayBuffer | string) { + const stringData = typeof data === 'string' ? data : new TextDecoder().decode(data); + return { + data: this.cryptor.encrypt(stringData), + metadata: null, + }; + } + + decrypt(encryptedData: EncryptedDataType) { + const data = typeof encryptedData.data === 'string' ? encryptedData.data : encode(encryptedData.data); + return this.cryptor.decrypt(data); + } + + async encryptFile(file: PubNubFileType, File: PubNubFileType) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: can not detect cipherKey from old Config + return this.fileCryptor.encryptFile(this.config?.cipherKey, file, File); + } + + async decryptFile(file: PubNubFileType, File: PubNubFileType) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: can not detect cipherKey from old Config + return this.fileCryptor.decryptFile(this.config.cipherKey, file, File); + } +} diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts new file mode 100644 index 000000000..5b5217dad --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -0,0 +1,279 @@ +import LegacyCryptor from './legacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; +import { EncryptedDataType, ICryptor } from './ICryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; +import { decode } from '../../../core/components/base64_codec'; + +export { LegacyCryptor, AesCbcCryptor }; + +type CryptorType = ICryptor | ILegacyCryptor; + +type CryptoModuleConfiguration = { + default: CryptorType; + cryptors?: Array; +}; + +export class CryptoModule { + static LEGACY_IDENTIFIER = ''; + static encoder = new TextEncoder(); + static decoder = new TextDecoder(); + defaultCryptor: CryptorType; + cryptors: Array; + + constructor(cryptoModuleConfiguration: CryptoModuleConfiguration) { + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = cryptoModuleConfiguration.cryptors ?? []; + } + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + //@ts-ignore: type detection issue with old Config type assignment + static legacyCryptoModule(config) { + return new this({ + default: new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), + cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], + }); + } + + static aesCbcCryptoModule(config: any) { + return new this({ + default: new AesCbcCryptor({ cipherKey: config.cipherKey }), + cryptors: [ + new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), + ], + }); + } + + static withDefaultCryptor(defaultCryptor: CryptorType) { + return new this({ default: defaultCryptor }); + } + + private getAllCryptors() { + return [this.defaultCryptor, ...this.cryptors]; + } + + encrypt(data: ArrayBuffer | string) { + const encrypted = (this.defaultCryptor as ICryptor).encrypt(data); + if (!encrypted.metadata) return encrypted.data; + const headerData = this.getHeaderData(encrypted); + return this.concatArrayBuffer(headerData!, encrypted.data); + } + + decrypt(data: ArrayBuffer | string) { + const encryptedData = typeof data === 'string' ? decode(data) : data; + const header = CryptorHeader.tryParse(encryptedData); + const cryptor = this.getCryptor(header); + const metadata = + header.length > 0 + ? encryptedData.slice(header.length - (header as CryptorHeaderV1).metadataLength, header.length) + : null; + if (encryptedData.slice(header.length).byteLength <= 0) throw new Error('decryption error. empty content'); + return cryptor!.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + } + + async encryptFile(file: PubNubFileType, File: PubNubFileType) { + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return (this.defaultCryptor as ILegacyCryptor).encryptFile(file, File); + const fileData = await this.getFileData(file.data); + const encrypted = await (this.defaultCryptor as ICryptor).encryptFileData(fileData); + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: this.concatArrayBuffer(this.getHeaderData(encrypted)!, encrypted.data), + }); + } + + async decryptFile(file: PubNubFileType, File: PubNubFileType) { + const data = await file.data.arrayBuffer(); + const header = CryptorHeader.tryParse(data); + const cryptor = this.getCryptor(header); + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) { + return (cryptor as ILegacyCryptor).decryptFile(file, File); + } + const fileData = await this.getFileData(data); + const metadata = fileData.slice(header.length - (header as CryptorHeaderV1).metadataLength, header.length); + return File.create({ + name: file.name, + data: await (this.defaultCryptor as ICryptor).decryptFileData({ + data: data.slice(header.length), + metadata: metadata, + }), + }); + } + + private getCryptor(header: string | CryptorHeaderV1) { + if (header === '') { + const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); + if (cryptor) return cryptor; + throw new Error('unknown cryptor error'); + } else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + } + + private getCryptorFromId(id: string) { + const cryptor = this.getAllCryptors().find((c) => id === c.identifier); + if (cryptor) { + return cryptor; + } + throw Error('unknown cryptor error'); + } + + private concatArrayBuffer(ab1: ArrayBuffer, ab2: ArrayBuffer) { + const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); + + tmp.set(new Uint8Array(ab1), 0); + tmp.set(new Uint8Array(ab2), ab1.byteLength); + + return tmp.buffer; + } + + private getHeaderData(encrypted: EncryptedDataType) { + if (!encrypted.metadata) return; + const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + const headerData = new Uint8Array(header!.length); + let pos = 0; + headerData.set(header!.data, pos); + pos += header!.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + return headerData.buffer; + } + + private async getFileData(input: any) { + if (input instanceof Blob) { + const fileData = await input.arrayBuffer(); + return fileData; + } + if (input instanceof ArrayBuffer) { + return input; + } + if (typeof input === 'string') { + return CryptoModule.encoder.encode(input); + } + throw new Error( + 'Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob', + ); + } +} + +// CryptorHeader Utility +class CryptorHeader { + static SENTINEL = 'PNED'; + static LEGACY_IDENTIFIER = ''; + static IDENTIFIER_LENGTH = 4; + static VERSION = 1; + static MAX_VERSION = 1; + static decoder = new TextDecoder(); + + static from(id: string, metadata: ArrayBuffer) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) return; + return new CryptorHeaderV1(id, metadata.byteLength); + } + + static tryParse(data: ArrayBuffer) { + const encryptedData = new Uint8Array(data); + let sentinel: any = ''; + let version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) return ''; + } + if (encryptedData.byteLength >= 5) { + version = (encryptedData as Uint8Array)[4] as number; + } else { + throw new Error('decryption error. invalid header version'); + } + if (version > CryptorHeader.MAX_VERSION) throw new Error('unknown cryptor error'); + + let identifier: any = ''; + let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) { + identifier = encryptedData.slice(5, pos); + } else { + throw new Error('decryption error. invalid crypto identifier'); + } + let metadataLength = null; + if (encryptedData.byteLength >= pos + 1) { + metadataLength = (encryptedData as Uint8Array)[pos]; + } else { + throw new Error('decryption error. invalid metadata length'); + } + pos += 1; + if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); + pos += 2; + } + return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + } +} + +// v1 CryptorHeader +class CryptorHeaderV1 { + static IDENTIFIER_LENGTH = 4; + static SENTINEL = 'PNED'; + + _identifier; + _metadataLength; + + constructor(id: string, metadataLength: number) { + this._identifier = id; + this._metadataLength = metadataLength; + } + + get identifier() { + return this._identifier; + } + + set identifier(value) { + this._identifier = value; + } + + get metadataLength() { + return this._metadataLength; + } + + set metadataLength(value) { + this._metadataLength = value; + } + + get version() { + return CryptorHeader.VERSION; + } + + get length() { + return ( + CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength + ); + } + + get data() { + let pos = 0; + const header = new Uint8Array(this.length); + const encoder = new TextEncoder(); + header.set(encoder.encode(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) header.set(encoder.encode(this.identifier), pos); + pos += CryptorHeader.IDENTIFIER_LENGTH; + const metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; + } else { + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + } + return header; + } +} diff --git a/src/crypto/modules/node.js b/src/crypto/modules/node.js index 27e9f4f0e..11055962c 100644 --- a/src/crypto/modules/node.js +++ b/src/crypto/modules/node.js @@ -1,5 +1,5 @@ /** */ -import { Readable, PassThrough } from 'stream'; +import { Readable, PassThrough, Transform } from 'stream'; import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; export default class NodeCryptography { @@ -41,6 +41,7 @@ export default class NodeCryptography { const bKey = this.getKey(key); if (file.data instanceof Buffer) { + if (file.data.byteLength <= 0) throw new Error('encryption error. empty content'); return File.create({ name: file.name, mimeType: 'application/octet-stream', @@ -48,6 +49,7 @@ export default class NodeCryptography { }); } if (file.data instanceof Readable) { + if (file.contentLength === 0) throw new Error('encryption error. empty content'); return File.create({ name: file.name, mimeType: 'application/octet-stream', @@ -118,22 +120,29 @@ export default class NodeCryptography { decryptBuffer(key, ciphertext) { const bIv = ciphertext.slice(0, NodeCryptography.IV_LENGTH); const bCiphertext = ciphertext.slice(NodeCryptography.IV_LENGTH); - + if (bCiphertext.byteLength <= 0) throw new Error('decryption error: empty content'); const aes = createDecipheriv(this.algo, key, bIv); return Buffer.concat([aes.update(bCiphertext), aes.final()]); } - encryptStream(key, stream) { - const output = new PassThrough(); + async encryptStream(key, stream) { const bIv = this.getIv(); - - const aes = createCipheriv(this.algo, key, bIv); - - output.write(bIv); - stream.pipe(aes).pipe(output); - - return output; + const aes = createCipheriv('aes-256-cbc', key, bIv).setAutoPadding(true); + let inited = false; + return stream.pipe(aes).pipe( + new Transform({ + transform(chunk, _, cb) { + if (!inited) { + inited = true; + this.push(Buffer.concat([bIv, chunk])); + } else { + this.push(chunk); + } + cb(); + }, + }), + ); } decryptStream(key, stream) { diff --git a/src/crypto/modules/web.js b/src/crypto/modules/web.js index 6940db0b7..20e1a274b 100644 --- a/src/crypto/modules/web.js +++ b/src/crypto/modules/web.js @@ -11,6 +11,8 @@ function concatArrayBuffer(ab1, ab2) { export default class WebCryptography { static IV_LENGTH = 16; + static encoder = new TextEncoder(); + static decoder = new TextDecoder(); get algo() { return 'aes-256-cbc'; @@ -30,7 +32,6 @@ export default class WebCryptography { async decrypt(key, input) { const cKey = await this.getKey(key); - if (input instanceof ArrayBuffer) { return this.decryptArrayBuffer(cKey, input); } @@ -41,9 +42,10 @@ export default class WebCryptography { } async encryptFile(key, file, File) { + if (file.data.byteLength <= 0) throw new Error('encryption error. empty content'); const bKey = await this.getKey(key); - const abPlaindata = await file.toArrayBuffer(); + const abPlaindata = await file.data.arrayBuffer(); const abCipherdata = await this.encryptArrayBuffer(bKey, abPlaindata); @@ -57,8 +59,7 @@ export default class WebCryptography { async decryptFile(key, file, File) { const bKey = await this.getKey(key); - const abCipherdata = await file.toArrayBuffer(); - + const abCipherdata = await file.data.arrayBuffer(); const abPlaindata = await this.decryptArrayBuffer(bKey, abCipherdata); return File.create({ @@ -68,11 +69,11 @@ export default class WebCryptography { } async getKey(key) { - const bKey = Buffer.from(key); - const abHash = await crypto.subtle.digest('SHA-256', bKey.buffer); - - const abKey = Buffer.from(Buffer.from(abHash).toString('hex').slice(0, 32), 'utf8').buffer; - + const digest = await crypto.subtle.digest('SHA-256', WebCryptography.encoder.encode(key)); + const hashHex = Array.from(new Uint8Array(digest)) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); + const abKey = WebCryptography.encoder.encode(hashHex.slice(0, 32)).buffer; return crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt']); } @@ -84,28 +85,33 @@ export default class WebCryptography { async decryptArrayBuffer(key, ciphertext) { const abIv = ciphertext.slice(0, 16); - - return crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16)); + if (ciphertext.slice(WebCryptography.IV_LENGTH).byteLength <= 0) throw new Error('decryption error: empty content'); + const data = await crypto.subtle.decrypt( + { name: 'AES-CBC', iv: abIv }, + key, + ciphertext.slice(WebCryptography.IV_LENGTH), + ); + return data; } async encryptString(key, plaintext) { const abIv = crypto.getRandomValues(new Uint8Array(16)); - const abPlaintext = Buffer.from(plaintext).buffer; + const abPlaintext = WebCryptography.encoder.encode(plaintext).buffer; const abPayload = await crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext); const ciphertext = concatArrayBuffer(abIv.buffer, abPayload); - return Buffer.from(ciphertext).toString('utf8'); + return WebCryptography.decoder.decode(ciphertext); } async decryptString(key, ciphertext) { - const abCiphertext = Buffer.from(ciphertext); + const abCiphertext = WebCryptography.encoder.encode(ciphertext).buffer; const abIv = abCiphertext.slice(0, 16); const abPayload = abCiphertext.slice(16); const abPlaintext = await crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload); - return Buffer.from(abPlaintext).toString('utf8'); + return WebCryptography.decoder.decode(abPlaintext); } } diff --git a/src/file/modules/node.js b/src/file/modules/node.js index 751b81773..9b51c6e27 100644 --- a/src/file/modules/node.js +++ b/src/file/modules/node.js @@ -1,11 +1,7 @@ -/** */ - import { Readable, PassThrough } from 'stream'; -import { ReadStream } from 'fs'; +import fs from 'fs'; import { basename } from 'path'; -import { IFile, FileClass } from '..'; - const PubNubFile = class PubNubFile { static supportsBlob = false; @@ -29,6 +25,8 @@ const PubNubFile = class PubNubFile { mimeType; + contentLength; + static create(config) { return new this(config); } @@ -37,9 +35,10 @@ const PubNubFile = class PubNubFile { if (stream instanceof Readable) { this.data = stream; - if (stream instanceof ReadStream) { + if (stream instanceof fs.ReadStream) { // $FlowFixMe: incomplete flow node definitions this.name = basename(stream.path); + this.contentLength = fs.statSync(stream.path).size; } } else if (data instanceof Buffer) { this.data = Buffer.from(data); diff --git a/src/networking/modules/node.js b/src/networking/modules/node.js index 08f068db3..b5d272044 100644 --- a/src/networking/modules/node.js +++ b/src/networking/modules/node.js @@ -1,6 +1,6 @@ import superagent from 'superagent'; -import superagentProxy from 'superagent-proxy'; import AgentKeepAlive from 'agentkeepalive'; +import superagentProxy from '../proxyAgent'; let keepAliveAgent = null; let keepAliveSecureAgent = null; diff --git a/src/networking/proxyAgent.js b/src/networking/proxyAgent.js new file mode 100644 index 000000000..ebee260ea --- /dev/null +++ b/src/networking/proxyAgent.js @@ -0,0 +1,15 @@ +import { ProxyAgent } from 'proxy-agent'; + +export default function (superagent) { + var Request = superagent.Request; + Request.prototype.proxy = proxy; + return superagent; +} + +function proxy(proxyConfiguration) { + var agent = new ProxyAgent(proxyConfiguration); + + if (agent) this.agent(agent); + + return this; +} diff --git a/src/node/index.ts b/src/node/index.ts index 5d7b3cd73..c95b77ae3 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -8,8 +8,10 @@ import { keepAlive, proxy } from '../networking/modules/node'; import NodeCryptography from '../crypto/modules/node'; import PubNubFile from '../file/modules/node'; +import { CryptoModule, LegacyCryptor, AesCbcCryptor } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; export = class extends PubNubCore { + static CryptoModule = CryptoModule; constructor(setup: any) { setup.cbor = new Cbor((buffer: ArrayBuffer) => CborReader.decode(Buffer.from(buffer)), decode); setup.networking = new Networking({ @@ -27,6 +29,16 @@ export = class extends PubNubCore { setup.PubNubFile = PubNubFile; setup.cryptography = new NodeCryptography(); + setup.initCryptoModule = (cryptoConfiguration: any) => { + return new CryptoModule({ + default: new LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); + }; + if (!('ssl' in setup)) { setup.ssl = true; } diff --git a/src/web/index.js b/src/web/index.js index 52564ae17..24008da2e 100644 --- a/src/web/index.js +++ b/src/web/index.js @@ -11,6 +11,7 @@ import { del, get, post, patch, getfile, postfile } from '../networking/modules/ import WebCryptography from '../crypto/modules/web'; import PubNubFile from '../file/modules/web'; +import { CryptoModule, LegacyCryptor, AesCbcCryptor } from '../crypto/modules/WebCryptoModule/webCryptoModule'; function sendBeacon(url) { if (navigator && navigator.sendBeacon) { @@ -21,10 +22,10 @@ function sendBeacon(url) { } export default class extends PubNubCore { + static CryptoModule = CryptoModule; constructor(setup) { // extract config. const { listenToBrowserNetworkEvents = true } = setup; - setup.sdkFamily = 'Web'; setup.networking = new Networking({ del, @@ -40,6 +41,16 @@ export default class extends PubNubCore { setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); + setup.initCryptoModule = (cryptoConfiguration) => { + return new CryptoModule({ + default: new LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); + }; + super(setup); if (listenToBrowserNetworkEvents) { diff --git a/test/contract/steps/cryptoModule/cryptoModule.ts b/test/contract/steps/cryptoModule/cryptoModule.ts new file mode 100644 index 000000000..c7785b85d --- /dev/null +++ b/test/contract/steps/cryptoModule/cryptoModule.ts @@ -0,0 +1,178 @@ +import { Given, When, Then, Before } from '@cucumber/cucumber'; +import { expect } from 'chai'; +import fs from 'fs'; + +import { + CryptoModule, + AesCbcCryptor, + LegacyCryptor, +} from '../../../../lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js'; + +Before(function () { + this.useRandomIVs = true; +}); + +Given('Crypto module with {string} cryptor', function (cryptorIdentifier: string) { + this.cryptorIdentifier = cryptorIdentifier; +}); + +Given( + 'Crypto module with default {string} and additional {string} cryptors', + function (defaultCryptorId: string, additionalCryptorId: string) { + this.defaultCryptorId = defaultCryptorId; + this.additionalCryptorId = additionalCryptorId; + }, +); + +Given('with {string} cipher key', function (cipherKey: string) { + this.cipherKey = cipherKey; +}); + +Given('with {string} vector', function (vector: string) { + if (vector === 'constant') this.useRandomIVs = false; + this._initCryptor = (id: string) => { + return id === 'legacy' + ? new LegacyCryptor({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }) + : new AesCbcCryptor({ cipherKey: this.cipherKey }); + }; +}); + +When('I decrypt {string} file', async function (fileName: string) { + if (this.cryptorIdentifier === 'acrh') { + const cryptor = new AesCbcCryptor({ cipherKey: this.cipherKey }); + this.cryptoModule = CryptoModule.withDefaultCryptor(cryptor); + } + const pubnub = await this.getPubnub({ subscribeKey: 'key' }); + const fileData = fs.readFileSync(this.getFilePath(fileName)); + const file = pubnub.File.create({ + name: fileName, + mimeType: 'text/plain', + data: fileData, + }); + try { + const result = await this.cryptoModule.decryptFile(file, pubnub.File); + } catch (e: any) { + this.errorMessage = e?.message; + } +}); + +When('I decrypt {string} file as {string}', async function (fileName: string, format: string) { + if (this.defaultCryptorId && this.additionalCryptorId) { + this.cryptoModule = new CryptoModule({ + default: this._initCryptor(this.defaultCryptorId), + cryptors: [this._initCryptor(this.additionalCryptorId)], + }); + } else { + this.cryptoModule = CryptoModule.withDefaultCryptor(this._initCryptor(this.cryptorIdentifier)); + } + + const pubnub = await this.getPubnub({ subscribeKey: 'key' }); + + if (format === 'binary') { + this.isBinary = true; + if (!this.useRandomIVs) return; + let encrypteFile = pubnub.File.create({ + name: fileName, + data: fs.readFileSync(this.getFilePath(fileName)), + }); + try { + this.binaryFileResult = await this.cryptoModule.decryptFile(encrypteFile, pubnub.File); + } catch (e: any) { + this.errorMessage = e?.message; + } + } else if (format === 'stream') { + this.isStream = true; + const filestream = fs.createReadStream(this.getFilePath(fileName)); + this.file = pubnub.File.create({ + name: fileName, + stream: filestream, + }); + try { + this.streamFileResult = await this.cryptoModule.decryptFile(this.file, pubnub.File); + } catch (e: any) { + this.errorMessage = e?.message; + } + } +}); + +Then('Decrypted file content equal to the {string} file content', async function (sourceFile: string) { + if (this.isBinary && !this.useRandomIVs) return; + if (this.isStream) { + const fileStream = await this.streamFileResult.toStream(); + const tempFilePath = `${__dirname}/${this.file.name}`; + const outputStream = fs.createWriteStream(tempFilePath); + const expected = fs.readFileSync(this.getFilePath(sourceFile)); + fileStream.pipe(outputStream); + return new Promise((resolve) => { + outputStream.on('finish', () => { + try { + const actual = fs.readFileSync(tempFilePath); + expect(Buffer.compare(actual, expected.slice(0, actual.length)) === 0).to.be.true; + } finally { + fs.unlink(tempFilePath, () => {}); + } + resolve(0); + }); + }); + } + expect(this.binaryFileResult.data.equals(fs.readFileSync(this.getFilePath(sourceFile)))).to.be.true; +}); + +Then('I receive {string}', async function (result: string) { + if ((this.isBinaryFile || this.isBinary) && !this.useRandomIVs) return; + if (result === 'success') { + expect(this.errorMessage).to.be.undefined; + } else { + expect(this.errorMessage).to.have.string(result); + } +}); + +Given('Legacy code with {string} cipher key and {string} vector', function (cipherKey: string, vector: string) { + const cryptor = new LegacyCryptor({ cipherKey: cipherKey, useRandomIVs: vector === 'random' ? true : false }); + this.cryptoModule = CryptoModule.withDefaultCryptor(cryptor); +}); + +When('I encrypt {string} file as {string}', async function (fileName: string, format: string) { + this.pubnub = await this.getPubnub({ subscribeKey: 'key' }); + this.fileDataBuffer = fs.readFileSync(this.getFilePath(fileName)); + if (format === 'stream') { + this.file = this.pubnub.File.create({ + name: fileName, + mimeType: 'application/octet-stream', + stream: fs.createReadStream(this.getFilePath(fileName)), + }); + this.isStream = true; + } else { + this.file = this.pubnub.File.create({ + name: fileName, + mimeType: 'application/octet-stream', + data: this.fileDataBuffer, + }); + this.isBinaryFile = true; + } + if (!this.cryptoModule) { + this.cryptoModule = CryptoModule.withDefaultCryptor(this._initCryptor(this.cryptorIdentifier)); + } + try { + this.encryptedFile = await this.cryptoModule.encryptFile(this.file, this.pubnub.File); + } catch (e: any) { + this.errorMessage = e?.message; + } +}); + +Then('Successfully decrypt an encrypted file with legacy code', async function () { + const decryptedFile = await this.cryptoModule.decryptFile(this.encryptedFile, this.pubnub.File); + if (this.isStream) { + const fileStream = await decryptedFile.toStream(); + const tempFilePath = `${__dirname}/${this.file.name}`; + const outputStream = fs.createWriteStream(tempFilePath); + fileStream.pipe(outputStream); + outputStream.on('end', () => { + const actualFileBuffer = fs.readFileSync(tempFilePath); + expect(actualFileBuffer).to.equalBytes(this.fileDataBuffer); + fs.unlink(tempFilePath, () => {}); + }); + } else { + expect(decryptedFile.data.toString('utf8')).to.equal(this.fileDataBuffer.toString('utf8')); + } +}); diff --git a/test/integration/components/config.test.js b/test/integration/components/config.test.js index 2234698f8..a639494a3 100644 --- a/test/integration/components/config.test.js +++ b/test/integration/components/config.test.js @@ -42,6 +42,17 @@ describe('components/config', () => { assert.equal(pubnub.getUUID(), 'uuid2'); }); + it('get/set userId', () => { + let pubnub = new PubNub({ + subscribeKey: 'mySubKey', + publishKey: 'myPublishKey', + userId: 'userId1', + }); + assert.equal(pubnub.getUserId(), 'userId1'); + pubnub.setUserId('userId2'); + assert.equal(pubnub.getUserId(), 'userId2'); + }); + it('throws when both userId and uuid are provided', () => { let config = { subscribeKey: 'demo', publishKey: 'demo', uuid: 'myUuid', userId: 'myUserId' }; diff --git a/test/integration/components/crypto.test.js b/test/integration/components/crypto.test.js index 4b4a1ee7b..b425c55ff 100644 --- a/test/integration/components/crypto.test.js +++ b/test/integration/components/crypto.test.js @@ -23,4 +23,26 @@ describe('components/crypto useRandomIVs', () => { expect(decrypted).to.deep.equal(data); }); + + it('should be able to encrypt and decrypt a message with CryptoModule', () => { + const pubnub = new PubNub({ + subscribeKey: 'demo-36', + publishKey: 'demo-36', + useRandomIVs: true, + cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({ + cipherKey: 'abcd' + }), + uuid: 'myUUID', + }); + const data = { + message: + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', + }; + const plaintext = JSON.stringify(data); + const ciphertext = pubnub.encrypt(plaintext); + + const decrypted = pubnub.decrypt(ciphertext); + + expect(decrypted).to.deep.equal(data); + }); }); diff --git a/test/integration/components/subscription_manager.test.js b/test/integration/components/subscription_manager.test.js index a7fd09bbd..56990f990 100644 --- a/test/integration/components/subscription_manager.test.js +++ b/test/integration/components/subscription_manager.test.js @@ -12,6 +12,7 @@ describe('#components/subscription_manager', () => { let pubnub; let pubnubWithPassingHeartbeats; let pubnubWithLimitedQueue; + let pubnubWithCrypto; before(() => { nock.disableNetConnect(); @@ -46,6 +47,12 @@ describe('#components/subscription_manager', () => { autoNetworkDetection: false, heartbeatInterval: 149, }); + pubnubWithCrypto = new PubNub({ + subscribeKey: 'mySubKey', + publishKey: 'myPublishKey', + uuid: 'myUUID', + cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({ cipherKey: 'cipherKey' }), + }); }); afterEach(() => { @@ -653,4 +660,128 @@ describe('#components/subscription_manager', () => { } }, 250); }); + + it('handles unencrypted message when cryptoModule is configured', (done) => { + const scope = utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + heartbeat: 300, + }) + .reply( + 200, + '{"t":{"t":"3","r":1},"m":[{"a":"4","f":0,"i":"Client-g5d4g","p":{"t":"14607577960925503","r":1}, "i": "client1", "k":"sub-c-4cec9f8e-01fa-11e6-8180-0619f8945a4f","c":"coolChannel","d":"hello","b":"coolChan-bnel"}]}', + ); + + let incomingPayloads = []; + + pubnubWithCrypto.addListener({ + message(messagePayload) { + incomingPayloads.push(messagePayload); + if (incomingPayloads.length === 1) { + assert.equal(scope.isDone(), true); + assert.deepEqual(incomingPayloads, [ + { + actualChannel: 'coolChannel', + message: 'hello', + subscribedChannel: 'coolChan-bnel', + channel: 'coolChannel', + subscription: 'coolChan-bnel', + timetoken: '14607577960925503', + publisher: 'client1', + error: 'Error while decrypting message content: decryption error. invalid header version', + }, + ]); + done(); + } + }, + }); + + pubnubWithCrypto.subscribe({ channels: ['ch1'] }); + }); + + it('handles unencrypted message when `setCipherKey()` is used', (done) => { + pubnub.setCipherKey('hello'); + const scope = utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + heartbeat: 300, + }) + .reply( + 200, + '{"t":{"t":"3","r":1},"m":[{"a":"4","f":0,"i":"Client-g5d4g","p":{"t":"14607577960925503","r":1}, "i": "client1", "k":"sub-c-4cec9f8e-01fa-11e6-8180-0619f8945a4f","c":"coolChannel","d":"hello","b":"coolChan-bnel"}]}', + ); + + let incomingPayloads = []; + + pubnubWithCrypto.addListener({ + message(messagePayload) { + incomingPayloads.push(messagePayload); + console.log('\n\n\n incomingpayload = ', JSON.stringify(incomingPayloads)); + if (incomingPayloads.length === 1) { + assert.equal(scope.isDone(), true); + assert.deepEqual(incomingPayloads, [ + { + actualChannel: 'coolChannel', + message: 'hello', + subscribedChannel: 'coolChan-bnel', + channel: 'coolChannel', + subscription: 'coolChan-bnel', + timetoken: '14607577960925503', + publisher: 'client1', + error: 'Error while decrypting message content: decryption error. invalid header version', + }, + ]); + done(); + } + }, + }); + + pubnubWithCrypto.subscribe({ channels: ['ch1'] }); + }); + + it('handles encryped messages when cryptoModule is configured', (done) => { + const scope = utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + heartbeat: 300, + }) + .reply( + 200, + '{"t":{"t":"3","r":1},"m":[{"a":"4","f":0,"i":"Client-g5d4g","p":{"t":"14607577960925503","r":1}, "i": "client1", "k":"sub-c-4cec9f8e-01fa-11e6-8180-0619f8945a4f","c":"coolChannel","d":"UE5FRAFBQ1JIEIocqA6BfaybN/3U0WJRam0v3bPwfAXezgeCeGp+MztQ","b":"coolChan-bnel"}]}', + ); + + let incomingPayloads = []; + + pubnubWithCrypto.addListener({ + message(messagePayload) { + incomingPayloads.push(messagePayload); + if (incomingPayloads.length === 1) { + assert.equal(scope.isDone(), true); + assert.deepEqual(incomingPayloads, [ + { + actualChannel: 'coolChannel', + message: 'hello', + subscribedChannel: 'coolChan-bnel', + channel: 'coolChannel', + subscription: 'coolChan-bnel', + timetoken: '14607577960925503', + publisher: 'client1', + }, + ]); + done(); + } + }, + }); + + pubnubWithCrypto.subscribe({ channels: ['ch1'] }); + }); }); diff --git a/test/integration/endpoints/fetch_messages.test.js b/test/integration/endpoints/fetch_messages.test.js index 151cd9a30..9ca8fb9df 100644 --- a/test/integration/endpoints/fetch_messages.test.js +++ b/test/integration/endpoints/fetch_messages.test.js @@ -6,7 +6,7 @@ import nock from 'nock'; import utils from '../../utils'; import PubNub from '../../../src/node/index'; -function publishMessagesToChannel(client , count , channel , completion ) { +function publishMessagesToChannel(client, count, channel, completion) { let publishCompleted = 0; let messages = []; @@ -38,13 +38,7 @@ function publishMessagesToChannel(client , count , channel publish(publishCompleted); } -function addActionsInChannel( - client , - count , - messageTimetokens , - channel , - completion -) { +function addActionsInChannel(client, count, messageTimetokens, channel, completion) { const types = ['reaction', 'receipt', 'custom']; const values = [ PubNub.generateUUID(), @@ -562,4 +556,51 @@ describe('fetch messages endpoints', () => { done(); }); }); + + it('handles unencrypted payload when cryptomodule configured', (done) => { + nock.disableNetConnect(); + const scope = utils + .createNock() + .get(`/v3/history/sub-key/${subscribeKey}/channel/ch1`) + .query({ + max: '10', + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + include_uuid: 'true', + include_message_type: 'true', + }) + .reply( + 200, + '{ "channels": { "ch1": [{"message":"hello","timetoken":"11"}, {"message":"hey","timetoken":"12"}] } }', + ); + + pubnub.setCipherKey('cipherKey'); + pubnub.fetchMessages({ channels: ['ch1'], count: 10 }, (status, response) => { + assert.equal(status.error, false); + assert.deepEqual(response, { + channels: { + ch1: [ + { + channel: 'ch1', + message: 'hello', + timetoken: '11', + messageType: undefined, + uuid: undefined, + error: 'Error while decrypting message content: decryption error. invalid header version', + }, + { + channel: 'ch1', + message: 'hey', + timetoken: '12', + messageType: undefined, + uuid: undefined, + error: 'Error while decrypting message content: decryption error. invalid header version', + }, + ], + }, + }); + assert.equal(scope.isDone(), true); + done(); + }); + }); }); diff --git a/test/integration/endpoints/history.test.js b/test/integration/endpoints/history.test.js index 8ff110078..34897b3c4 100644 --- a/test/integration/endpoints/history.test.js +++ b/test/integration/endpoints/history.test.js @@ -6,7 +6,7 @@ import nock from 'nock'; import utils from '../../utils'; import PubNub from '../../../src/node/index'; -function publishMessagesToChannel(client , count , channel , completion ) { +function publishMessagesToChannel(client, count, channel, completion) { let publishCompleted = 0; let messages = []; @@ -38,7 +38,6 @@ function publishMessagesToChannel(client , count , channel publish(publishCompleted); } - describe('history endpoints', () => { const subscribeKey = process.env.SUBSCRIBE_KEY || 'demo'; const publishKey = process.env.PUBLISH_KEY || 'demo'; @@ -61,7 +60,7 @@ describe('history endpoints', () => { subscribeKey, publishKey, uuid: 'myUUID', - useRandomIVs: false + useRandomIVs: false, }); }); @@ -79,23 +78,20 @@ describe('history endpoints', () => { }) .reply( 200, - '[[{"message":{"text":"hey"},"timetoken":"14648503433058358"},{"message":{"text2":"hey2"},"timetoken":"14648503433058359"}],"14648503433058358","14649346364851578"]' + '[[{"message":{"text":"hey"},"timetoken":"14648503433058358"},{"message":{"text2":"hey2"},"timetoken":"14648503433058359"}],"14648503433058358","14649346364851578"]', ); - pubnub.history( - { channel: 'ch1', stringifiedTimeToken: true }, - (status, response) => { - assert.equal(status.error, false); - assert.deepEqual(response.startTimeToken, '14648503433058358'); - assert.deepEqual(response.endTimeToken, '14649346364851578'); - assert.deepEqual(response.messages, [ - { timetoken: '14648503433058358', entry: { text: 'hey' } }, - { timetoken: '14648503433058359', entry: { text2: 'hey2' } }, - ]); - assert.equal(scope.isDone(), true); - done(); - } - ); + pubnub.history({ channel: 'ch1', stringifiedTimeToken: true }, (status, response) => { + assert.equal(status.error, false); + assert.deepEqual(response.startTimeToken, '14648503433058358'); + assert.deepEqual(response.endTimeToken, '14649346364851578'); + assert.deepEqual(response.messages, [ + { timetoken: '14648503433058358', entry: { text: 'hey' } }, + { timetoken: '14648503433058359', entry: { text2: 'hey2' } }, + ]); + assert.equal(scope.isDone(), true); + done(); + }); }); it('supports encrypted payload with timetoken', (done) => { @@ -112,24 +108,21 @@ describe('history endpoints', () => { }) .reply( 200, - '[[{"message":"zFJeF9BVABL80GUiQEBjLg==","timetoken":"14649369736959785"},{"message":"HIq4MTi9nk/KEYlHOKpMCaH78ZXppGynDHrgY9nAd3s=","timetoken":"14649369766426772"}],"14649369736959785","14649369766426772"]' + '[[{"message":"zFJeF9BVABL80GUiQEBjLg==","timetoken":"14649369736959785"},{"message":"HIq4MTi9nk/KEYlHOKpMCaH78ZXppGynDHrgY9nAd3s=","timetoken":"14649369766426772"}],"14649369736959785","14649369766426772"]', ); pubnub.setCipherKey('cipherKey'); - pubnub.history( - { channel: 'ch1', stringifiedTimeToken: true }, - (status, response) => { - assert.equal(status.error, false); - assert.deepEqual(response.startTimeToken, '14649369736959785'); - assert.deepEqual(response.endTimeToken, '14649369766426772'); - assert.deepEqual(response.messages, [ - { timetoken: '14649369736959785', entry: { text: 'hey' } }, - { timetoken: '14649369766426772', entry: { text2: 'hey2' } }, - ]); - assert.equal(scope.isDone(), true); - done(); - } - ); + pubnub.history({ channel: 'ch1', stringifiedTimeToken: true }, (status, response) => { + assert.equal(status.error, false); + assert.deepEqual(response.startTimeToken, '14649369736959785'); + assert.deepEqual(response.endTimeToken, '14649369766426772'); + assert.deepEqual(response.messages, [ + { timetoken: '14649369736959785', entry: { text: 'hey' } }, + { timetoken: '14649369766426772', entry: { text2: 'hey2' } }, + ]); + assert.equal(scope.isDone(), true); + done(); + }); }); it('supports metadata', (done) => { @@ -153,19 +146,55 @@ describe('history endpoints', () => { const average = Math.floor(countedDelays.reduce((acc, delay) => acc + delay, 0) / countedDelays.length); const leeway = 50; - utils.runAPIWithResponseDelays(scope, - 200, - '[[{"message":{"text":"hey"},"timetoken":"14648503433058358"},{"message":{"text2":"hey2"},"timetoken":"14648503433058359"}],"14648503433058358","14649346364851578"]', - delays, - (completion) => { - pubnub.history( - { channel: 'ch1', stringifiedTimeToken: true }, - () => { completion(); } - ); - }) + utils + .runAPIWithResponseDelays( + scope, + 200, + '[[{"message":{"text":"hey"},"timetoken":"14648503433058358"},{"message":{"text2":"hey2"},"timetoken":"14648503433058359"}],"14648503433058358","14649346364851578"]', + delays, + (completion) => { + pubnub.history({ channel: 'ch1', stringifiedTimeToken: true }, () => { + completion(); + }); + }, + ) .then((lastRequest) => { utils.verifyRequestTelemetry(lastRequest.path, 'l_hist', average, leeway); done(); }); }).timeout(60000); + + it('handles unencrypted payload with cryptoModule', (done) => { + nock.disableNetConnect(); + const scope = utils + .createNock() + .get(`/v2/history/sub-key/${subscribeKey}/channel/ch1`) + .query({ + count: '100', + include_token: 'true', + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + string_message_token: true, + }) + .reply( + 200, + '[[{"message":"zFJeF9BVABL80GUiQEBjLg==","timetoken":"14648503433058358"},{"message":"hello","timetoken":"14648503433058359"}],"14648503433058358","14649346364851578"]', + ); + pubnub.setCipherKey('cipherKey'); + pubnub.history({ channel: 'ch1', stringifiedTimeToken: true }, (status, response) => { + assert.equal(status.error, false); + assert.deepEqual(response.startTimeToken, '14648503433058358'); + assert.deepEqual(response.endTimeToken, '14649346364851578'); + assert.deepEqual(response.messages, [ + { timetoken: '14648503433058358', entry: { text: 'hey' } }, + { + timetoken: '14648503433058359', + entry: 'hello', + error: 'Error while decrypting message content: decryption error. invalid header version', + }, + ]); + assert.equal(scope.isDone(), true); + done(); + }); + }); }); diff --git a/test/old_contract/utils.ts b/test/old_contract/utils.ts index f0386f635..a8226a8c9 100644 --- a/test/old_contract/utils.ts +++ b/test/old_contract/utils.ts @@ -7,3 +7,7 @@ export function loadFixtureFile(persona: string) { ); return JSON.parse(fileData); } + +export function getFilePath(filename) { + return `${process.cwd()}/dist/contract/contract/features/encryption/assets/${filename}`; +} diff --git a/test/old_contract/world.ts b/test/old_contract/world.ts index 3ef2e3fa8..79a4577c5 100644 --- a/test/old_contract/world.ts +++ b/test/old_contract/world.ts @@ -1,6 +1,6 @@ import { setWorldConstructor, setDefaultTimeout, World } from '@cucumber/cucumber'; import PubNub from '../../lib/node/index.js'; -import { loadFixtureFile } from './utils'; +import { loadFixtureFile, getFilePath } from './utils'; import * as http from 'http'; interface State { @@ -130,6 +130,9 @@ class PubnubWorld extends World { } return this.fileFixtures[name]; } + getFilePath(filename) { + return getFilePath(filename); + } } setWorldConstructor(PubnubWorld); diff --git a/tsconfig.json b/tsconfig.json index 3fe149522..2103f09c5 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,18 +1,20 @@ { "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { "target": "ES5", "module": "CommonJS", "moduleResolution": "Node", "esModuleInterop": true, - "allowJs": true, "noEmitOnError": true, "strict": true, "outDir": "./lib", "downlevelIteration": true }, - "include": ["src/**/*"], - "exclude": ["node_modules"] -} + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} \ No newline at end of file