From 7dabfd382a3697e164cf2719dc3250afbd3b57f0 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 11 Sep 2023 08:45:32 +0530 Subject: [PATCH 01/38] ref: decoupling cryptor module --- src/core/components/config.js | 7 ++++++- src/core/components/subscription_manager.js | 2 ++ src/core/pubnub-common.js | 5 ++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/core/components/config.js b/src/core/components/config.js index a7c8c2d7c..1e6759fda 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -129,12 +129,15 @@ export default class { maximumCacheSize; /* - support customp encryption and decryption functions. + support custom encryption and decryption functions. */ customEncrypt; // function to support custome encryption of messages customDecrypt; // function used to decrypt old version messages + // registered cryptors for encryption and decryption of messages. + cryptors; + // File Upload // How many times the publish-file should be retried before giving up @@ -175,6 +178,8 @@ export default class { this.customEncrypt = setup.customEncrypt; this.customDecrypt = setup.customDecrypt; + this.cryptors = setup.cryptors || []; + this.fileUploadPublishRetryLimit = setup.fileUploadPublishRetryLimit ?? 5; this.useRandomIVs = setup.useRandomIVs ?? true; diff --git a/src/core/components/subscription_manager.js b/src/core/components/subscription_manager.js index 1e0e40165..fa02e37ea 100644 --- a/src/core/components/subscription_manager.js +++ b/src/core/components/subscription_manager.js @@ -70,6 +70,7 @@ export default class { config, crypto, listenerManager, + cryptors, }) { this._listenerManager = listenerManager; this._config = config; @@ -729,6 +730,7 @@ export default class { if (this._config.cipherKey) { announce.message = this._crypto.decrypt(message.payload); + //TODO: select one of the cryptors and decrypt. } else { announce.message = message.payload; } diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index 1c15e342c..a28a88114 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -278,8 +278,9 @@ export default class { const config = new Config({ setup }); this._config = config; const crypto = new Crypto({ config }); // LEGACY - + const { cryptography } = setup; + const cryptors = [crypto, cryptography, ...config.cryptors]; networking.init(config); @@ -297,6 +298,7 @@ export default class { networking, crypto, cryptography, + cryptors, tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, @@ -341,6 +343,7 @@ export default class { config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), + cryptors: modules.cryptors, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); From 77d6a96ee18d28ba0d19ac025ffa309eb8451601 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 19 Sep 2023 15:18:39 +0530 Subject: [PATCH 02/38] cryptoModule --- src/core/endpoints/file_upload/send_file.js | 19 +- .../NodeCryptoModule/NodeCryptoModule.js | 301 ++++++++++++++++++ .../modules/NodeCryptoModule/aesCbcCryptor.js | 91 ++++++ .../modules/NodeCryptoModule/legacyCryptor.js | 36 +++ src/crypto/modules/node.js | 25 +- 5 files changed, 446 insertions(+), 26 deletions(-) create mode 100644 src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js create mode 100644 src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js create mode 100644 src/crypto/modules/NodeCryptoModule/legacyCryptor.js diff --git a/src/core/endpoints/file_upload/send_file.js b/src/core/endpoints/file_upload/send_file.js index 6e1a08f8e..5eb8be763 100644 --- a/src/core/endpoints/file_upload/send_file.js +++ b/src/core/endpoints/file_upload/send_file.js @@ -1,18 +1,5 @@ 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, @@ -68,11 +55,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/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js new file mode 100644 index 000000000..dbd614939 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -0,0 +1,301 @@ +import { Readable, PassThrough, Transform } from 'stream'; +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; +import LegacyCryptor from './legacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; + +export default class CryptoModule { + defaultCryptor; + cryptors = []; + + constructor({cryptoModuleConfiguration}) { + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = [...this.defaultCryptor, ...cryptoModuleConfiguration.cryptors]; + } + + static legacyCryptoModule({config}) { + return new this({ + default: new LegacyCryptor({config}), + cryptors: [new AesCbcCryptor(config.cipherKey)] + }) + } + + static aesCbcCryptoModule({config}) { + return new this({ + default: new AesCbcCryptor(config.cipherKey), + cryptors: [new LegacyCryptor({config})] + }) + } + + async encrypt(data, encoding) { + let encrypted = this.default.encrypt(data); + + let header = CryptoHeader.from(this.default.identifier, encrypted.metadata); + + let payload = new Uint8Array(header.length); + let pos = 0; + payload.set(header.data, pos); + pos += header.length; + if (encrypted.metadata) { + pos -= encrypted.metadata.length; + payload.set(encrypted.metadata, pos); + } + if (encoding) { + return Buffer.concat([payload, encrypted.data]).toString(encoding); + } else { + return Buffer.concat([payload, encrypted.data]); + } + } + + async decrypt(data, encoding) { + let encryptedData = null; + if (encoding) { + encryptedData = Buffer.from(data, encoding); + } else { + encryptedData = Buffer.from(data); + } + let header = CryptoHeader.tryParse(encryptedData); + let cryptor = this._getCryptor(header); + + if (cryptor instanceof LegacyCryptor) return cryptor.decrypt(data); + + return cryptor.decrypt({ + data: encryptedData.slice(header.length), + metadata: encryptedData.slice(header.length - header.size, header.length), + }); + } + + async encryptFile(file, File) { + if (this.defaultCryptor instanceof LegacyCryptor) + return this.defaultCryptor.encryptFile(file, File) ; + if (file.data instanceof Buffer) { + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: await this.encrypt(file.data), + }); + } + if (file.data instanceof Readable) { + let encryptedStream = this.defaultCryptor.encryptStream(file.data); + let header = CryptoHeader.from(this.default.identifier, encryptedStream.metadata); + + let 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.data.pipe(output); + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: output, + }); + } + } + + async decryptFile(file, File) { + if (file.data instanceof Buffer){ + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: await this.encrypt(file.data), + }); + } + + if (file.data instanceof Readable){ + let stream = file.data; + return new Promise((resolve, _) => { + stream.on('readable', () => resolve(this._decryptStream(stream,file, File))); + }); + } + } + + async _decryptStream(stream, file, File) { + let magicBytes = stream.read(4); + if (magicBytes !== null) { + if (!CryptoHeader.isSentinel(magicBytes)) { + return this._legacyFileDecrypt(magicBytes, stream); + } + let versionByte = stream.read(1); + CryptoHeader.validateVersion(versionByte[0]); + let identifier = stream.read(4); + let cryptor = this._getCryptorFromId(CryptoHeader.tryGetIdentifier(identifier)); + let headerSize = CryptoHeader.tryGetMetadataSizeFromStream(stream); + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: await cryptor.decryptStream({ stream: stream, metadataLength: headerSize })}); + } + } + + async _legacyFileDecrypt(bytes, stream) { + const sourceStream = new PassThrough(); + sourceStream.write(bytes); + stream.pipe(sourceStream); + stream.pause(); + sourceStream.pause(); + return this.default.decryptFile( + File.create({ + name: file.name, + mimeType: 'application/octet-stream', + data: sourceStream, + }), + ); + } + + _getCryptor(header) { + if (header === null) { + return this.legacyCryptor; + } else if (header instanceof CryptoHeaderV1) { + return this._getCryptorFromId(header.identifier); + } + } + + _getCryptorFromId(id) { + const cryptor = this.cryptors.find((c) => id === c.identifier); + if (cryptor) { + return cryptor; + } + throw Error('No registered cryptor can decrypt the data.'); + } +} + +// CryptoHeader Utility +class CryptoHeader { + static SENTINEL = 'PNED'; + static IDENTIFIER_LENGTH = 4; + static MAX_VERSION = 1; + + static from(id, headerSize) { + return new CryptoHeaderV1(id, headerSize); + } + + static isSentinel(bytes) { + if (bytes && bytes.byteLength >= 4) { + if (bytes.toString('utf8') == CryptoHeader.SENTINEL) return true; + } + } + + static validateVersion(data) { + if (data && data > CryptoHeader.MAX_VERSION) throw Error('Decrypting data created by unknown cryptor.'); + return data; + } + + static tryGetIdentifier(data) { + if (data & (data.byteLength < 4)) { + throw Error('Decrypted data header is malformed.'); + } else { + return data.toString('utf8'); + } + } + + static tryGetMetadataSizeFromStream(stream) { + let sizeBuf = stream.read(1); + if (sizeBuf && sizeBuf[0] < 255) { + return sizeBuf[0]; + } + if (sizeBuf === 255) { + let nextBuf = stream(2); + if (nextBuf & (nextBuf.byteLength >= 2)) { + return new Uint16Array([nextBuf[0], nextBuf[1]]).reduce((acc, val) => (acc << 8) + val, 0); + } + } + } + static tryParse(encryptedData) { + let sentinel = ''; + let version = null; + if (encryptedData.length >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== CryptoHeader.SENTINEL) return null; + } + + if (encryptedData.length >= 5) { + version = encryptedData[4]; + } else { + throw Error('Decrypted data header is malformed.'); + } + if (version > CryptoHeader.MAX_VERSION) throw Error('Decrypting data created by unknown cryptor.'); + + let identifier = ''; + let pos = 5 + CryptoHeader.IDENTIFIER_LENGTH; + if (encryptedData.length >= pos) { + identifier = encryptedData.slice(5, pos); + } else { + throw Error('Decrypted data header is malformed.'); + } + let headerSize = null; + if (encryptedData.length > pos + 1) { + headerSize = encryptedData[pos]; + } + pos += 1; + if (headerSize === 255 && encryptedData.length >= pos + 2) { + headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce((acc, val) => (acc << 8) + val, 0); + pos += 2; + } + return new CryptoHeaderV1(identifier.toString('utf8'), encryptedData.slice(pos, pos + headerSize)); + } +} + +// v1 cryptoHeader +class CryptoHeaderV1 { + static IDENTIFIER_LENGTH = 4; + + static SENTINEL = 'PNED'; + static VERSION = 1; + + identifier; + metadata; + + constructor(id, metadata) { + this.identifier = id; + this.metadata = metadata; + } + + get identifier() { + return this.identifier; + } + + get metadata() { + return this.metadata; + } + + get version() { + return CryptoHeaderV1.VERSION; + } + + get length() { + return ( + CryptoHeaderV1.SENTINEL.length + + 1 + + CryptoHeaderV1.IDENTIFIER_LENGTH + + (this.metadata.length < 255 ? 1 : 3) + + this.metadata.length + ); + } + + get size() { + return this.metadata.length; + } + + get data() { + let pos = 0; + const header = new Uint8Array(this.length); + header.set(Buffer.from(CryptoHeaderV1.SENTINEL)); + pos += CryptoHeaderV1.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) header.set(Buffer.from(this.identifier), pos); + pos += CryptoHeaderV1.IDENTIFIER_LENGTH; + let metadata_size = this.metadata.length; + if (metadata_size < 255) { + header[pos] = metadata_size; + } else { + header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + } + return header; + } +} diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js new file mode 100644 index 000000000..ff24dff75 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js @@ -0,0 +1,91 @@ +import { Readable, PassThrough, Transform } from 'stream'; +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; + +export default class AesCbcCryptor { + static BLOCK_SIZE = 16; + + constructor(key) { + this.cipherKey = key; + } + + 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(), 'utf8'); + } + + async encrypt(data) { + const iv = this._getIv(); + const key = this._getKey(); + + const bPlain = Buffer.from(data); + const aes = createCipheriv(this.algo, key, iv); + + return { + metadata: iv, + data: Buffer.concat([aes.update(bPlain), aes.final()]), + }; + } + + async decrypt(encryptedData) { + const aes = createDecipheriv(this.algo, this._getKey(), encryptedData.metadata); + return Buffer.concat([aes.update(encryptedData.data), aes.final()]); + } + + async encryptStream(stream) { + const output = new PassThrough(); + const bIv = this._getIv(); + const aes = createCipheriv(this.algo, this._getKey(), bIv); + stream.pipe(aes).pipe(output); + return { + data: output, + metadata: bIv, + metadataLength: AesCbcCryptor.BLOCK_SIZE, + }; + } + + async decryptStream(encryptedStream) { + const output = new PassThrough(); + + let bIv = Buffer.alloc(0); + let aes = null; + 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(output); + + aes.write(bChunk.slice(sliceLen)); + } + } + data = encryptedStream.stream.read(); + } + encryptedStream.stream.on('end', () => { + if (aes) { + aes.end(); + } + output.end(); + }); + return output; + } +} diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.js b/src/crypto/modules/NodeCryptoModule/legacyCryptor.js new file mode 100644 index 000000000..2b115a827 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -0,0 +1,36 @@ +import Crypto from '../../../core/components/cryptography/index'; +import FileCryptor from '../node'; + +export default class LegacyCryptor { + config; + cipherKey; + useRandomIVs; + + cryptor; + fileCryptor; + + constructor({ pnConfig }) { + this.config = pnConfig + this.cryptor = new Crypto({ pnConfig }); + this.fileCryptor = new FileCryptor(); + } + + get identifier() { + return ''; + } + async encrypt(data) { + return this.cryptor.encrypt(data); + } + + async decrypt(encryptedData) { + return this.cryptor.decrypt(encryptedData); + } + + async encryptFile(file, File) { + return this.fileCryptor.encryptFile(this.config.cipherKey, file, File); + } + + async decryptFile(file, File) { + return this.fileCryptor.decryptFile(this.config.cipherKey, file, File); + } +} diff --git a/src/crypto/modules/node.js b/src/crypto/modules/node.js index 27e9f4f0e..d198daba1 100644 --- a/src/crypto/modules/node.js +++ b/src/crypto/modules/node.js @@ -124,16 +124,23 @@ export default class NodeCryptography { 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) { From 3382595301b223aceb8f9983fbe7fa985fd05e16 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 19 Sep 2023 15:23:49 +0530 Subject: [PATCH 03/38] lint --- .../NodeCryptoModule/NodeCryptoModule.js | 28 +++++++++---------- .../modules/NodeCryptoModule/legacyCryptor.js | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index dbd614939..fadc82fad 100644 --- a/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -7,23 +7,23 @@ export default class CryptoModule { defaultCryptor; cryptors = []; - constructor({cryptoModuleConfiguration}) { + constructor({ cryptoModuleConfiguration }) { this.defaultCryptor = cryptoModuleConfiguration.default; this.cryptors = [...this.defaultCryptor, ...cryptoModuleConfiguration.cryptors]; } - static legacyCryptoModule({config}) { + static legacyCryptoModule({ config }) { return new this({ - default: new LegacyCryptor({config}), - cryptors: [new AesCbcCryptor(config.cipherKey)] - }) + default: new LegacyCryptor({ config }), + cryptors: [new AesCbcCryptor(config.cipherKey)], + }); } - static aesCbcCryptoModule({config}) { + static aesCbcCryptoModule({ config }) { return new this({ default: new AesCbcCryptor(config.cipherKey), - cryptors: [new LegacyCryptor({config})] - }) + cryptors: [new LegacyCryptor({ config })], + }); } async encrypt(data, encoding) { @@ -65,8 +65,7 @@ export default class CryptoModule { } async encryptFile(file, File) { - if (this.defaultCryptor instanceof LegacyCryptor) - return this.defaultCryptor.encryptFile(file, File) ; + if (this.defaultCryptor instanceof LegacyCryptor) return this.defaultCryptor.encryptFile(file, File); if (file.data instanceof Buffer) { return File.create({ name: file.name, @@ -98,7 +97,7 @@ export default class CryptoModule { } async decryptFile(file, File) { - if (file.data instanceof Buffer){ + if (file.data instanceof Buffer) { return File.create({ name: file.name, mimeType: 'application/octet-stream', @@ -106,10 +105,10 @@ export default class CryptoModule { }); } - if (file.data instanceof Readable){ + if (file.data instanceof Readable) { let stream = file.data; return new Promise((resolve, _) => { - stream.on('readable', () => resolve(this._decryptStream(stream,file, File))); + stream.on('readable', () => resolve(this._decryptStream(stream, file, File))); }); } } @@ -128,7 +127,8 @@ export default class CryptoModule { return File.create({ name: file.name, mimeType: 'application/octet-stream', - data: await cryptor.decryptStream({ stream: stream, metadataLength: headerSize })}); + data: await cryptor.decryptStream({ stream: stream, metadataLength: headerSize }), + }); } } diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.js b/src/crypto/modules/NodeCryptoModule/legacyCryptor.js index 2b115a827..48dd71cfd 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -10,7 +10,7 @@ export default class LegacyCryptor { fileCryptor; constructor({ pnConfig }) { - this.config = pnConfig + this.config = pnConfig; this.cryptor = new Crypto({ pnConfig }); this.fileCryptor = new FileCryptor(); } From da1cce6956569c367eebf9c4f23fde85684b4a74 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 19 Sep 2023 18:50:34 +0530 Subject: [PATCH 04/38] rever cryptors in config --- src/core/components/config.js | 5 ----- src/core/components/subscription_manager.js | 4 +--- src/core/pubnub-common.js | 3 --- 3 files changed, 1 insertion(+), 11 deletions(-) diff --git a/src/core/components/config.js b/src/core/components/config.js index 1e6759fda..69ccb8fc1 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -135,9 +135,6 @@ export default class { customDecrypt; // function used to decrypt old version messages - // registered cryptors for encryption and decryption of messages. - cryptors; - // File Upload // How many times the publish-file should be retried before giving up @@ -178,8 +175,6 @@ export default class { this.customEncrypt = setup.customEncrypt; this.customDecrypt = setup.customDecrypt; - this.cryptors = setup.cryptors || []; - this.fileUploadPublishRetryLimit = setup.fileUploadPublishRetryLimit ?? 5; this.useRandomIVs = setup.useRandomIVs ?? true; diff --git a/src/core/components/subscription_manager.js b/src/core/components/subscription_manager.js index fa02e37ea..e8bc96864 100644 --- a/src/core/components/subscription_manager.js +++ b/src/core/components/subscription_manager.js @@ -69,8 +69,7 @@ export default class { getFileUrl, config, crypto, - listenerManager, - cryptors, + listenerManager }) { this._listenerManager = listenerManager; this._config = config; @@ -730,7 +729,6 @@ export default class { if (this._config.cipherKey) { announce.message = this._crypto.decrypt(message.payload); - //TODO: select one of the cryptors and decrypt. } else { announce.message = message.payload; } diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index a28a88114..8fb3a5b6c 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -280,7 +280,6 @@ export default class { const crypto = new Crypto({ config }); // LEGACY const { cryptography } = setup; - const cryptors = [crypto, cryptography, ...config.cryptors]; networking.init(config); @@ -298,7 +297,6 @@ export default class { networking, crypto, cryptography, - cryptors, tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, @@ -343,7 +341,6 @@ export default class { config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), - cryptors: modules.cryptors, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); From 41fbba977e309d4482fc01cc3990abeeaf6d0609 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 19 Sep 2023 18:54:11 +0530 Subject: [PATCH 05/38] lint fixes --- src/core/components/subscription_manager.js | 2 +- src/core/pubnub-common.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/components/subscription_manager.js b/src/core/components/subscription_manager.js index e8bc96864..1e0e40165 100644 --- a/src/core/components/subscription_manager.js +++ b/src/core/components/subscription_manager.js @@ -69,7 +69,7 @@ export default class { getFileUrl, config, crypto, - listenerManager + listenerManager, }) { this._listenerManager = listenerManager; this._config = config; diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index 8fb3a5b6c..1c15e342c 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -278,7 +278,7 @@ export default class { const config = new Config({ setup }); this._config = config; const crypto = new Crypto({ config }); // LEGACY - + const { cryptography } = setup; networking.init(config); From cad96a7977d26e272597d2315d793e06c19b96aa Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:20:14 +0530 Subject: [PATCH 06/38] CryptoModule for web and node --- .../WebCryptoModule/webCryptoModule.js | 348 ++++++++++++++++++ .../modules/NodeCryptoModule/ICryptor.ts | 19 + .../NodeCryptoModule/ILegacyCryptor.ts | 15 + .../NodeCryptoModule/NodeCryptoModule.js | 301 --------------- .../modules/NodeCryptoModule/aesCbcCryptor.js | 91 ----- .../modules/NodeCryptoModule/aesCbcCryptor.ts | 92 +++++ .../modules/NodeCryptoModule/legacyCryptor.js | 36 -- .../modules/NodeCryptoModule/legacyCryptor.ts | 39 ++ .../NodeCryptoModule/nodeCryptoModule.ts | 347 +++++++++++++++++ .../modules/WebCryptoModule/ICryptor.ts | 10 + .../modules/WebCryptoModule/ILegacyCryptor.ts | 14 + .../modules/WebCryptoModule/aesCbcCryptor.ts | 51 +++ .../modules/WebCryptoModule/legacyCryptor.ts | 44 +++ .../WebCryptoModule/webCryptoModule.ts | 254 +++++++++++++ src/crypto/modules/node.js | 2 +- src/crypto/modules/web.js | 29 +- 16 files changed, 1256 insertions(+), 436 deletions(-) create mode 100644 lib/crypto/modules/WebCryptoModule/webCryptoModule.js create mode 100644 src/crypto/modules/NodeCryptoModule/ICryptor.ts create mode 100644 src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts delete mode 100644 src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js delete mode 100644 src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js create mode 100644 src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts delete mode 100644 src/crypto/modules/NodeCryptoModule/legacyCryptor.js create mode 100644 src/crypto/modules/NodeCryptoModule/legacyCryptor.ts create mode 100644 src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts create mode 100644 src/crypto/modules/WebCryptoModule/ICryptor.ts create mode 100644 src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts create mode 100644 src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts create mode 100644 src/crypto/modules/WebCryptoModule/legacyCryptor.ts create mode 100644 src/crypto/modules/WebCryptoModule/webCryptoModule.ts diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js new file mode 100644 index 000000000..02daea5a5 --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -0,0 +1,348 @@ +"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 }); +var endpoint_1 = require("../../../core/components/endpoint"); +var legacyCryptor_1 = __importDefault(require("./legacyCryptor")); +var aesCbcCryptor_1 = __importDefault(require("./aesCbcCryptor")); +var CryptoModule = /** @class */ (function () { + function CryptoModule(cryptoModuleConfiguration) { + var _a; + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; + } + //@ts-ignore: type detection issue with old Config type assignment + CryptoModule.legacyCryptoModule = function (_a) { + var config = _a.config; + return new this({ + default: new legacyCryptor_1.default({ config: config }), + cryptors: [new aesCbcCryptor_1.default(config.cipherKey)], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + return new this({ + default: new aesCbcCryptor_1.default(config.cipherKey), + cryptors: [new legacyCryptor_1.default({ config: config })], + }); + }; + 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) { + return __awaiter(this, void 0, void 0, function () { + var encrypted, header, headerData, pos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(data)]; + case 1: + encrypted = _a.sent(); + if (!encrypted.metadata) + return [2 /*return*/, encrypted.data]; + header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + headerData = new Uint8Array(header.length); + pos = 0; + headerData.set(header.data, pos); + pos += header.length; + if (encrypted.metadata) { + pos -= encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + } + return [2 /*return*/, this.concatArrayBuffer(headerData.buffer, encrypted.data)]; + } + }); + }); + }; + CryptoModule.prototype.decrypt = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + var header, cryptor, metadata; + return __generator(this, function (_a) { + header = CryptorHeader.tryParse(encryptedData); + cryptor = this.getCryptor(header); + metadata = header.length > 0 + ? encryptedData.slice(header.length - header.metadataLength, header.length) + : null; + //@ts-ignore: cryptor will be there or unreachable due to exception + return [2 /*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 _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on default cryptor) + */ + //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. + if (this.defaultCryptor.identifier === '') + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; + _b = (_a = File).create; + _c = { + name: file.name, + mimeType: 'application/octet-stream' + }; + return [4 /*yield*/, this.encrypt(file.data)]; + case 1: return [2 /*return*/, _b.apply(_a, [( + //@ts-ignore: can not infer that PubNubFile has data field + _c.data = _d.sent(), + _c)])]; + case 2: return [2 /*return*/]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var header, cryptor, _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; + 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) + */ + //@ts-ignore: cryptor will be there or unreachable due to exception + if (cryptor.identifier === CryptoModule.LEGACY_IDENTIFIER) + return [2 /*return*/, cryptor.decryptFile(file, File)]; + _b = (_a = File).create; + _c = { + name: file.name + }; + return [4 /*yield*/, this.decrypt(file.data)]; + case 1: return [2 /*return*/, _b.apply(_a, [( + //@ts-ignore: can not infer that PubNubFile has data field + _c.data = _d.sent(), + _c)])]; + case 2: 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'); + } + 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'); + }; + 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.LEGACY_IDENTIFIER = ''; + return CryptoModule; +}()); +exports.default = 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 (encryptedData) { + var sentinel = ''; + var version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) + return ''; + } + if (encryptedData.byteLength >= 5) { + version = encryptedData[4]; + } + else { + throw new endpoint_1.PubNubError('decryption error'); + } + if (version > CryptorHeader.MAX_VERSION) + throw new endpoint_1.PubNubError('unknown cryptor'); + var identifier = ''; + var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) { + identifier = encryptedData.slice(5, pos); + } + else { + throw new endpoint_1.PubNubError('decryption error'); + } + var headerSize = null; + if (encryptedData.byteLength > pos + 1) { + headerSize = encryptedData[pos]; + } + pos += 1; + if (headerSize === 255 && encryptedData.byteLength >= pos + 2) { + headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), headerSize); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.MAX_VERSION = 1; + 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 CryptorHeaderV1.VERSION; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "length", { + get: function () { + return (CryptorHeaderV1.SENTINEL.length + + 1 + + CryptorHeaderV1.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(CryptorHeaderV1.SENTINEL)); + pos += CryptorHeaderV1.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(encoder.encode(this.identifier), pos); + pos += CryptorHeaderV1.IDENTIFIER_LENGTH; + var metadata_size = this.metadataLength; + if (metadata_size < 255) { + header[pos] = metadata_size; + } + else { + header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + } + return header; + }, + enumerable: false, + configurable: true + }); + CryptorHeaderV1.IDENTIFIER_LENGTH = 4; + CryptorHeaderV1.SENTINEL = 'PNED'; + CryptorHeaderV1.VERSION = 1; + return CryptorHeaderV1; +}()); diff --git a/src/crypto/modules/NodeCryptoModule/ICryptor.ts b/src/crypto/modules/NodeCryptoModule/ICryptor.ts new file mode 100644 index 000000000..387f07042 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/ICryptor.ts @@ -0,0 +1,19 @@ +export type EncryptedDataType = { + data: Buffer; + metadata: Buffer | null; +}; + +export type EncryptedStream = { + stream: NodeJS.ReadableStream; + metadataLength: number; + metadata?: Buffer | undefined; +}; + +export interface ICryptor { + get identifier(): string; + encrypt(data: BufferSource): Promise; + decrypt(data: EncryptedDataType): Promise; + + 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..5dfe4c31e --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts @@ -0,0 +1,15 @@ +import { EncryptedDataType } from './ICryptor'; +import PubNubFile from '../../../file/modules/node'; + +export type PubnubFile = typeof PubNubFile; +export type ArrayBufferLike = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | DataView | BufferSource; + +export interface ILegacyCryptor { + get identifier(): string; + + encrypt(data: ArrayBufferLike): Promise; + decrypt(data: EncryptedDataType): Promise; + + encryptFile(file: T, File: T): Promise; + decryptFile(file: T, File: T): Promise; +} diff --git a/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js deleted file mode 100644 index fadc82fad..000000000 --- a/src/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ /dev/null @@ -1,301 +0,0 @@ -import { Readable, PassThrough, Transform } from 'stream'; -import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; -import LegacyCryptor from './legacyCryptor'; -import AesCbcCryptor from './aesCbcCryptor'; - -export default class CryptoModule { - defaultCryptor; - cryptors = []; - - constructor({ cryptoModuleConfiguration }) { - this.defaultCryptor = cryptoModuleConfiguration.default; - this.cryptors = [...this.defaultCryptor, ...cryptoModuleConfiguration.cryptors]; - } - - static legacyCryptoModule({ config }) { - return new this({ - default: new LegacyCryptor({ config }), - cryptors: [new AesCbcCryptor(config.cipherKey)], - }); - } - - static aesCbcCryptoModule({ config }) { - return new this({ - default: new AesCbcCryptor(config.cipherKey), - cryptors: [new LegacyCryptor({ config })], - }); - } - - async encrypt(data, encoding) { - let encrypted = this.default.encrypt(data); - - let header = CryptoHeader.from(this.default.identifier, encrypted.metadata); - - let payload = new Uint8Array(header.length); - let pos = 0; - payload.set(header.data, pos); - pos += header.length; - if (encrypted.metadata) { - pos -= encrypted.metadata.length; - payload.set(encrypted.metadata, pos); - } - if (encoding) { - return Buffer.concat([payload, encrypted.data]).toString(encoding); - } else { - return Buffer.concat([payload, encrypted.data]); - } - } - - async decrypt(data, encoding) { - let encryptedData = null; - if (encoding) { - encryptedData = Buffer.from(data, encoding); - } else { - encryptedData = Buffer.from(data); - } - let header = CryptoHeader.tryParse(encryptedData); - let cryptor = this._getCryptor(header); - - if (cryptor instanceof LegacyCryptor) return cryptor.decrypt(data); - - return cryptor.decrypt({ - data: encryptedData.slice(header.length), - metadata: encryptedData.slice(header.length - header.size, header.length), - }); - } - - async encryptFile(file, File) { - if (this.defaultCryptor instanceof LegacyCryptor) return this.defaultCryptor.encryptFile(file, File); - if (file.data instanceof Buffer) { - return File.create({ - name: file.name, - mimeType: 'application/octet-stream', - data: await this.encrypt(file.data), - }); - } - if (file.data instanceof Readable) { - let encryptedStream = this.defaultCryptor.encryptStream(file.data); - let header = CryptoHeader.from(this.default.identifier, encryptedStream.metadata); - - let 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.data.pipe(output); - return File.create({ - name: file.name, - mimeType: 'application/octet-stream', - stream: output, - }); - } - } - - async decryptFile(file, File) { - if (file.data instanceof Buffer) { - return File.create({ - name: file.name, - mimeType: 'application/octet-stream', - data: await this.encrypt(file.data), - }); - } - - if (file.data instanceof Readable) { - let stream = file.data; - return new Promise((resolve, _) => { - stream.on('readable', () => resolve(this._decryptStream(stream, file, File))); - }); - } - } - - async _decryptStream(stream, file, File) { - let magicBytes = stream.read(4); - if (magicBytes !== null) { - if (!CryptoHeader.isSentinel(magicBytes)) { - return this._legacyFileDecrypt(magicBytes, stream); - } - let versionByte = stream.read(1); - CryptoHeader.validateVersion(versionByte[0]); - let identifier = stream.read(4); - let cryptor = this._getCryptorFromId(CryptoHeader.tryGetIdentifier(identifier)); - let headerSize = CryptoHeader.tryGetMetadataSizeFromStream(stream); - return File.create({ - name: file.name, - mimeType: 'application/octet-stream', - data: await cryptor.decryptStream({ stream: stream, metadataLength: headerSize }), - }); - } - } - - async _legacyFileDecrypt(bytes, stream) { - const sourceStream = new PassThrough(); - sourceStream.write(bytes); - stream.pipe(sourceStream); - stream.pause(); - sourceStream.pause(); - return this.default.decryptFile( - File.create({ - name: file.name, - mimeType: 'application/octet-stream', - data: sourceStream, - }), - ); - } - - _getCryptor(header) { - if (header === null) { - return this.legacyCryptor; - } else if (header instanceof CryptoHeaderV1) { - return this._getCryptorFromId(header.identifier); - } - } - - _getCryptorFromId(id) { - const cryptor = this.cryptors.find((c) => id === c.identifier); - if (cryptor) { - return cryptor; - } - throw Error('No registered cryptor can decrypt the data.'); - } -} - -// CryptoHeader Utility -class CryptoHeader { - static SENTINEL = 'PNED'; - static IDENTIFIER_LENGTH = 4; - static MAX_VERSION = 1; - - static from(id, headerSize) { - return new CryptoHeaderV1(id, headerSize); - } - - static isSentinel(bytes) { - if (bytes && bytes.byteLength >= 4) { - if (bytes.toString('utf8') == CryptoHeader.SENTINEL) return true; - } - } - - static validateVersion(data) { - if (data && data > CryptoHeader.MAX_VERSION) throw Error('Decrypting data created by unknown cryptor.'); - return data; - } - - static tryGetIdentifier(data) { - if (data & (data.byteLength < 4)) { - throw Error('Decrypted data header is malformed.'); - } else { - return data.toString('utf8'); - } - } - - static tryGetMetadataSizeFromStream(stream) { - let sizeBuf = stream.read(1); - if (sizeBuf && sizeBuf[0] < 255) { - return sizeBuf[0]; - } - if (sizeBuf === 255) { - let nextBuf = stream(2); - if (nextBuf & (nextBuf.byteLength >= 2)) { - return new Uint16Array([nextBuf[0], nextBuf[1]]).reduce((acc, val) => (acc << 8) + val, 0); - } - } - } - static tryParse(encryptedData) { - let sentinel = ''; - let version = null; - if (encryptedData.length >= 4) { - sentinel = encryptedData.slice(0, 4); - if (sentinel.toString('utf8') !== CryptoHeader.SENTINEL) return null; - } - - if (encryptedData.length >= 5) { - version = encryptedData[4]; - } else { - throw Error('Decrypted data header is malformed.'); - } - if (version > CryptoHeader.MAX_VERSION) throw Error('Decrypting data created by unknown cryptor.'); - - let identifier = ''; - let pos = 5 + CryptoHeader.IDENTIFIER_LENGTH; - if (encryptedData.length >= pos) { - identifier = encryptedData.slice(5, pos); - } else { - throw Error('Decrypted data header is malformed.'); - } - let headerSize = null; - if (encryptedData.length > pos + 1) { - headerSize = encryptedData[pos]; - } - pos += 1; - if (headerSize === 255 && encryptedData.length >= pos + 2) { - headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce((acc, val) => (acc << 8) + val, 0); - pos += 2; - } - return new CryptoHeaderV1(identifier.toString('utf8'), encryptedData.slice(pos, pos + headerSize)); - } -} - -// v1 cryptoHeader -class CryptoHeaderV1 { - static IDENTIFIER_LENGTH = 4; - - static SENTINEL = 'PNED'; - static VERSION = 1; - - identifier; - metadata; - - constructor(id, metadata) { - this.identifier = id; - this.metadata = metadata; - } - - get identifier() { - return this.identifier; - } - - get metadata() { - return this.metadata; - } - - get version() { - return CryptoHeaderV1.VERSION; - } - - get length() { - return ( - CryptoHeaderV1.SENTINEL.length + - 1 + - CryptoHeaderV1.IDENTIFIER_LENGTH + - (this.metadata.length < 255 ? 1 : 3) + - this.metadata.length - ); - } - - get size() { - return this.metadata.length; - } - - get data() { - let pos = 0; - const header = new Uint8Array(this.length); - header.set(Buffer.from(CryptoHeaderV1.SENTINEL)); - pos += CryptoHeaderV1.SENTINEL.length; - header[pos] = this.version; - pos++; - if (this.identifier) header.set(Buffer.from(this.identifier), pos); - pos += CryptoHeaderV1.IDENTIFIER_LENGTH; - let metadata_size = this.metadata.length; - if (metadata_size < 255) { - header[pos] = metadata_size; - } else { - header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); - } - return header; - } -} diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js deleted file mode 100644 index ff24dff75..000000000 --- a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.js +++ /dev/null @@ -1,91 +0,0 @@ -import { Readable, PassThrough, Transform } from 'stream'; -import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; - -export default class AesCbcCryptor { - static BLOCK_SIZE = 16; - - constructor(key) { - this.cipherKey = key; - } - - 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(), 'utf8'); - } - - async encrypt(data) { - const iv = this._getIv(); - const key = this._getKey(); - - const bPlain = Buffer.from(data); - const aes = createCipheriv(this.algo, key, iv); - - return { - metadata: iv, - data: Buffer.concat([aes.update(bPlain), aes.final()]), - }; - } - - async decrypt(encryptedData) { - const aes = createDecipheriv(this.algo, this._getKey(), encryptedData.metadata); - return Buffer.concat([aes.update(encryptedData.data), aes.final()]); - } - - async encryptStream(stream) { - const output = new PassThrough(); - const bIv = this._getIv(); - const aes = createCipheriv(this.algo, this._getKey(), bIv); - stream.pipe(aes).pipe(output); - return { - data: output, - metadata: bIv, - metadataLength: AesCbcCryptor.BLOCK_SIZE, - }; - } - - async decryptStream(encryptedStream) { - const output = new PassThrough(); - - let bIv = Buffer.alloc(0); - let aes = null; - 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(output); - - aes.write(bChunk.slice(sliceLen)); - } - } - data = encryptedStream.stream.read(); - } - encryptedStream.stream.on('end', () => { - if (aes) { - aes.end(); - } - output.end(); - }); - return output; - } -} diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts new file mode 100644 index 000000000..b817a0812 --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts @@ -0,0 +1,92 @@ +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: number = 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()); + } + + async encrypt(data: Buffer) { + const iv = this.getIv(); + const key = this.getKey(); + + const bPlain = Buffer.from(data); + const aes = createCipheriv(this.algo, key, iv); + + return { + metadata: iv, + data: Buffer.concat([aes.update(bPlain), aes.final()]), + }; + } + + async decrypt(encryptedData: EncryptedDataType) { + const aes = createDecipheriv(this.algo, this.getKey(), encryptedData.metadata); + return Buffer.concat([aes.update(encryptedData.data), aes.final()]); + } + + async encryptStream(stream: NodeJS.ReadableStream) { + const output = new PassThrough(); + const bIv = this.getIv(); + 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.js b/src/crypto/modules/NodeCryptoModule/legacyCryptor.js deleted file mode 100644 index 48dd71cfd..000000000 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ /dev/null @@ -1,36 +0,0 @@ -import Crypto from '../../../core/components/cryptography/index'; -import FileCryptor from '../node'; - -export default class LegacyCryptor { - config; - cipherKey; - useRandomIVs; - - cryptor; - fileCryptor; - - constructor({ pnConfig }) { - this.config = pnConfig; - this.cryptor = new Crypto({ pnConfig }); - this.fileCryptor = new FileCryptor(); - } - - get identifier() { - return ''; - } - async encrypt(data) { - return this.cryptor.encrypt(data); - } - - async decrypt(encryptedData) { - return this.cryptor.decrypt(encryptedData); - } - - async encryptFile(file, File) { - return this.fileCryptor.encryptFile(this.config.cipherKey, file, File); - } - - async decryptFile(file, File) { - return this.fileCryptor.decryptFile(this.config.cipherKey, file, File); - } -} diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts new file mode 100644 index 000000000..c6a6f7f7d --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -0,0 +1,39 @@ +import Crypto from '../../../core/components/cryptography/index'; +import FileCryptor from '../node'; +import { EncryptedDataType } from './ICryptor'; +import { ILegacyCryptor, ArrayBufferLike, PubnubFile } 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 ''; + } + async encrypt(data: ArrayBufferLike) { + return { + data: this.cryptor.encrypt(data), + metadata: null, + }; + } + + async decrypt(encryptedData: EncryptedDataType) { + return this.cryptor.decrypt(encryptedData.data.toString()); + } + + async encryptFile(file: PubnubFile, File: PubnubFile) { + return this.fileCryptor.encryptFile(this.config.cipherKey, file, File); + } + + async decryptFile(file: PubnubFile, File: PubnubFile) { + 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..31d60d87d --- /dev/null +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -0,0 +1,347 @@ +import { Readable, PassThrough } from 'stream'; +import { PubNubError } from '../../../core/components/endpoint'; +import LegacyCryptor from './legacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; +import { ICryptor } from './ICryptor'; +import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; + +type CryptorType = ICryptor | ILegacyCryptor; + +type CryptoModuleConfiguration = { + default: CryptorType; + cryptors?: Array; +}; + +export default class CryptoModule { + static LEGACY_IDENTIFIER = ''; + + defaultCryptor: CryptorType; + cryptors: Array; + + constructor(cryptoModuleConfiguration: CryptoModuleConfiguration) { + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = cryptoModuleConfiguration.cryptors ?? []; + } + + //@ts-ignore: type detection issue with old Config type assignment + static legacyCryptoModule({ config }) { + return new this({ + default: new LegacyCryptor({ config }), + cryptors: [new AesCbcCryptor(config.cipherKey)], + }); + } + + static aesCbcCryptoModule(config: { cipherKey: { cipherKey: string } }) { + return new this({ + default: new AesCbcCryptor(config.cipherKey), + cryptors: [new LegacyCryptor({ config })], + }); + } + + static withDefaultCryptor(defaultCryptor: CryptorType) { + return new this({ default: defaultCryptor }); + } + + getAllCryptors() { + return [this.defaultCryptor, ...this.cryptors]; + } + + getLegacyCryptor() { + return this.getAllCryptors().find((c) => c.identifier === ''); + } + + async encrypt(data: Buffer) { + let encrypted = await this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) return encrypted.data; + + let header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + + let headerData = new Uint8Array(header!.length); + let pos = 0; + headerData.set(header!.data, pos); + pos += header!.length; + if (encrypted.metadata) { + pos -= encrypted.metadata.length; + headerData.set(encrypted.metadata, pos); + } + return Buffer.concat([headerData, encrypted.data]); + } + + async decrypt(data: Buffer) { + let encryptedData = null; + encryptedData = Buffer.from(data); + + let header = CryptorHeader.tryParse(encryptedData); + let cryptor = this.getCryptor(header); + let metadata = + header.length > 0 + ? encryptedData.slice(header.length - (header as CryptorHeaderV1).metadataLength, header.length) + : null; + return cryptor!.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + } + + async encryptFile(file: PubnubFile, File: PubnubFile) { + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on intsance type) + */ + if (this.defaultCryptor instanceof LegacyCryptor) return this.defaultCryptor.encryptFile(file, File); + //@ts-ignore: can not infer that PubNubFile has data field + if (file.data instanceof Buffer) { + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + //@ts-ignore: can not infer that PubNubFile has data field + data: await this.encrypt(file.data!), + }); + } + //@ts-ignore: can not infer that PubNubFile has data field + if (file.data instanceof Readable) { + //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. + let encryptedStream = this.defaultCryptor.encryptStream(file.data); + let header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); + + let 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.data.pipe(output); + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: output, + }); + } + } + + async decryptFile(file: any, File: PubnubFile) { + if (file?.data instanceof Buffer) { + let header = CryptorHeader.tryParse(file.data); + let cryptor = this.getCryptor(header); + /** + * If It's legacyone then redirect it. + * (as long as we support legacy need to check on instance type) + */ + //@ts-ignore: cryptor will be there or unreachable due to exception + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); + return File.create({ + name: file.name, + data: await this.decrypt(file?.data), + }); + } + + if (file.data instanceof Readable) { + let stream = file.data; + return new Promise((resolve) => { + stream.on('readable', () => resolve(this.onStreamReadable(stream, file, File))); + }); + } + } + + async onStreamReadable(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { + stream.removeAllListeners('readable'); + + let magicBytes = stream.read(4); + if (!CryptorHeader.isSentinel(magicBytes as Buffer)) { + stream.unshift(magicBytes); + return this.decryptLegacyFileStream(stream, file, File); + } + let versionByte = stream.read(1); + CryptorHeader.validateVersion(versionByte[0] as number); + let identifier = stream.read(4); + let cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier as Buffer)); + let headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream); + + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: await (cryptor as ICryptor).decryptStream({ stream: stream, metadataLength: headerSize as number }), + }); + } + + async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { + const cryptor = this.getLegacyCryptor(); + if (cryptor) { + //@ts-ignore: cryptor will be there or unreachable due to exception + return cryptor.decryptFile( + File.create({ + name: file.name, + stream: stream, + }), + File, + ); + } else { + throw new PubNubError('unknown cryptor'); + } + } + + getCryptor(header: CryptorHeader) { + if (header === '') { + const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); + if (cryptor) return cryptor; + throw new Error('unknown cryptor'); + } else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + } + + getCryptorFromId(id: string) { + const cryptor = this.getAllCryptors().find((c) => id === c.identifier); + if (cryptor) { + return cryptor; + } + throw Error('unknown cryptor'); + } +} + +// CryptorHeader Utility +class CryptorHeader { + static SENTINEL = 'PNED'; + static LEGACY_IDENTIFIER = ''; + static IDENTIFIER_LENGTH = 4; + static MAX_VERSION = 1; + + 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 PubNubError('decryption error'); + return data; + } + + static tryGetIdentifier(data: Buffer) { + if (data.byteLength < 4) { + throw new PubNubError('unknown cryptor'); + } else { + return data.toString('utf8'); + } + } + + static tryGetMetadataSizeFromStream(stream: NodeJS.ReadableStream) { + let sizeBuf = stream.read(1); + if (sizeBuf && (sizeBuf[0] as number) < 255) { + return sizeBuf[0] as number; + } + if ((sizeBuf[0] as number) === 255) { + let 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); + } + } + } + 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 PubNubError('decryption error'); + } + if (version > CryptorHeader.MAX_VERSION) throw new PubNubError('unknown cryptor'); + + let identifier: Buffer; + let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.length >= pos) { + identifier = encryptedData.slice(5, pos); + } else { + throw new PubNubError('decryption error'); + } + let headerSize = null; + if (encryptedData.length > pos + 1) { + headerSize = encryptedData[pos]; + } + pos += 1; + if (headerSize === 255 && encryptedData.length >= pos + 2) { + headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce((acc, val) => (acc << 8) + val, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), headerSize!); + } +} + +// v1 CryptorHeader +class CryptorHeaderV1 { + static IDENTIFIER_LENGTH = 4; + + static SENTINEL = 'PNED'; + static VERSION = 1; + + _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 CryptorHeaderV1.VERSION; + } + + get length() { + return ( + CryptorHeaderV1.SENTINEL.length + + 1 + + CryptorHeaderV1.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength + ); + } + + get data() { + let pos = 0; + const header = new Uint8Array(this.length); + header.set(Buffer.from(CryptorHeaderV1.SENTINEL)); + pos += CryptorHeaderV1.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) header.set(Buffer.from(this.identifier), pos); + pos += CryptorHeaderV1.IDENTIFIER_LENGTH; + let metadata_size = this.metadataLength; + if (metadata_size < 255) { + header[pos] = metadata_size; + } else { + header.set([255, metadata_size >> 8, metadata_size & 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..7d9ef08d5 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/ICryptor.ts @@ -0,0 +1,10 @@ +export type EncryptedDataType = { + data: ArrayBufferLike; + metadata: ArrayBufferLike | null; +}; + +export interface ICryptor { + get identifier(): string; + encrypt(data: BufferSource): Promise; + decrypt(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..608400162 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts @@ -0,0 +1,14 @@ +import { EncryptedDataType } from './ICryptor'; +import PubNubFile from '../../../file/modules/web'; + +export type PubnubFile = typeof PubNubFile; + +export interface ILegacyCryptor { + get identifier(): string; + + encrypt(data: ArrayBufferLike): Promise; + decrypt(data: EncryptedDataType): Promise; + + 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..03ef53b43 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -0,0 +1,51 @@ +import { ICryptor, EncryptedDataType } from './ICryptor'; + +export default class AesCbcCryptor implements ICryptor { + static BLOCK_SIZE = 16; + static encoder = new TextEncoder(); + static decoder = new TextDecoder(); + + cipherKey: string; + + constructor(configuration: { cipherKey: any }) { + this.cipherKey = configuration.cipherKey; + } + + get algo() { + return 'AES-CBC'; + } + + get identifier() { + return 'ACRH'; + } + + _getIv() { + return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); + } + + 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, 'AES-CBC', true, ['encrypt', 'decrypt']); + } + + async encrypt(data: BufferSource) { + const abIv = this._getIv(); + const key = await this._getKey(); + + return { + metadata: abIv, + data: await crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, data), + }; + } + + async decrypt(encryptedData: EncryptedDataType) { + const key = await this._getKey(); + const decryptedData = await crypto.subtle.decrypt( + { name: this.algo, iv: encryptedData.metadata! }, + key, + encryptedData.data, + ); + return decryptedData; + } +} diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts new file mode 100644 index 000000000..062398eec --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -0,0 +1,44 @@ +import Crypto from '../../../core/components/cryptography/index'; +import PubNubFile from '../../../file/modules/web'; +import FileCryptor from '../web'; +import { EncryptedDataType } from './ICryptor'; +import { ILegacyCryptor } from './ILegacyCryptor'; + +export type PubnubFile = typeof PubNubFile; + +export default class LegacyCryptor implements ILegacyCryptor { + config; + + cryptor; + fileCryptor; + + constructor(config: { config: any }) { + this.config = config; + this.cryptor = new Crypto({ config }); + this.fileCryptor = new FileCryptor(); + } + + get identifier() { + return ''; + } + async encrypt(data: ArrayBufferLike) { + return { + data: this.cryptor.encrypt(data) as ArrayBuffer, + metadata: null, + }; + } + + async decrypt(encryptedData: EncryptedDataType) { + return this.cryptor.decrypt(encryptedData.data); + } + + async encryptFile(file: PubnubFile, File: PubnubFile) { + //@ts-ignore: can not detect cipherKey from old Config + return this.fileCryptor.encryptFile(this.config?.cipherKey, file, File); + } + + async decryptFile(file: PubnubFile, File: PubnubFile) { + //@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..3bba4dd37 --- /dev/null +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -0,0 +1,254 @@ +import { PubNubError } from '../../../core/components/endpoint'; +import LegacyCryptor from './legacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; +import { ICryptor } from './ICryptor'; +import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; + +type CryptorType = ICryptor | ILegacyCryptor; + +type CryptoModuleConfiguration = { + default: CryptorType; + cryptors?: Array; +}; + +export default class CryptoModule { + static LEGACY_IDENTIFIER = ''; + defaultCryptor: CryptorType; + cryptors: Array; + + constructor(cryptoModuleConfiguration: CryptoModuleConfiguration) { + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = cryptoModuleConfiguration.cryptors ?? []; + } + + //@ts-ignore: type detection issue with old Config type assignment + static legacyCryptoModule({ config }) { + return new this({ + default: new LegacyCryptor({ config }), + cryptors: [new AesCbcCryptor(config.cipherKey)], + }); + } + + static aesCbcCryptoModule(config: { cipherKey: { cipherKey: any } }) { + return new this({ + default: new AesCbcCryptor(config.cipherKey), + cryptors: [new LegacyCryptor({ config })], + }); + } + + static withDefaultCryptor(defaultCryptor: CryptorType) { + return new this({ default: defaultCryptor }); + } + + getAllCryptors() { + return [this.defaultCryptor, ...this.cryptors]; + } + + async encrypt(data: ArrayBuffer) { + let encrypted = await this.defaultCryptor.encrypt(data); + if (!encrypted.metadata) return encrypted.data; + + let header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + + let headerData = new Uint8Array((header as CryptorHeaderV1).length); + let pos = 0; + headerData.set((header as CryptorHeaderV1).data, pos); + pos += (header as CryptorHeaderV1).length; + if (encrypted.metadata) { + pos -= encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + } + return this.concatArrayBuffer(headerData.buffer, encrypted.data); + } + + async decrypt(encryptedData: ArrayBuffer) { + let header = CryptorHeader.tryParse(encryptedData); + let cryptor = this.getCryptor(header); + let metadata = + header.length > 0 + ? encryptedData.slice(header.length - (header as CryptorHeaderV1).metadataLength, header.length) + : null; + //@ts-ignore: cryptor will be there or unreachable due to exception + return cryptor.decrypt({ + data: encryptedData.slice(header.length), + metadata: metadata, + }); + } + + async encryptFile(file: PubnubFile, File: PubnubFile) { + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on default cryptor) + */ + //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. + if (this.defaultCryptor.identifier === '') return this.defaultCryptor.encryptFile(file, File); + //@ts-ignore: can not infer that PubNubFile has data field + if (file.data instanceof Buffer) { + return File.create({ + name: file.name, + mimeType: 'application/octet-stream', + //@ts-ignore: can not infer that PubNubFile has data field + data: await this.encrypt(file.data), + }); + } + } + + async decryptFile(file: PubnubFile, File: PubnubFile) { + //@ts-ignore: can not infer that PubNubFile has data field + if (file.data instanceof Buffer) { + //@ts-ignore: can not infer that PubNubFile has data field + let header = CryptorHeader.tryParse(file.data); + let cryptor = this.getCryptor(header); + /** + * If It's legacyone then redirect it. + * (as long as we support legacy need to check on instance type) + */ + //@ts-ignore: cryptor will be there or unreachable due to exception + if (cryptor.identifier === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); + return File.create({ + name: file.name, + //@ts-ignore: can not infer that PubNubFile has data field + data: await this.decrypt(file.data), + }); + } + } + + getCryptor(header: string | CryptorHeaderV1) { + if (header === '') { + const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); + if (cryptor) return cryptor; + throw new Error('unknown cryptor'); + } else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + } + + getCryptorFromId(id: string) { + const cryptor = this.getAllCryptors().find((c) => id === c.identifier); + if (cryptor) { + return cryptor; + } + throw Error('unknown cryptor'); + } + + 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; + } +} + +// CryptorHeader Utility +class CryptorHeader { + static SENTINEL = 'PNED'; + static LEGACY_IDENTIFIER = ''; + static IDENTIFIER_LENGTH = 4; + static MAX_VERSION = 1; + + static from(id: string, metadata: ArrayBuffer) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) return; + return new CryptorHeaderV1(id, metadata.byteLength); + } + + static tryParse(encryptedData: ArrayBuffer) { + let sentinel: any = ''; + let version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) return ''; + } + + if (encryptedData.byteLength >= 5) { + version = (encryptedData as Uint8Array)[4] as number; + } else { + throw new PubNubError('decryption error'); + } + if (version > CryptorHeader.MAX_VERSION) throw new PubNubError('unknown cryptor'); + + let identifier: any = ''; + let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) { + identifier = encryptedData.slice(5, pos); + } else { + throw new PubNubError('decryption error'); + } + let headerSize = null; + if (encryptedData.byteLength > pos + 1) { + headerSize = (encryptedData as Uint8Array)[pos]; + } + pos += 1; + if (headerSize === 255 && encryptedData.byteLength >= pos + 2) { + headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce((acc, val) => (acc << 8) + val, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), headerSize!); + } +} + +// v1 CryptorHeader +class CryptorHeaderV1 { + static IDENTIFIER_LENGTH = 4; + + static SENTINEL = 'PNED'; + static VERSION = 1; + + _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 CryptorHeaderV1.VERSION; + } + + get length() { + return ( + CryptorHeaderV1.SENTINEL.length + + 1 + + CryptorHeaderV1.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(CryptorHeaderV1.SENTINEL)); + pos += CryptorHeaderV1.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) header.set(encoder.encode(this.identifier), pos); + pos += CryptorHeaderV1.IDENTIFIER_LENGTH; + let metadata_size = this.metadataLength; + if (metadata_size < 255) { + header[pos] = metadata_size; + } else { + header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + } + return header; + } +} diff --git a/src/crypto/modules/node.js b/src/crypto/modules/node.js index d198daba1..bf63cc427 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 { diff --git a/src/crypto/modules/web.js b/src/crypto/modules/web.js index 6940db0b7..44e419f4d 100644 --- a/src/crypto/modules/web.js +++ b/src/crypto/modules/web.js @@ -9,8 +9,22 @@ function concatArrayBuffer(ab1, ab2) { return tmp.buffer; } +function ab2hex(ab) { + return [...new Uint8Array(ab)].map((x) => x.toString(16).padStart(2, '0')).join(''); +} + +function hex2ab(hex) { + return new Uint8Array( + hex.match(/[\da-f]{2}/gi).map(function (h) { + return parseInt(h, 16); + }), + ); +} + export default class WebCryptography { static IV_LENGTH = 16; + static encoder = new TextEncoder(); + static decoder = new TextDecoder(); get algo() { return 'aes-256-cbc'; @@ -68,10 +82,10 @@ export default class WebCryptography { } async getKey(key) { - const bKey = Buffer.from(key); + const bKey = WebCryptography.encoder.encode(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 abKey = hex2ab(ab2hex(abHash).slice(0, 32)).buffer; return crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt']); } @@ -85,27 +99,28 @@ 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)); + const data = await crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16)); + 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); } } From 28b57775df70d819eaca9b5722253fee6bb24ba1 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:20:51 +0530 Subject: [PATCH 07/38] step definitions for contract tests --- .../steps/cryptoModule/cryptoModule.ts | 162 ++++++++++++++++++ test/contract/utils.ts | 4 + test/contract/world.ts | 5 +- 3 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 test/contract/steps/cryptoModule/cryptoModule.ts diff --git a/test/contract/steps/cryptoModule/cryptoModule.ts b/test/contract/steps/cryptoModule/cryptoModule.ts new file mode 100644 index 000000000..8a8f37785 --- /dev/null +++ b/test/contract/steps/cryptoModule/cryptoModule.ts @@ -0,0 +1,162 @@ +import { Given, When, Then, Before, After } from '@cucumber/cucumber'; +import { expect } from 'chai'; +import { Blob } from 'buffer'; +import fs from 'fs'; + +import CryptoModule from '../../../../lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js'; +import AesCbcCryptor from '../../../../lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js'; +import LegacyCryptor from '../../../../lib/crypto/modules/NodeCryptoModule/legacyCryptor.js'; + +Before(function () { + this.grantPayload = {}; + 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; +}); + +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) { + this._initCryptor = (id: string) => { + return id === 'legacy' + ? new LegacyCryptor({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }) + : new AesCbcCryptor({ cipherKey: this.cipherKey }); + }; + + 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)), + }); + this.binaryFileResult = await this.cryptoModule.decryptFile(encrypteFile, pubnub.File); + } else if (format === 'stream') { + this.isStream = true; + const filestream = fs.createReadStream(this.getFilePath(fileName)); + this.file = pubnub.File.create({ + name: fileName, + stream: filestream, + }); + this.streamFileResult = await this.cryptoModule.decryptFile(this.file, pubnub.File); + } +}); + +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}', function (result: string) { + if (result === 'success') { + expect(this.errorMessage).to.be.undefined; + } else { + expect(result).to.have.string(this.errorMessage); + } +}); + +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.encryptedFile = await this.cryptoModule.encryptFile(this.file, this.pubnub.File); +}); + +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/contract/utils.ts b/test/contract/utils.ts index 2337b4d8e..5e0e9ccd3 100644 --- a/test/contract/utils.ts +++ b/test/contract/utils.ts @@ -7,3 +7,7 @@ export function loadFixtureFile(persona) { ); return JSON.parse(fileData); } + +export function getFilePath(filename) { + return `${process.cwd()}/dist/contract/contract/features/encryption/assets/${filename}`; +} diff --git a/test/contract/world.ts b/test/contract/world.ts index 08e8bd1c3..41227b598 100644 --- a/test/contract/world.ts +++ b/test/contract/world.ts @@ -4,7 +4,7 @@ import { 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 { @@ -134,6 +134,9 @@ class PubnubWorld extends World{ } return this.fileFixtures[name]; } + getFilePath(filename) { + return getFilePath(filename); + } } setWorldConstructor(PubnubWorld); From 5d43f199554c7baad93db81c1a8b16f3587f6db7 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:21:07 +0530 Subject: [PATCH 08/38] lib files --- dist/web/pubnub.js | 34 +- dist/web/pubnub.min.js | 4 +- .../modules/NodeCryptoModule/ICryptor.js | 2 + .../NodeCryptoModule/ILegacyCryptor.js | 2 + .../NodeCryptoModule/NodeCryptoModule.js | 453 ++++++++++++++++++ .../modules/NodeCryptoModule/aesCbcCryptor.js | 148 ++++++ .../modules/NodeCryptoModule/legacyCryptor.js | 91 ++++ .../modules/WebCryptoModule/ICryptor.js | 2 + .../modules/WebCryptoModule/ILegacyCryptor.js | 2 + .../modules/WebCryptoModule/aesCbcCryptor.js | 117 +++++ .../modules/WebCryptoModule/legacyCryptor.js | 93 ++++ lib/crypto/modules/node.js | 26 +- lib/crypto/modules/web.js | 59 ++- 13 files changed, 1007 insertions(+), 26 deletions(-) create mode 100644 lib/crypto/modules/NodeCryptoModule/ICryptor.js create mode 100644 lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js create mode 100644 lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js create mode 100644 lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js create mode 100644 lib/crypto/modules/NodeCryptoModule/legacyCryptor.js create mode 100644 lib/crypto/modules/WebCryptoModule/ICryptor.js create mode 100644 lib/crypto/modules/WebCryptoModule/ILegacyCryptor.js create mode 100644 lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js create mode 100644 lib/crypto/modules/WebCryptoModule/legacyCryptor.js diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 18ecabe18..476b332b6 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -12481,6 +12481,14 @@ tmp.set(new Uint8Array(ab2), ab1.byteLength); return tmp.buffer; } + function ab2hex(ab) { + return __spreadArray([], __read(new Uint8Array(ab)), false).map(function (x) { return x.toString(16).padStart(2, '0'); }).join(''); + } + function hex2ab(hex) { + return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { + return parseInt(h, 16); + })); + } var WebCryptography = /** @class */ (function () { function WebCryptography() { } @@ -12580,11 +12588,11 @@ return __generator(this, function (_a) { switch (_a.label) { case 0: - bKey = Buffer.from(key); + bKey = WebCryptography.encoder.encode(key); return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; case 1: abHash = _a.sent(); - abKey = Buffer.from(Buffer.from(abHash).toString('hex').slice(0, 32), 'utf8').buffer; + abKey = hex2ab(ab2hex(abHash).slice(0, 32)).buffer; return [2 /*return*/, crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt'])]; } }); @@ -12607,10 +12615,16 @@ }; 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); + return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16))]; + case 1: + data = _a.sent(); + return [2 /*return*/, data]; + } }); }); }; @@ -12621,12 +12635,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)]; } }); }); @@ -12637,18 +12651,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; }()); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 87695308a..51f1d8024 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&&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(),m=b>>5,v=31&b;if(7===m)switch(v){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(v))<0&&(m<2||6=0;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}return c(f);case 3:var w=[];if(f<0)for(;(f=y(m))>=0;)g(w,f);else g(w,f);return String.fromCharCode.apply(null,w);case 4:var k;if(f<0)for(k=[];!h();)k.push(e());else for(k=new Array(f),o=0;o0&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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 k;if(f<0)for(k=[];!h();)k.push(e());else for(k=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.3.3"},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}var m,v,_,O,S,P=P||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),v=(m=P).enc.Utf8,m.algo.HMAC=m.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=v.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=P,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],m=e[i+10],v=e[i+11],_=e[i+12],O=e[i+13],S=e[i+14],P=e[i+15],w=t(w=a[0],E=a[1],T=a[2],k=a[3],u,7,c[0]),k=t(k,w,E,T,s,12,c[1]),T=t(T,k,w,E,l,17,c[2]),E=t(E,T,k,w,p,22,c[3]);w=t(w,E,T,k,f,7,c[4]),k=t(k,w,E,T,h,12,c[5]),T=t(T,k,w,E,d,17,c[6]),E=t(E,T,k,w,y,22,c[7]),w=t(w,E,T,k,g,7,c[8]),k=t(k,w,E,T,b,12,c[9]),T=t(T,k,w,E,m,17,c[10]),E=t(E,T,k,w,v,22,c[11]),w=t(w,E,T,k,_,7,c[12]),k=t(k,w,E,T,O,12,c[13]),T=t(T,k,w,E,S,17,c[14]),w=n(w,E=t(E,T,k,w,P,22,c[15]),T,k,s,5,c[16]),k=n(k,w,E,T,d,9,c[17]),T=n(T,k,w,E,v,14,c[18]),E=n(E,T,k,w,u,20,c[19]),w=n(w,E,T,k,h,5,c[20]),k=n(k,w,E,T,m,9,c[21]),T=n(T,k,w,E,P,14,c[22]),E=n(E,T,k,w,f,20,c[23]),w=n(w,E,T,k,b,5,c[24]),k=n(k,w,E,T,S,9,c[25]),T=n(T,k,w,E,p,14,c[26]),E=n(E,T,k,w,g,20,c[27]),w=n(w,E,T,k,O,5,c[28]),k=n(k,w,E,T,l,9,c[29]),T=n(T,k,w,E,y,14,c[30]),w=r(w,E=n(E,T,k,w,_,20,c[31]),T,k,h,4,c[32]),k=r(k,w,E,T,g,11,c[33]),T=r(T,k,w,E,v,16,c[34]),E=r(E,T,k,w,S,23,c[35]),w=r(w,E,T,k,s,4,c[36]),k=r(k,w,E,T,f,11,c[37]),T=r(T,k,w,E,y,16,c[38]),E=r(E,T,k,w,m,23,c[39]),w=r(w,E,T,k,O,4,c[40]),k=r(k,w,E,T,u,11,c[41]),T=r(T,k,w,E,p,16,c[42]),E=r(E,T,k,w,d,23,c[43]),w=r(w,E,T,k,b,4,c[44]),k=r(k,w,E,T,_,11,c[45]),T=r(T,k,w,E,P,16,c[46]),w=o(w,E=r(E,T,k,w,l,23,c[47]),T,k,u,6,c[48]),k=o(k,w,E,T,y,10,c[49]),T=o(T,k,w,E,S,15,c[50]),E=o(E,T,k,w,h,21,c[51]),w=o(w,E,T,k,_,6,c[52]),k=o(k,w,E,T,p,10,c[53]),T=o(T,k,w,E,m,15,c[54]),E=o(E,T,k,w,s,21,c[55]),w=o(w,E,T,k,g,6,c[56]),k=o(k,w,E,T,P,10,c[57]),T=o(T,k,w,E,d,15,c[58]),E=o(E,T,k,w,O,21,c[59]),w=o(w,E,T,k,f,6,c[60]),k=o(k,w,E,T,v,10,c[61]),T=o(T,k,w,E,l,15,c[62]),E=o(E,T,k,w,b,21,c[63]);a[0]=a[0]+w|0,a[1]=a[1]+E|0,a[2]=a[2]+T|0,a[3]=a[3]+k|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=P,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=P,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 m=h[y],v=h[m],_=h[v],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*v^257*m^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=m^h[h[h[_^m]]],g^=h[h[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),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^=S[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)}(),P.mode.ECB=((S=P.lib.BlockCipherMode.extend()).Encryptor=S.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),S.Decryptor=S.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),S);var w=P;function k(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 N(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function C(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var j={signPamFromParams:function(e){return C(e).map((function(t){return"".concat(t,"=").concat(N(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:N},M={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory"},R=function(){function e(e){var t=e.subscribeEndpoint,n=e.leaveEndpoint,r=e.heartbeatEndpoint,o=e.setStateEndpoint,i=e.timeEndpoint,a=e.getFileUrl,s=e.config,u=e.crypto,c=e.listenerManager;this._listenerManager=c,this._config=s,this._leaveEndpoint=n,this._heartbeatEndpoint=r,this._setStateEndpoint=o,this._subscribeEndpoint=t,this._getFileUrl=a,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 E({timeEndpoint:i}),this._dedupingManager=new A({config:s})}return e.prototype.adaptStateChange=function(e,t){var n=this,r=e.state,o=e.channels,i=void 0===o?[]:o,a=e.channelGroups,s=void 0===a?[]:a,u=e.withHeartbeat,c=void 0!==u&&u;if(i.forEach((function(e){e in n._channels&&(n._channels[e].state=r)})),s.forEach((function(e){e in n._channelGroups&&(n._channelGroups[e].state=r)})),c){var l={};return i.forEach((function(e){return l[e]=r})),s.forEach((function(e){return l[e]=r})),this._heartbeatEndpoint({channels:i,channelGroups:s,state:l},t)}return this._setStateEndpoint({state:r,channels:i,channelGroups:s},t)},e.prototype.adaptPresenceChange=function(e){var t=this,n=e.connected,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i;n?(o.forEach((function(e){t._heartbeatChannels[e]={state:{}}})),a.forEach((function(e){t._heartbeatChannelGroups[e]={state:{}}}))):(o.forEach((function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]})),a.forEach((function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]})),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:o,channelGroups:a},(function(e){t._listenerManager.announceStatus(e)}))),this.reconnect()},e.prototype.adaptSubscribeChange=function(e){var t=this,n=e.timetoken,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i,s=e.withPresence,u=void 0!==s&&s,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),o.forEach((function(e){t._channels[e]={state:{}},u&&(t._presenceChannels[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannels[e]={}),t._pendingChannelSubscriptions.push(e)})),a.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,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i,s=[],u=[];o.forEach((function(e){e in n._channels&&(delete n._channels[e],s.push(e),e in n._heartbeatChannels&&delete n._heartbeatChannels[e]),e in n._presenceChannels&&(delete n._presenceChannels[e],s.push(e))})),a.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===s.length&&0===u.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:s,channelGroups:u},(function(e){e.affectedChannels=s,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 o=e._channels[r].state;Object.keys(o).length&&(t[r]=o),n.push(r)})),Object.keys(this._presenceChannels).forEach((function(e){n.push("".concat(e,"-pnpres"))})),Object.keys(this._channelGroups).forEach((function(n){var o=e._channelGroups[n].state;Object.keys(o).length&&(t[n]=o),r.push(n)})),Object.keys(this._presenceChannelGroups).forEach((function(e){r.push("".concat(e,"-pnpres"))})),0!==n.length||0!==r.length){var o={channels:n,channelGroups:r,state:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(o,this._processSubscribeResponse.bind(this))}},e.prototype._processSubscribeResponse=function(e,t){var o=this;if(e.error){if(e.errorData&&"Aborted"===e.errorData.message)return;e.category===M.PNTimeoutCategory?this._startSubscribeLoop():e.category===M.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection((function(){o._config.autoNetworkDetection&&!o._isOnline&&(o._isOnline=!0,o._listenerManager.announceNetworkUp()),o.reconnect(),o._subscriptionStatusAnnounced=!0;var t={category:M.PNReconnectedCategory,operation:e.operation,lastTimetoken:o._lastTimetoken,currentTimetoken:o._currentTimetoken};o._listenerManager.announceStatus(t)})),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===M.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 i={};i.category=M.PNConnectedCategory,i.operation=e.operation,i.affectedChannels=this._pendingChannelSubscriptions,i.subscribedChannels=this.getSubscribedChannels(),i.affectedChannelGroups=this._pendingChannelGroupSubscriptions,i.lastTimetoken=this._lastTimetoken,i.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(i),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var a=t.messages||[],s=this._config,u=s.requestMessageCountThreshold,c=s.dedupeOnSubscribe;if(u&&a.length>=u){var l={};l.category=M.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(j.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._config.cipherKey){var d=o._crypto.decrypt(e.payload);"object"==typeof d&&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;(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._config.cipherKey?y.message=o._crypto.decrypt(e.payload):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}(),U={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!==U.PNSubscribeOperation&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(e!==U.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 U.PNPublishOperation:t="pub";break;case U.PNSignalOperation:t="sig";break;case U.PNHistoryOperation:case U.PNFetchMessagesOperation:case U.PNDeleteMessagesOperation:case U.PNMessageCounts:t="hist";break;case U.PNUnsubscribeOperation:case U.PNWhereNowOperation:case U.PNHereNowOperation:case U.PNHeartbeatOperation:case U.PNSetStateOperation:case U.PNGetStateOperation:t="pres";break;case U.PNAddChannelsToGroupOperation:case U.PNRemoveChannelsFromGroupOperation:case U.PNChannelGroupsOperation:case U.PNRemoveGroupOperation:case U.PNChannelsForGroupOperation:t="cg";break;case U.PNPushNotificationEnabledChannelsOperation:case U.PNRemoveAllPushNotificationsOperation:t="push";break;case U.PNCreateUserOperation:case U.PNUpdateUserOperation:case U.PNDeleteUserOperation:case U.PNGetUserOperation:case U.PNGetUsersOperation:case U.PNCreateSpaceOperation:case U.PNUpdateSpaceOperation:case U.PNDeleteSpaceOperation:case U.PNGetSpaceOperation:case U.PNGetSpacesOperation:case U.PNGetMembersOperation:case U.PNUpdateMembersOperation:case U.PNGetMembershipsOperation:case U.PNUpdateMembershipsOperation:t="obj";break;case U.PNAddMessageActionOperation:case U.PNRemoveMessageActionOperation:case U.PNGetMessageActionsOperation:t="msga";break;case U.PNAccessManagerGrant:case U.PNAccessManagerAudit:t="pam";break;case U.PNAccessManagerGrantToken:case U.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),I=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,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}(I),F=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}(I),G=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}(I),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 F(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 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}(),L=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=M.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=M.PNNetworkDownCategory,this.announceStatus(e)},e}(),B=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}(),H=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 q(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}function z(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 V(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 W(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=W(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(j.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 J(e,t){for(var r=[],o=2;o0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.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 ae=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 se=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 ue=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 ce=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(i),"/uuid/").concat(j.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 le=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 pe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 fe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 he=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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}}),de={getOperation:function(){return U.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(j.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}}},ye={getOperation:function(){return U.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(j.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}}},ge={getOperation:function(){return U.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=e.crypto,r=e.config,o=JSON.stringify(t);return r.cipherKey&&(o=n.encrypt(o),o=JSON.stringify(o)),o||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(j.encodeString(t.channel),"/0/").concat(j.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]}}},be=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,m,v,_,O,S,P,w,k,T,E,A,N,C,j,M,R,U,x,I,D,F,G,K,L;return i(this,(function(i){switch(i.label){case 0:if(!a)throw new H("Validation failed, check status for details",q("channel can't be empty"));if(!p)throw new H("Validation failed, check status for details",q("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,m=o.form_fields,v=t.data,_=v.id,O=v.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=m,e.mimeType&&(S=m.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(k=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,k.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(A=(E=l).POSTFILE,N=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,A.apply(E,N.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,x=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,x.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(I=i.sent()).response&&"string"==typeof I.response.text?(D=I.response.text,F=/(.*)<\/Message>/gi.exec(D),new H(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",I)):new H("Upload to bucket failed.",I);case 19:if(204!==P.status)throw new H("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,K=!1,L={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return L=i.sent(),K=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!K&&G>0)return[3,20];i.label=24;case 24:if(K)return[2,{timetoken:L.timetoken,id:_,name:O}];throw new H("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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 H("Validation failed, check status for details",q("channel can't be empty"));if(!r)throw new H("Validation failed, check status for details",q("file id can't be empty"));if(!o)throw new H("Validation failed, check status for details",q("file name can't be empty"));var u="/v1/files/".concat(i.subscribeKey,"/channels/").concat(j.encodeString(n),"/files/").concat(r,"/").concat(o),c={};c.uuid=i.getUUID(),c.pnsdk=V(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)},ve={getOperation:function(){return U.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(j.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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},_e={getOperation:function(){return U.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(j.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 U.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}}},Se={getOperation:function(){return U.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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}}},Pe={getOperation:function(){return U.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(j.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}}},we={getOperation:function(){return U.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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}}},ke={getOperation:function(){return U.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}}},Te={getOperation:function(){return U.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(j.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}}},Ee={getOperation:function(){return U.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(j.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}}},Ae={getOperation:function(){return U.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(j.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}}},Ne={getOperation:function(){return U.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(j.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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Ce={getOperation:function(){return U.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(j.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}}},je={getOperation:function(){return U.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Me={getOperation:function(){return U.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(j.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 Re=Object.freeze({__proto__:null,getOperation:function(){return U.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 Ue=Object.freeze({__proto__:null,getOperation:function(){return U.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,m=void 0!==b&&b,v=t.update,_=void 0!==v&&v,O=t.authKeys,S=void 0===O?[]:O,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=m?"1":"0",w.u=_?"1":"0",r.length>0&&(w.channel=r.join(",")),i.length>0&&(w["channel-group"]=i.join(",")),S.length>0&&(w.auth=S.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 Ie(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(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]=Ie(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Ie(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Ie(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]=Ie(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Ie(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Ie(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]=Ie(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Ie(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Ie(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]=Ie(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Ie(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Ie(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Fe=Object.freeze({__proto__:null,getOperation:function(){return U.PNAccessManagerGrantToken},extractPermissions:Ie,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 De(0,t)},handleResponse:function(e,t){return t.data.token}}),Ge={getOperation:function(){return U.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(j.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,o=JSON.stringify(t);return r.cipherKey&&(o=n.encrypt(o),o=JSON.stringify(o)),o}var Le=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(r),"/0/").concat(j.encodeString(o))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(j.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 Be=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(o),"/0/").concat(j.encodeString(a))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});function He(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}var qe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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={timetoken:t.timetoken,entry:He(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var ze=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 U.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(j.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 U.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(j.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={};o.channel=r,o.timetoken=t.timetoken,o.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),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=Object.freeze({__proto__:null,getOperation:function(){return U.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 Je=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 U.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(j.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 U.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(j.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 m=this.currentContext;this.currentContext=f,this.notify({type:"transitionDone",fromState:b,fromContext:m,toState:p,toContext:f,event:e});try{for(var v=a(h),_=v.next();!_.done;_=v.next()){g=_.value;this.notify({type:"invocationDispatched",invocation:g})}}catch(e){r={error:e}}finally{try{_&&!_.done&&(o=v.return)&&o.call(v)}finally{if(r)throw r.error}}try{for(var O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}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(Nt())];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(Et(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof H?[2,t.transition(At(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(Ot(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof H?[2,t.transition(St(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(mt.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(mt.type,(function(e){return Dt.with(n({},e))}));var xt=new Ze("RECEIVE_FAILURE");xt.on(Ct.type,(function(e){return It.with(n(n({},e),{attempts:0}))})),xt.on(bt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var It=new Ze("RECEIVE_RECONNECTING");It.onEnter((function(e){return dt(e)})),It.onExit((function(){return dt.cancel})),It.on(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),It.on(At.type,(function(e,t){return It.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),It.on(Nt.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),It.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(kt.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?Kt.with(void 0):Dt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Dt.on(Tt.type,(function(e,t){return It.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(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),Ft.on(At.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(Nt.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?Kt.with(void 0):Gt.with({channels:t.payload.channels,groups:t.payload.groups})})),Gt.on(vt.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 Kt=new Ze("UNSUBSCRIBED");Kt.on(gt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Lt=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(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=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(mt())},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 T({config:i}),c=e.cryptography;r.init(i);var l=new B(i,o);this._tokenManager=l;var p=new x({maximumSamplesCount:6e4});this._telemetryManager=p;var f={config:i,networking:r,crypto:a,cryptography:c,tokenManager:l,telemetryManager:p,PubNubFile:e.PubNubFile};this.File=e.PubNubFile,this.encryptFile=function(e,n){return c.encryptFile(e,n,t.File)},this.decryptFile=function(e,n){return c.decryptFile(e,n,t.File)};var h=J.bind(this,f,$e),d=J.bind(this,f,ie),y=J.bind(this,f,se),b=J.bind(this,f,ce),m=J.bind(this,f,Je),v=new L;if(this._listenerManager=v,this.iAmHere=J.bind(this,f,se),this.iAmAway=J.bind(this,f,ie),this.setPresenceState=J.bind(this,f,ce),this.handshake=J.bind(this,f,Qe),this.receiveMessages=J.bind(this,f,Xe),!0===i.enableSubscribeBeta){var _=new Lt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=_.subscribe.bind(_),this.unsubscribe=_.unsubscribe.bind(_),this.eventEngine=_}else{var O=new R({timeEndpoint:h,leaveEndpoint:d,heartbeatEndpoint:y,setStateEndpoint:b,subscribeEndpoint:m,crypto:f.crypto,config:f.config,listenerManager:v,getFileUrl:function(e){return me(f,e)}});this.subscribe=O.adaptSubscribeChange.bind(O),this.unsubscribe=O.adaptUnsubscribeChange.bind(O),this.disconnect=O.disconnect.bind(O),this.reconnect=O.reconnect.bind(O),this.unsubscribeAll=O.unsubscribeAll.bind(O),this.getSubscribedChannels=O.getSubscribedChannels.bind(O),this.getSubscribedChannelGroups=O.getSubscribedChannelGroups.bind(O),this.setState=O.adaptStateChange.bind(O),this.presence=O.adaptPresenceChange.bind(O),this.destroy=function(e){O.unsubscribeAll(e),O.disconnect()}}this.addListener=v.addListener.bind(v),this.removeListener=v.removeListener.bind(v),this.removeAllListeners=v.removeAllListeners.bind(v),this.parseToken=l.parseToken.bind(l),this.setToken=l.setToken.bind(l),this.getToken=l.getToken.bind(l),this.channelGroups={listGroups:J.bind(this,f,Z),listChannels:J.bind(this,f,ee),addChannels:J.bind(this,f,Q),removeChannels:J.bind(this,f,X),deleteGroup:J.bind(this,f,Y)},this.push={addChannels:J.bind(this,f,te),removeChannels:J.bind(this,f,ne),deleteDevice:J.bind(this,f,oe),listChannels:J.bind(this,f,re)},this.hereNow=J.bind(this,f,le),this.whereNow=J.bind(this,f,ae),this.getState=J.bind(this,f,ue),this.grant=J.bind(this,f,Ue),this.grantToken=J.bind(this,f,Fe),this.audit=J.bind(this,f,Re),this.revokeToken=J.bind(this,f,Ge),this.publish=J.bind(this,f,Le),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=J.bind(this,f,Be),this.history=J.bind(this,f,qe),this.deleteMessages=J.bind(this,f,ze),this.messageCounts=J.bind(this,f,Ve),this.fetchMessages=J.bind(this,f,We),this.addMessageAction=J.bind(this,f,pe),this.removeMessageAction=J.bind(this,f,fe),this.getMessageActions=J.bind(this,f,he),this.listFiles=J.bind(this,f,de);var S=J.bind(this,f,ye);this.publishFile=J.bind(this,f,ge),this.sendFile=be({generateUploadUrl:S,publishFile:this.publishFile,modules:f}),this.getFileUrl=function(e){return me(f,e)},this.downloadFile=J.bind(this,f,ve),this.deleteFile=J.bind(this,f,_e),this.objects={getAllUUIDMetadata:J.bind(this,f,Oe),getUUIDMetadata:J.bind(this,f,Se),setUUIDMetadata:J.bind(this,f,Pe),removeUUIDMetadata:J.bind(this,f,we),getAllChannelMetadata:J.bind(this,f,ke),getChannelMetadata:J.bind(this,f,Te),setChannelMetadata:J.bind(this,f,Ee),removeChannelMetadata:J.bind(this,f,Ae),getChannelMembers:J.bind(this,f,Ne),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 M.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return M.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return M.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return M.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return M.PNNetworkIssuesCategory;if(e.timeout)return M.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return M.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return M.PNBadRequestCategory;if(e.response.forbidden)return M.PNAccessDeniedCategory}return M.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(Jt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn(Jt,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(Jt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn(Jt,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=Kn(e),r=n.length>0?n[0]:"",o=Ln("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,Un([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Sn(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&&(Nn[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:{}})),$n="function"==typeof Map&&Map.prototype,Jn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Qn=$n&&Jn&&"function"==typeof Jn.get?Jn.get:null,Xn=$n&&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,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,vr=Object.getOwnPropertySymbols,_r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Or="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Sr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Or||"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 kr(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,Er=Tr.custom,Ar=Rr(Er)?Er:null;function Nr(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]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}function Mr(e){return!("[object RegExp]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}function Rr(e){if(Or)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 xr(e,t){return Ur.call(e,t)}function Ir(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 Nr(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 Kr(e){return"Object("+e+")"}function Lr(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(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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?kr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?kr(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 xr(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=Or?lr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):_r.call(t);return"object"!=typeof t||Or?y:Kr(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||[],m=0;m"}if(jr(t)){if(0===t.length)return"[]";var v=qr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(v)?"["+Hr(v,p)+"]":"[ "+yr.call(v,", ")+" ]"}if(function(e){return!("[object Error]"!==Ir(e)||Sr&&"object"==typeof e&&Sr 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(Ar&&"function"==typeof t[Ar]&&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 O=[];return Xn&&Xn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Br("Map",Qn.call(t),O,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 S=[];return tr&&tr.call(t,(function(e){S.push(f(e,t))})),Br("Set",er.call(t),S,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 Lr("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 Lr("WeakSet");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{return or.call(e),!0}catch(e){}return!1}(t))return Lr("WeakRef");if(function(e){return!("[object Number]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(ir.call(t));if(function(e){return!("[object String]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t)&&!Mr(t)){var P=qr(t,f),w=wr?wr(t)===Object.prototype:t instanceof Object||t.constructor===Object,k=t instanceof Object?"":"null prototype",T=!w&&Sr&&Object(t)===t&&Sr in t?cr.call(Ir(t),8,-1):k?"Object":"",E=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||k?"["+yr.call(dr.call([],T||[],k||[]),": ")+"] ":"");return 0===P.length?E+"{}":p?E+"{"+Hr(P,p)+"}":E+"{ "+yr.call(P,", ")+" }"}return String(t)},$r=zr("%TypeError%"),Jr=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?m.join(",")||null:void 0}];else if(_o(u))P=u;else{var k=Object.keys(m);P=c?k.sort(c):k}for(var T=o&&_o(m)&&1===m.length?n+"[]":n,E=0;E-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&&No.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return ko;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||ko.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(!mo.call(bo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=bo.formatters[n],o=ko.filter;return("function"==typeof e.filter||_o(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:ko.addQueryPrefix,allowDots:void 0===e.allowDots?ko.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ko.charsetSentinel,delimiter:void 0===e.delimiter?ko.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:ko.encode,encoder:"function"==typeof e.encoder?e.encoder:ko.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:ko.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:ko.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:ko.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ko.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 vo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=vo[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:""},Io={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||Ao.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),No.call(r,c)?r[c]=Ao.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,Ko=Do.hasOwn;var Lo=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(Ko(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)Ko(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)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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");Ko(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 $o(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 Jo(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 Jo(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 Jo(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)&&m(t,n,e[n]);return t.join("&")}function m(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;){m(e,t,o.value)}}catch(e){i.e(e)}finally{i.f()}}else if(c(r))for(const n in r)p(r,n)&&m(e,`${t}[${n}]`,r[n]);else e.push(encodeURI(t)+"="+encodeURIComponent(r));else e.push(encodeURI(t))}function v(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 O(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=v,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":v,"application/json":JSON.parse},l(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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=k,y.delete=k,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:M.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:return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.toArrayBuffer()];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.toArrayBuffer()];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(e){return o(this,void 0,void 0,(function(){var t,n,r;return i(this,(function(o){switch(o.label){case 0:return t=Buffer.from(e),[4,crypto.subtle.digest("SHA-256",t.buffer)];case 1:return n=o.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 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(e,t){return o(this,void 0,void 0,(function(){var n;return i(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 o(this,void 0,void 0,(function(){var n,r,o,a;return i(this,(function(i){switch(i.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 o=i.sent(),a=ci(n.buffer,o),[2,Buffer.from(a).toString("utf8")]}}))}))},e.prototype.decryptString=function(e,t){return o(this,void 0,void 0,(function(){var n,r,o,a;return i(this,(function(i){switch(i.label){case 0:return n=Buffer.from(t),r=n.slice(0,16),o=n.slice(16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:r},e,o)];case 1:return a=i.sent(),[2,Buffer.from(a).toString("utf8")]}}))}))},e.IV_LENGTH=16,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);function hi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var di=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:hi,getfile:oi,postfile:ri}),t.cbor=new zt((function(e){return qt(f.decode(e))}),b),t.PubNubFile=fi,t.cryptography=new pi,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}(Bt);return di})); +!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.setCipherKey(o.cipherKey),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)}}return e.prototype.getAuthKey=function(){return this.authKey},e.prototype.setAuthKey=function(e){return this.authKey=e,this},e.prototype.setCipherKey=function(e){return this.cipherKey=e,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.3.3"},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}var v,m,_,O,S,P=P||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=(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 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=P,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],O=e[i+13],S=e[i+14],P=e[i+15],w=t(w=a[0],E=a[1],T=a[2],k=a[3],u,7,c[0]),k=t(k,w,E,T,s,12,c[1]),T=t(T,k,w,E,l,17,c[2]),E=t(E,T,k,w,p,22,c[3]);w=t(w,E,T,k,f,7,c[4]),k=t(k,w,E,T,h,12,c[5]),T=t(T,k,w,E,d,17,c[6]),E=t(E,T,k,w,y,22,c[7]),w=t(w,E,T,k,g,7,c[8]),k=t(k,w,E,T,b,12,c[9]),T=t(T,k,w,E,v,17,c[10]),E=t(E,T,k,w,m,22,c[11]),w=t(w,E,T,k,_,7,c[12]),k=t(k,w,E,T,O,12,c[13]),T=t(T,k,w,E,S,17,c[14]),w=n(w,E=t(E,T,k,w,P,22,c[15]),T,k,s,5,c[16]),k=n(k,w,E,T,d,9,c[17]),T=n(T,k,w,E,m,14,c[18]),E=n(E,T,k,w,u,20,c[19]),w=n(w,E,T,k,h,5,c[20]),k=n(k,w,E,T,v,9,c[21]),T=n(T,k,w,E,P,14,c[22]),E=n(E,T,k,w,f,20,c[23]),w=n(w,E,T,k,b,5,c[24]),k=n(k,w,E,T,S,9,c[25]),T=n(T,k,w,E,p,14,c[26]),E=n(E,T,k,w,g,20,c[27]),w=n(w,E,T,k,O,5,c[28]),k=n(k,w,E,T,l,9,c[29]),T=n(T,k,w,E,y,14,c[30]),w=r(w,E=n(E,T,k,w,_,20,c[31]),T,k,h,4,c[32]),k=r(k,w,E,T,g,11,c[33]),T=r(T,k,w,E,m,16,c[34]),E=r(E,T,k,w,S,23,c[35]),w=r(w,E,T,k,s,4,c[36]),k=r(k,w,E,T,f,11,c[37]),T=r(T,k,w,E,y,16,c[38]),E=r(E,T,k,w,v,23,c[39]),w=r(w,E,T,k,O,4,c[40]),k=r(k,w,E,T,u,11,c[41]),T=r(T,k,w,E,p,16,c[42]),E=r(E,T,k,w,d,23,c[43]),w=r(w,E,T,k,b,4,c[44]),k=r(k,w,E,T,_,11,c[45]),T=r(T,k,w,E,P,16,c[46]),w=o(w,E=r(E,T,k,w,l,23,c[47]),T,k,u,6,c[48]),k=o(k,w,E,T,y,10,c[49]),T=o(T,k,w,E,S,15,c[50]),E=o(E,T,k,w,h,21,c[51]),w=o(w,E,T,k,_,6,c[52]),k=o(k,w,E,T,p,10,c[53]),T=o(T,k,w,E,v,15,c[54]),E=o(E,T,k,w,s,21,c[55]),w=o(w,E,T,k,g,6,c[56]),k=o(k,w,E,T,P,10,c[57]),T=o(T,k,w,E,d,15,c[58]),E=o(E,T,k,w,O,21,c[59]),w=o(w,E,T,k,f,6,c[60]),k=o(k,w,E,T,m,10,c[61]),T=o(T,k,w,E,l,15,c[62]),E=o(E,T,k,w,b,21,c[63]);a[0]=a[0]+w|0,a[1]=a[1]+E|0,a[2]=a[2]+T|0,a[3]=a[3]+k|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=P,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=P,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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)}(),P.mode.ECB=((S=P.lib.BlockCipherMode.extend()).Encryptor=S.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),S.Decryptor=S.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),S);var w=P;function k(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 N(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function C(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var j={signPamFromParams:function(e){return C(e).map((function(t){return"".concat(t,"=").concat(N(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:N},M={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory"},R=function(){function e(e){var t=e.subscribeEndpoint,n=e.leaveEndpoint,r=e.heartbeatEndpoint,o=e.setStateEndpoint,i=e.timeEndpoint,a=e.getFileUrl,s=e.config,u=e.crypto,c=e.listenerManager;this._listenerManager=c,this._config=s,this._leaveEndpoint=n,this._heartbeatEndpoint=r,this._setStateEndpoint=o,this._subscribeEndpoint=t,this._getFileUrl=a,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 E({timeEndpoint:i}),this._dedupingManager=new A({config:s})}return e.prototype.adaptStateChange=function(e,t){var n=this,r=e.state,o=e.channels,i=void 0===o?[]:o,a=e.channelGroups,s=void 0===a?[]:a,u=e.withHeartbeat,c=void 0!==u&&u;if(i.forEach((function(e){e in n._channels&&(n._channels[e].state=r)})),s.forEach((function(e){e in n._channelGroups&&(n._channelGroups[e].state=r)})),c){var l={};return i.forEach((function(e){return l[e]=r})),s.forEach((function(e){return l[e]=r})),this._heartbeatEndpoint({channels:i,channelGroups:s,state:l},t)}return this._setStateEndpoint({state:r,channels:i,channelGroups:s},t)},e.prototype.adaptPresenceChange=function(e){var t=this,n=e.connected,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i;n?(o.forEach((function(e){t._heartbeatChannels[e]={state:{}}})),a.forEach((function(e){t._heartbeatChannelGroups[e]={state:{}}}))):(o.forEach((function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]})),a.forEach((function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]})),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:o,channelGroups:a},(function(e){t._listenerManager.announceStatus(e)}))),this.reconnect()},e.prototype.adaptSubscribeChange=function(e){var t=this,n=e.timetoken,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i,s=e.withPresence,u=void 0!==s&&s,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),o.forEach((function(e){t._channels[e]={state:{}},u&&(t._presenceChannels[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannels[e]={}),t._pendingChannelSubscriptions.push(e)})),a.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,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i,s=[],u=[];o.forEach((function(e){e in n._channels&&(delete n._channels[e],s.push(e),e in n._heartbeatChannels&&delete n._heartbeatChannels[e]),e in n._presenceChannels&&(delete n._presenceChannels[e],s.push(e))})),a.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===s.length&&0===u.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:s,channelGroups:u},(function(e){e.affectedChannels=s,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 o=e._channels[r].state;Object.keys(o).length&&(t[r]=o),n.push(r)})),Object.keys(this._presenceChannels).forEach((function(e){n.push("".concat(e,"-pnpres"))})),Object.keys(this._channelGroups).forEach((function(n){var o=e._channelGroups[n].state;Object.keys(o).length&&(t[n]=o),r.push(n)})),Object.keys(this._presenceChannelGroups).forEach((function(e){r.push("".concat(e,"-pnpres"))})),0!==n.length||0!==r.length){var o={channels:n,channelGroups:r,state:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(o,this._processSubscribeResponse.bind(this))}},e.prototype._processSubscribeResponse=function(e,t){var o=this;if(e.error){if(e.errorData&&"Aborted"===e.errorData.message)return;e.category===M.PNTimeoutCategory?this._startSubscribeLoop():e.category===M.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection((function(){o._config.autoNetworkDetection&&!o._isOnline&&(o._isOnline=!0,o._listenerManager.announceNetworkUp()),o.reconnect(),o._subscriptionStatusAnnounced=!0;var t={category:M.PNReconnectedCategory,operation:e.operation,lastTimetoken:o._lastTimetoken,currentTimetoken:o._currentTimetoken};o._listenerManager.announceStatus(t)})),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===M.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 i={};i.category=M.PNConnectedCategory,i.operation=e.operation,i.affectedChannels=this._pendingChannelSubscriptions,i.subscribedChannels=this.getSubscribedChannels(),i.affectedChannelGroups=this._pendingChannelGroupSubscriptions,i.lastTimetoken=this._lastTimetoken,i.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(i),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var a=t.messages||[],s=this._config,u=s.requestMessageCountThreshold,c=s.dedupeOnSubscribe;if(u&&a.length>=u){var l={};l.category=M.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(j.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._config.cipherKey){var d=o._crypto.decrypt(e.payload);"object"==typeof d&&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;(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._config.cipherKey?y.message=o._crypto.decrypt(e.payload):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}(),U={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!==U.PNSubscribeOperation&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(e!==U.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 U.PNPublishOperation:t="pub";break;case U.PNSignalOperation:t="sig";break;case U.PNHistoryOperation:case U.PNFetchMessagesOperation:case U.PNDeleteMessagesOperation:case U.PNMessageCounts:t="hist";break;case U.PNUnsubscribeOperation:case U.PNWhereNowOperation:case U.PNHereNowOperation:case U.PNHeartbeatOperation:case U.PNSetStateOperation:case U.PNGetStateOperation:t="pres";break;case U.PNAddChannelsToGroupOperation:case U.PNRemoveChannelsFromGroupOperation:case U.PNChannelGroupsOperation:case U.PNRemoveGroupOperation:case U.PNChannelsForGroupOperation:t="cg";break;case U.PNPushNotificationEnabledChannelsOperation:case U.PNRemoveAllPushNotificationsOperation:t="push";break;case U.PNCreateUserOperation:case U.PNUpdateUserOperation:case U.PNDeleteUserOperation:case U.PNGetUserOperation:case U.PNGetUsersOperation:case U.PNCreateSpaceOperation:case U.PNUpdateSpaceOperation:case U.PNDeleteSpaceOperation:case U.PNGetSpaceOperation:case U.PNGetSpacesOperation:case U.PNGetMembersOperation:case U.PNUpdateMembersOperation:case U.PNGetMembershipsOperation:case U.PNUpdateMembershipsOperation:t="obj";break;case U.PNAddMessageActionOperation:case U.PNRemoveMessageActionOperation:case U.PNGetMessageActionsOperation:t="msga";break;case U.PNAccessManagerGrant:case U.PNAccessManagerAudit:t="pam";break;case U.PNAccessManagerGrantToken:case U.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),I=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,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}(I),F=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}(I),G=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}(I),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 F(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 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}(),L=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=M.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=M.PNNetworkDownCategory,this.announceStatus(e)},e}(),B=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}(),H=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 q(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}function z(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 V(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 W(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=W(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(j.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 J(e,t){for(var r=[],o=2;o0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.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 ae=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 se=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 ue=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 ce=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(i),"/uuid/").concat(j.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 le=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 pe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 fe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 he=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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}}),de={getOperation:function(){return U.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(j.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}}},ye={getOperation:function(){return U.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(j.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}}},ge={getOperation:function(){return U.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=e.crypto,r=e.config,o=JSON.stringify(t);return r.cipherKey&&(o=n.encrypt(o),o=JSON.stringify(o)),o||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(j.encodeString(t.channel),"/0/").concat(j.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]}}},be=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,k,T,E,A,N,C,j,M,R,U,x,I,D,F,G,K,L;return i(this,(function(i){switch(i.label){case 0:if(!a)throw new H("Validation failed, check status for details",q("channel can't be empty"));if(!p)throw new H("Validation failed, check status for details",q("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(k=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,k.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(A=(E=l).POSTFILE,N=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,A.apply(E,N.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,x=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,x.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(I=i.sent()).response&&"string"==typeof I.response.text?(D=I.response.text,F=/(.*)<\/Message>/gi.exec(D),new H(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",I)):new H("Upload to bucket failed.",I);case 19:if(204!==P.status)throw new H("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,K=!1,L={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return L=i.sent(),K=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!K&&G>0)return[3,20];i.label=24;case 24:if(K)return[2,{timetoken:L.timetoken,id:_,name:O}];throw new H("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},ve=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 H("Validation failed, check status for details",q("channel can't be empty"));if(!r)throw new H("Validation failed, check status for details",q("file id can't be empty"));if(!o)throw new H("Validation failed, check status for details",q("file name can't be empty"));var u="/v1/files/".concat(i.subscribeKey,"/channels/").concat(j.encodeString(n),"/files/").concat(r,"/").concat(o),c={};c.uuid=i.getUUID(),c.pnsdk=V(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)},me={getOperation:function(){return U.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(j.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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},_e={getOperation:function(){return U.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(j.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 U.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}}},Se={getOperation:function(){return U.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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}}},Pe={getOperation:function(){return U.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(j.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}}},we={getOperation:function(){return U.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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}}},ke={getOperation:function(){return U.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}}},Te={getOperation:function(){return U.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(j.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}}},Ee={getOperation:function(){return U.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(j.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}}},Ae={getOperation:function(){return U.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(j.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}}},Ne={getOperation:function(){return U.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(j.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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Ce={getOperation:function(){return U.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(j.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}}},je={getOperation:function(){return U.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Me={getOperation:function(){return U.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(j.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 Re=Object.freeze({__proto__:null,getOperation:function(){return U.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 Ue=Object.freeze({__proto__:null,getOperation:function(){return U.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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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 Ie(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(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]=Ie(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Ie(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Ie(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]=Ie(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Ie(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Ie(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]=Ie(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Ie(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Ie(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]=Ie(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Ie(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Ie(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Fe=Object.freeze({__proto__:null,getOperation:function(){return U.PNAccessManagerGrantToken},extractPermissions:Ie,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 De(0,t)},handleResponse:function(e,t){return t.data.token}}),Ge={getOperation:function(){return U.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(j.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,o=JSON.stringify(t);return r.cipherKey&&(o=n.encrypt(o),o=JSON.stringify(o)),o}var Le=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(r),"/0/").concat(j.encodeString(o))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(j.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 Be=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(o),"/0/").concat(j.encodeString(a))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});function He(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}var qe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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={timetoken:t.timetoken,entry:He(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var ze=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 U.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(j.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 U.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(j.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={};o.channel=r,o.timetoken=t.timetoken,o.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),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=Object.freeze({__proto__:null,getOperation:function(){return U.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 Je=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 U.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(j.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 U.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(j.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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}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(Nt())];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(Et(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof H?[2,t.transition(At(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(Ot(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof H?[2,t.transition(St(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 xt=new Ze("RECEIVE_FAILURE");xt.on(Ct.type,(function(e){return It.with(n(n({},e),{attempts:0}))})),xt.on(bt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var It=new Ze("RECEIVE_RECONNECTING");It.onEnter((function(e){return dt(e)})),It.onExit((function(){return dt.cancel})),It.on(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),It.on(At.type,(function(e,t){return It.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),It.on(Nt.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),It.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(kt.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?Kt.with(void 0):Dt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Dt.on(Tt.type,(function(e,t){return It.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(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),Ft.on(At.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(Nt.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?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: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 Kt=new Ze("UNSUBSCRIBED");Kt.on(gt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Lt=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(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=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 T({config:i}),c=e.cryptography;r.init(i);var l=new B(i,o);this._tokenManager=l;var p=new x({maximumSamplesCount:6e4});this._telemetryManager=p;var f={config:i,networking:r,crypto:a,cryptography:c,tokenManager:l,telemetryManager:p,PubNubFile:e.PubNubFile};this.File=e.PubNubFile,this.encryptFile=function(e,n){return c.encryptFile(e,n,t.File)},this.decryptFile=function(e,n){return c.decryptFile(e,n,t.File)};var h=J.bind(this,f,$e),d=J.bind(this,f,ie),y=J.bind(this,f,se),b=J.bind(this,f,ce),v=J.bind(this,f,Je),m=new L;if(this._listenerManager=m,this.iAmHere=J.bind(this,f,se),this.iAmAway=J.bind(this,f,ie),this.setPresenceState=J.bind(this,f,ce),this.handshake=J.bind(this,f,Qe),this.receiveMessages=J.bind(this,f,Xe),!0===i.enableSubscribeBeta){var _=new Lt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=_.subscribe.bind(_),this.unsubscribe=_.unsubscribe.bind(_),this.eventEngine=_}else{var O=new R({timeEndpoint:h,leaveEndpoint:d,heartbeatEndpoint:y,setStateEndpoint:b,subscribeEndpoint:v,crypto:f.crypto,config:f.config,listenerManager:m,getFileUrl:function(e){return ve(f,e)}});this.subscribe=O.adaptSubscribeChange.bind(O),this.unsubscribe=O.adaptUnsubscribeChange.bind(O),this.disconnect=O.disconnect.bind(O),this.reconnect=O.reconnect.bind(O),this.unsubscribeAll=O.unsubscribeAll.bind(O),this.getSubscribedChannels=O.getSubscribedChannels.bind(O),this.getSubscribedChannelGroups=O.getSubscribedChannelGroups.bind(O),this.setState=O.adaptStateChange.bind(O),this.presence=O.adaptPresenceChange.bind(O),this.destroy=function(e){O.unsubscribeAll(e),O.disconnect()}}this.addListener=m.addListener.bind(m),this.removeListener=m.removeListener.bind(m),this.removeAllListeners=m.removeAllListeners.bind(m),this.parseToken=l.parseToken.bind(l),this.setToken=l.setToken.bind(l),this.getToken=l.getToken.bind(l),this.channelGroups={listGroups:J.bind(this,f,Z),listChannels:J.bind(this,f,ee),addChannels:J.bind(this,f,Q),removeChannels:J.bind(this,f,X),deleteGroup:J.bind(this,f,Y)},this.push={addChannels:J.bind(this,f,te),removeChannels:J.bind(this,f,ne),deleteDevice:J.bind(this,f,oe),listChannels:J.bind(this,f,re)},this.hereNow=J.bind(this,f,le),this.whereNow=J.bind(this,f,ae),this.getState=J.bind(this,f,ue),this.grant=J.bind(this,f,Ue),this.grantToken=J.bind(this,f,Fe),this.audit=J.bind(this,f,Re),this.revokeToken=J.bind(this,f,Ge),this.publish=J.bind(this,f,Le),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=J.bind(this,f,Be),this.history=J.bind(this,f,qe),this.deleteMessages=J.bind(this,f,ze),this.messageCounts=J.bind(this,f,Ve),this.fetchMessages=J.bind(this,f,We),this.addMessageAction=J.bind(this,f,pe),this.removeMessageAction=J.bind(this,f,fe),this.getMessageActions=J.bind(this,f,he),this.listFiles=J.bind(this,f,de);var S=J.bind(this,f,ye);this.publishFile=J.bind(this,f,ge),this.sendFile=be({generateUploadUrl:S,publishFile:this.publishFile,modules:f}),this.getFileUrl=function(e){return ve(f,e)},this.downloadFile=J.bind(this,f,me),this.deleteFile=J.bind(this,f,_e),this.objects={getAllUUIDMetadata:J.bind(this,f,Oe),getUUIDMetadata:J.bind(this,f,Se),setUUIDMetadata:J.bind(this,f,Pe),removeUUIDMetadata:J.bind(this,f,we),getAllChannelMetadata:J.bind(this,f,ke),getChannelMetadata:J.bind(this,f,Te),setChannelMetadata:J.bind(this,f,Ee),removeChannelMetadata:J.bind(this,f,Ae),getChannelMembers:J.bind(this,f,Ne),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 M.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return M.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return M.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return M.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return M.PNNetworkIssuesCategory;if(e.timeout)return M.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return M.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return M.PNBadRequestCategory;if(e.response.forbidden)return M.PNAccessDeniedCategory}return M.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(Jt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn(Jt,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(Jt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn(Jt,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=Kn(e),r=n.length>0?n[0]:"",o=Ln("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,Un([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Sn(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&&(Nn[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:{}})),$n="function"==typeof Map&&Map.prototype,Jn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Qn=$n&&Jn&&"function"==typeof Jn.get?Jn.get:null,Xn=$n&&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,Or="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Sr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Or||"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 kr(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,Er=Tr.custom,Ar=Rr(Er)?Er:null;function Nr(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]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}function Mr(e){return!("[object RegExp]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}function Rr(e){if(Or)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 xr(e,t){return Ur.call(e,t)}function Ir(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 Nr(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 Kr(e){return"Object("+e+")"}function Lr(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(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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?kr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?kr(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 xr(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=Or?lr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):_r.call(t);return"object"!=typeof t||Or?y:Kr(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]"!==Ir(e)||Sr&&"object"==typeof e&&Sr 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(Ar&&"function"==typeof t[Ar]&&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 O=[];return Xn&&Xn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Br("Map",Qn.call(t),O,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 S=[];return tr&&tr.call(t,(function(e){S.push(f(e,t))})),Br("Set",er.call(t),S,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 Lr("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 Lr("WeakSet");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{return or.call(e),!0}catch(e){}return!1}(t))return Lr("WeakRef");if(function(e){return!("[object Number]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(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 Kr(f(vr.call(t)));if(function(e){return!("[object Boolean]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(ir.call(t));if(function(e){return!("[object String]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t)&&!Mr(t)){var P=qr(t,f),w=wr?wr(t)===Object.prototype:t instanceof Object||t.constructor===Object,k=t instanceof Object?"":"null prototype",T=!w&&Sr&&Object(t)===t&&Sr in t?cr.call(Ir(t),8,-1):k?"Object":"",E=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||k?"["+yr.call(dr.call([],T||[],k||[]),": ")+"] ":"");return 0===P.length?E+"{}":p?E+"{"+Hr(P,p)+"}":E+"{ "+yr.call(P,", ")+" }"}return String(t)},$r=zr("%TypeError%"),Jr=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 k=Object.keys(v);P=c?k.sort(c):k}for(var T=o&&_o(v)&&1===v.length?n+"[]":n,E=0;E-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&&No.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return ko;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||ko.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=ko.filter;return("function"==typeof e.filter||_o(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:ko.addQueryPrefix,allowDots:void 0===e.allowDots?ko.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ko.charsetSentinel,delimiter:void 0===e.delimiter?ko.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:ko.encode,encoder:"function"==typeof e.encoder?e.encoder:ko.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:ko.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:ko.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:ko.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ko.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:""},Io={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||Ao.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),No.call(r,c)?r[c]=Ao.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,Ko=Do.hasOwn;var Lo=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(Ko(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)Ko(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)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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");Ko(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 $o(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 Jo(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 Jo(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 Jo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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=k,y.delete=k,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:M.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:return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return n=t.slice(0,16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,t.slice(16))];case 1:return[2,r.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);function hi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var di=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:hi,getfile:oi,postfile:ri}),t.cbor=new zt((function(e){return qt(f.decode(e))}),b),t.PubNubFile=fi,t.cryptography=new pi,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}(Bt);return di})); 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..1cb80e7cc --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -0,0 +1,453 @@ +"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 }); +var stream_1 = require("stream"); +var endpoint_1 = require("../../../core/components/endpoint"); +var legacyCryptor_1 = __importDefault(require("./legacyCryptor")); +var aesCbcCryptor_1 = __importDefault(require("./aesCbcCryptor")); +var CryptoModule = /** @class */ (function () { + function CryptoModule(cryptoModuleConfiguration) { + var _a; + this.defaultCryptor = cryptoModuleConfiguration.default; + this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; + } + //@ts-ignore: type detection issue with old Config type assignment + CryptoModule.legacyCryptoModule = function (_a) { + var config = _a.config; + return new this({ + default: new legacyCryptor_1.default({ config: config }), + cryptors: [new aesCbcCryptor_1.default(config.cipherKey)], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + return new this({ + default: new aesCbcCryptor_1.default(config.cipherKey), + cryptors: [new legacyCryptor_1.default({ config: config })], + }); + }; + 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) { + return __awaiter(this, void 0, void 0, function () { + var encrypted, header, headerData, pos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(data)]; + case 1: + encrypted = _a.sent(); + if (!encrypted.metadata) + return [2 /*return*/, encrypted.data]; + header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + headerData = new Uint8Array(header.length); + pos = 0; + headerData.set(header.data, pos); + pos += header.length; + if (encrypted.metadata) { + pos -= encrypted.metadata.length; + headerData.set(encrypted.metadata, pos); + } + return [2 /*return*/, Buffer.concat([headerData, encrypted.data])]; + } + }); + }); + }; + CryptoModule.prototype.decrypt = function (data) { + return __awaiter(this, void 0, void 0, function () { + var encryptedData, header, cryptor, metadata; + return __generator(this, function (_a) { + encryptedData = null; + encryptedData = Buffer.from(data); + header = CryptorHeader.tryParse(encryptedData); + cryptor = this.getCryptor(header); + metadata = header.length > 0 + ? encryptedData.slice(header.length - header.metadataLength, header.length) + : null; + return [2 /*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 _a, _b, encryptedStream, header, payload, pos, output; + var _c; + return __generator(this, function (_d) { + switch (_d.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 instanceof legacyCryptor_1.default) + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; + _b = (_a = File).create; + _c = { + name: file.name, + mimeType: 'application/octet-stream' + }; + return [4 /*yield*/, this.encrypt(file.data)]; + case 1: return [2 /*return*/, _b.apply(_a, [( + //@ts-ignore: can not infer that PubNubFile has data field + _c.data = _d.sent(), + _c)])]; + case 2: + //@ts-ignore: can not infer that PubNubFile has data field + if (file.data instanceof stream_1.Readable) { + encryptedStream = this.defaultCryptor.encryptStream(file.data); + 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.data.pipe(output); + return [2 /*return*/, File.create({ + name: file.name, + mimeType: 'application/octet-stream', + stream: output, + })]; + } + return [2 /*return*/]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var header, cryptor, _a, _b, stream_2; + var _c; + var _this = this; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + if (!((file === null || file === void 0 ? void 0 : file.data) instanceof Buffer)) return [3 /*break*/, 2]; + 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) + */ + //@ts-ignore: cryptor will be there or unreachable due to exception + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) + return [2 /*return*/, cryptor.decryptFile(file, File)]; + _b = (_a = File).create; + _c = { + name: file.name + }; + return [4 /*yield*/, this.decrypt(file === null || file === void 0 ? void 0 : file.data)]; + case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + _c)])]; + case 2: + 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)) { + 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); + _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) { + cryptor = this.getLegacyCryptor(); + if (cryptor) { + //@ts-ignore: cryptor will be there or unreachable due to exception + return [2 /*return*/, cryptor.decryptFile(File.create({ + name: file.name, + stream: stream, + }), File)]; + } + else { + throw new endpoint_1.PubNubError('unknown cryptor'); + } + 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'); + } + 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'); + }; + CryptoModule.LEGACY_IDENTIFIER = ''; + return CryptoModule; +}()); +exports.default = 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 endpoint_1.PubNubError('decryption error'); + return data; + }; + CryptorHeader.tryGetIdentifier = function (data) { + if (data.byteLength < 4) { + throw new endpoint_1.PubNubError('unknown cryptor'); + } + 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); + } + } + }; + 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 endpoint_1.PubNubError('decryption error'); + } + if (version > CryptorHeader.MAX_VERSION) + throw new endpoint_1.PubNubError('unknown cryptor'); + var identifier; + var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.length >= pos) { + identifier = encryptedData.slice(5, pos); + } + else { + throw new endpoint_1.PubNubError('decryption error'); + } + var headerSize = null; + if (encryptedData.length > pos + 1) { + headerSize = encryptedData[pos]; + } + pos += 1; + if (headerSize === 255 && encryptedData.length >= pos + 2) { + headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + pos += 2; + } + return new CryptorHeaderV1(identifier.toString('utf8'), headerSize); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.MAX_VERSION = 1; + 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 CryptorHeaderV1.VERSION; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CryptorHeaderV1.prototype, "length", { + get: function () { + return (CryptorHeaderV1.SENTINEL.length + + 1 + + CryptorHeaderV1.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(CryptorHeaderV1.SENTINEL)); + pos += CryptorHeaderV1.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(Buffer.from(this.identifier), pos); + pos += CryptorHeaderV1.IDENTIFIER_LENGTH; + var metadata_size = this.metadataLength; + if (metadata_size < 255) { + header[pos] = metadata_size; + } + else { + header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + } + return header; + }, + enumerable: false, + configurable: true + }); + CryptorHeaderV1.IDENTIFIER_LENGTH = 4; + CryptorHeaderV1.SENTINEL = 'PNED'; + CryptorHeaderV1.VERSION = 1; + return CryptorHeaderV1; +}()); diff --git a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js new file mode 100644 index 000000000..8ae2a5467 --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/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 }; + } +}; +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) { + return __awaiter(this, void 0, void 0, function () { + var iv, key, bPlain, aes; + return __generator(this, function (_a) { + iv = this.getIv(); + key = this.getKey(); + bPlain = Buffer.from(data); + aes = (0, crypto_1.createCipheriv)(this.algo, key, iv); + return [2 /*return*/, { + metadata: iv, + data: Buffer.concat([aes.update(bPlain), aes.final()]), + }]; + }); + }); + }; + AesCbcCryptor.prototype.decrypt = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + var aes; + return __generator(this, function (_a) { + aes = (0, crypto_1.createDecipheriv)(this.algo, this.getKey(), encryptedData.metadata); + return [2 /*return*/, Buffer.concat([aes.update(encryptedData.data), aes.final()])]; + }); + }); + }; + 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(); + 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..9938ff928 --- /dev/null +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -0,0 +1,91 @@ +"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 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) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, { + data: this.cryptor.encrypt(data), + metadata: null, + }]; + }); + }); + }; + LegacyCryptor.prototype.decrypt = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + // Legacy cryptor only works on base64 string + return [2 /*return*/, this.cryptor.decrypt(encryptedData.data.toString())]; + }); + }); + }; + 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/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..83df01db6 --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js @@ -0,0 +1,117 @@ +"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 AesCbcCryptor = /** @class */ (function () { + function AesCbcCryptor(configuration) { + this.cipherKey = configuration.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, 'AES-CBC', true, ['encrypt', 'decrypt'])]; + } + }); + }); + }; + AesCbcCryptor.prototype.encrypt = function (data) { + return __awaiter(this, void 0, void 0, function () { + var abIv, key; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + abIv = this._getIv(); + return [4 /*yield*/, this._getKey()]; + case 1: + key = _b.sent(); + _a = { + metadata: abIv + }; + return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, data)]; + case 2: return [2 /*return*/, (_a.data = _b.sent(), + _a)]; + } + }); + }); + }; + AesCbcCryptor.prototype.decrypt = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + var key, decryptedData; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this._getKey()]; + case 1: + key = _a.sent(); + return [4 /*yield*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)]; + case 2: + decryptedData = _a.sent(); + return [2 /*return*/, decryptedData]; + } + }); + }); + }; + 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..9a685954f --- /dev/null +++ b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js @@ -0,0 +1,93 @@ +"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 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) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, { + data: this.cryptor.encrypt(data), + metadata: null, + }]; + }); + }); + }; + LegacyCryptor.prototype.decrypt = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, this.cryptor.decrypt(encryptedData.data)]; + }); + }); + }; + LegacyCryptor.prototype.encryptFile = function (file, File) { + var _a; + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_b) { + //@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) { + //@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/node.js b/lib/crypto/modules/node.js index 4250597d9..63ece807c 100644 --- a/lib/crypto/modules/node.js +++ b/lib/crypto/modules/node.js @@ -180,12 +180,26 @@ var NodeCryptography = /** @class */ (function () { 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..58ab3bb8f 100644 --- a/lib/crypto/modules/web.js +++ b/lib/crypto/modules/web.js @@ -36,6 +36,31 @@ 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 __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)); +}; Object.defineProperty(exports, "__esModule", { value: true }); function concatArrayBuffer(ab1, ab2) { var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); @@ -43,6 +68,14 @@ function concatArrayBuffer(ab1, ab2) { tmp.set(new Uint8Array(ab2), ab1.byteLength); return tmp.buffer; } +function ab2hex(ab) { + return __spreadArray([], __read(new Uint8Array(ab)), false).map(function (x) { return x.toString(16).padStart(2, '0'); }).join(''); +} +function hex2ab(hex) { + return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { + return parseInt(h, 16); + })); +} var WebCryptography = /** @class */ (function () { function WebCryptography() { } @@ -142,11 +175,11 @@ var WebCryptography = /** @class */ (function () { return __generator(this, function (_a) { switch (_a.label) { case 0: - bKey = Buffer.from(key); + bKey = WebCryptography.encoder.encode(key); return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; case 1: abHash = _a.sent(); - abKey = Buffer.from(Buffer.from(abHash).toString('hex').slice(0, 32), 'utf8').buffer; + abKey = hex2ab(ab2hex(abHash).slice(0, 32)).buffer; return [2 /*return*/, crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt'])]; } }); @@ -169,10 +202,16 @@ 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); + return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16))]; + case 1: + data = _a.sent(); + return [2 /*return*/, data]; + } }); }); }; @@ -183,12 +222,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 +238,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; From 243056b6997a4daae705805dbad04f2c6222695e Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:39:32 +0530 Subject: [PATCH 09/38] fix:es-lint --- .../NodeCryptoModule/NodeCryptoModule.js | 15 ++++-- .../modules/NodeCryptoModule/legacyCryptor.js | 1 - .../modules/WebCryptoModule/legacyCryptor.js | 2 + .../WebCryptoModule/webCryptoModule.js | 14 ++++-- .../NodeCryptoModule/nodeCryptoModule.ts | 49 +++++++++++-------- .../modules/WebCryptoModule/legacyCryptor.ts | 2 + .../WebCryptoModule/webCryptoModule.ts | 33 ++++++++----- src/crypto/modules/web.js | 5 +- 8 files changed, 75 insertions(+), 46 deletions(-) diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 1cb80e7cc..7b43de9db 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -74,7 +74,8 @@ var CryptoModule = /** @class */ (function () { this.defaultCryptor = cryptoModuleConfiguration.default; this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : []; } - //@ts-ignore: type detection issue with old Config type assignment + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore: type detection issue with old Config type assignment CryptoModule.legacyCryptoModule = function (_a) { var config = _a.config; return new this({ @@ -160,10 +161,12 @@ var CryptoModule = /** @class */ (function () { }; return [4 /*yield*/, this.encrypt(file.data)]; case 1: return [2 /*return*/, _b.apply(_a, [( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field _c.data = _d.sent(), _c)])]; case 2: + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof stream_1.Readable) { encryptedStream = this.defaultCryptor.encryptStream(file.data); @@ -205,6 +208,7 @@ var CryptoModule = /** @class */ (function () { * If It's legacyone then redirect it. * (as long as we support legacy need to check on instance type) */ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) return [2 /*return*/, cryptor.decryptFile(file, File)]; @@ -263,6 +267,7 @@ var CryptoModule = /** @class */ (function () { return __generator(this, function (_a) { cryptor = this.getLegacyCryptor(); if (cryptor) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception return [2 /*return*/, cryptor.decryptFile(File.create({ name: file.name, @@ -434,12 +439,12 @@ var CryptorHeaderV1 = /** @class */ (function () { if (this.identifier) header.set(Buffer.from(this.identifier), pos); pos += CryptorHeaderV1.IDENTIFIER_LENGTH; - var metadata_size = this.metadataLength; - if (metadata_size < 255) { - header[pos] = metadata_size; + var metadataSize = this.metadataLength; + if (metadataSize < 255) { + header[pos] = metadataSize; } else { - header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); } return header; }, diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js index 9938ff928..86163e55c 100644 --- a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -67,7 +67,6 @@ var LegacyCryptor = /** @class */ (function () { LegacyCryptor.prototype.decrypt = function (encryptedData) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { - // Legacy cryptor only works on base64 string return [2 /*return*/, this.cryptor.decrypt(encryptedData.data.toString())]; }); }); diff --git a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js index 9a685954f..0666c878d 100644 --- a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js @@ -75,6 +75,7 @@ var LegacyCryptor = /** @class */ (function () { 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)]; }); @@ -83,6 +84,7 @@ var LegacyCryptor = /** @class */ (function () { 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)]; }); diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index 02daea5a5..9adcd3555 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -73,6 +73,7 @@ var CryptoModule = /** @class */ (function () { 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 (_a) { var config = _a.config; @@ -126,6 +127,7 @@ var CryptoModule = /** @class */ (function () { metadata = header.length > 0 ? encryptedData.slice(header.length - header.metadataLength, header.length) : null; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception return [2 /*return*/, cryptor.decrypt({ data: encryptedData.slice(header.length), @@ -145,6 +147,7 @@ var CryptoModule = /** @class */ (function () { * Files handled differently in case of Legacy cryptor. * (as long as we support legacy need to check on default cryptor) */ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. if (this.defaultCryptor.identifier === '') return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; @@ -156,6 +159,7 @@ var CryptoModule = /** @class */ (function () { }; return [4 /*yield*/, this.encrypt(file.data)]; case 1: return [2 /*return*/, _b.apply(_a, [( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field _c.data = _d.sent(), _c)])]; @@ -178,6 +182,7 @@ var CryptoModule = /** @class */ (function () { * If It's legacyone then redirect it. * (as long as we support legacy need to check on instance type) */ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception if (cryptor.identifier === CryptoModule.LEGACY_IDENTIFIER) return [2 /*return*/, cryptor.decryptFile(file, File)]; @@ -187,6 +192,7 @@ var CryptoModule = /** @class */ (function () { }; return [4 /*yield*/, this.decrypt(file.data)]; case 1: return [2 /*return*/, _b.apply(_a, [( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field _c.data = _d.sent(), _c)])]; @@ -329,12 +335,12 @@ var CryptorHeaderV1 = /** @class */ (function () { if (this.identifier) header.set(encoder.encode(this.identifier), pos); pos += CryptorHeaderV1.IDENTIFIER_LENGTH; - var metadata_size = this.metadataLength; - if (metadata_size < 255) { - header[pos] = metadata_size; + var metadataSize = this.metadataLength; + if (metadataSize < 255) { + header[pos] = metadataSize; } else { - header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); } return header; }, diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 31d60d87d..742235f13 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -23,7 +23,8 @@ export default class CryptoModule { this.cryptors = cryptoModuleConfiguration.cryptors ?? []; } - //@ts-ignore: type detection issue with old Config type assignment + // 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({ config }), @@ -51,12 +52,12 @@ export default class CryptoModule { } async encrypt(data: Buffer) { - let encrypted = await this.defaultCryptor.encrypt(data); + const encrypted = await this.defaultCryptor.encrypt(data); if (!encrypted.metadata) return encrypted.data; - let header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - let headerData = new Uint8Array(header!.length); + const headerData = new Uint8Array(header!.length); let pos = 0; headerData.set(header!.data, pos); pos += header!.length; @@ -71,9 +72,9 @@ export default class CryptoModule { let encryptedData = null; encryptedData = Buffer.from(data); - let header = CryptorHeader.tryParse(encryptedData); - let cryptor = this.getCryptor(header); - let metadata = + 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; @@ -89,22 +90,26 @@ export default class CryptoModule { * (as long as we support legacy need to check on intsance type) */ if (this.defaultCryptor instanceof LegacyCryptor) return this.defaultCryptor.encryptFile(file, File); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Buffer) { return File.create({ name: file.name, mimeType: 'application/octet-stream', + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field data: await this.encrypt(file.data!), }); } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Readable) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. - let encryptedStream = this.defaultCryptor.encryptStream(file.data); - let header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); + const encryptedStream = this.defaultCryptor.encryptStream(file.data); + const header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); - let payload = new Uint8Array(header!.length); + const payload = new Uint8Array(header!.length); let pos = 0; payload.set(header!.data, pos); pos += header!.length; @@ -126,12 +131,13 @@ export default class CryptoModule { async decryptFile(file: any, File: PubnubFile) { if (file?.data instanceof Buffer) { - let header = CryptorHeader.tryParse(file.data); - let cryptor = this.getCryptor(header); + 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) */ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); return File.create({ @@ -151,16 +157,16 @@ export default class CryptoModule { async onStreamReadable(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { stream.removeAllListeners('readable'); - let magicBytes = stream.read(4); + const magicBytes = stream.read(4); if (!CryptorHeader.isSentinel(magicBytes as Buffer)) { stream.unshift(magicBytes); return this.decryptLegacyFileStream(stream, file, File); } - let versionByte = stream.read(1); + const versionByte = stream.read(1); CryptorHeader.validateVersion(versionByte[0] as number); - let identifier = stream.read(4); - let cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier as Buffer)); - let headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream); + const identifier = stream.read(4); + const cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier as Buffer)); + const headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream); return File.create({ name: file.name, @@ -172,6 +178,7 @@ export default class CryptoModule { async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { const cryptor = this.getLegacyCryptor(); if (cryptor) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception return cryptor.decryptFile( File.create({ @@ -336,11 +343,11 @@ class CryptorHeaderV1 { pos++; if (this.identifier) header.set(Buffer.from(this.identifier), pos); pos += CryptorHeaderV1.IDENTIFIER_LENGTH; - let metadata_size = this.metadataLength; - if (metadata_size < 255) { - header[pos] = metadata_size; + const metadataSize = this.metadataLength; + if (metadataSize < 255) { + header[pos] = metadataSize; } else { - header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); } return header; } diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts index 062398eec..b4c689faa 100644 --- a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -33,11 +33,13 @@ export default class LegacyCryptor implements ILegacyCryptor { } async encryptFile(file: PubnubFile, File: PubnubFile) { + // 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: PubnubFile, File: PubnubFile) { + // 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 index 3bba4dd37..ec7f11386 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -21,6 +21,7 @@ export default class CryptoModule { 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({ @@ -45,12 +46,12 @@ export default class CryptoModule { } async encrypt(data: ArrayBuffer) { - let encrypted = await this.defaultCryptor.encrypt(data); + const encrypted = await this.defaultCryptor.encrypt(data); if (!encrypted.metadata) return encrypted.data; - let header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - let headerData = new Uint8Array((header as CryptorHeaderV1).length); + const headerData = new Uint8Array((header as CryptorHeaderV1).length); let pos = 0; headerData.set((header as CryptorHeaderV1).data, pos); pos += (header as CryptorHeaderV1).length; @@ -62,12 +63,13 @@ export default class CryptoModule { } async decrypt(encryptedData: ArrayBuffer) { - let header = CryptorHeader.tryParse(encryptedData); - let cryptor = this.getCryptor(header); - let metadata = + 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; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception return cryptor.decrypt({ data: encryptedData.slice(header.length), @@ -80,13 +82,16 @@ export default class CryptoModule { * Files handled differently in case of Legacy cryptor. * (as long as we support legacy need to check on default cryptor) */ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. if (this.defaultCryptor.identifier === '') return this.defaultCryptor.encryptFile(file, File); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Buffer) { return File.create({ name: file.name, mimeType: 'application/octet-stream', + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field data: await this.encrypt(file.data), }); @@ -94,19 +99,23 @@ export default class CryptoModule { } async decryptFile(file: PubnubFile, File: PubnubFile) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Buffer) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field - let header = CryptorHeader.tryParse(file.data); - let cryptor = this.getCryptor(header); + 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) */ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: cryptor will be there or unreachable due to exception if (cryptor.identifier === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); return File.create({ name: file.name, + // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: can not infer that PubNubFile has data field data: await this.decrypt(file.data), }); @@ -243,11 +252,11 @@ class CryptorHeaderV1 { pos++; if (this.identifier) header.set(encoder.encode(this.identifier), pos); pos += CryptorHeaderV1.IDENTIFIER_LENGTH; - let metadata_size = this.metadataLength; - if (metadata_size < 255) { - header[pos] = metadata_size; + const metadataSize = this.metadataLength; + if (metadataSize < 255) { + header[pos] = metadataSize; } else { - header.set([255, metadata_size >> 8, metadata_size & 0xff], pos); + header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); } return header; } diff --git a/src/crypto/modules/web.js b/src/crypto/modules/web.js index 44e419f4d..31cabdd2b 100644 --- a/src/crypto/modules/web.js +++ b/src/crypto/modules/web.js @@ -98,9 +98,8 @@ export default class WebCryptography { async decryptArrayBuffer(key, ciphertext) { const abIv = ciphertext.slice(0, 16); - - const data = await crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16)); - return data; + const data = await crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16)); + return data; } async encryptString(key, plaintext) { From 36afc90d2fe8c4c21456057b8853b8d390c1a66c Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:45:12 +0530 Subject: [PATCH 10/38] let vs const --- src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 742235f13..baabaef7b 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -147,7 +147,7 @@ export default class CryptoModule { } if (file.data instanceof Readable) { - let stream = file.data; + const stream = file.data; return new Promise((resolve) => { stream.on('readable', () => resolve(this.onStreamReadable(stream, file, File))); }); @@ -243,12 +243,12 @@ class CryptorHeader { } static tryGetMetadataSizeFromStream(stream: NodeJS.ReadableStream) { - let sizeBuf = stream.read(1); + const sizeBuf = stream.read(1); if (sizeBuf && (sizeBuf[0] as number) < 255) { return sizeBuf[0] as number; } if ((sizeBuf[0] as number) === 255) { - let nextBuf = stream.read(2); + 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); } From 9d43d8dbd5634a6434d9ef21a12089450ce67c52 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:49:43 +0530 Subject: [PATCH 11/38] and some more ts not wanting me to specific about trivials --- src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts index b817a0812..289e5c5fd 100644 --- a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts @@ -3,7 +3,7 @@ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypt import { ICryptor, EncryptedDataType, EncryptedStream } from './ICryptor'; export default class AesCbcCryptor implements ICryptor { - static BLOCK_SIZE: number = 16; + static BLOCK_SIZE = 16; cipherKey: string; constructor(configuration: { cipherKey: string }) { From 3e1d47f89b5ffd92b7c5708d2cb386e1a00df8b0 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 25 Sep 2023 11:52:48 +0530 Subject: [PATCH 12/38] access modfiers --- .../modules/NodeCryptoModule/nodeCryptoModule.ts | 12 ++++++------ .../modules/WebCryptoModule/webCryptoModule.ts | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index baabaef7b..6378a9b37 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -43,11 +43,11 @@ export default class CryptoModule { return new this({ default: defaultCryptor }); } - getAllCryptors() { + private getAllCryptors() { return [this.defaultCryptor, ...this.cryptors]; } - getLegacyCryptor() { + private getLegacyCryptor() { return this.getAllCryptors().find((c) => c.identifier === ''); } @@ -154,7 +154,7 @@ export default class CryptoModule { } } - async onStreamReadable(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { + private async onStreamReadable(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { stream.removeAllListeners('readable'); const magicBytes = stream.read(4); @@ -175,7 +175,7 @@ export default class CryptoModule { }); } - async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { + private async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { const cryptor = this.getLegacyCryptor(); if (cryptor) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -192,7 +192,7 @@ export default class CryptoModule { } } - getCryptor(header: CryptorHeader) { + private getCryptor(header: CryptorHeader) { if (header === '') { const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); if (cryptor) return cryptor; @@ -202,7 +202,7 @@ export default class CryptoModule { } } - getCryptorFromId(id: string) { + private getCryptorFromId(id: string) { const cryptor = this.getAllCryptors().find((c) => id === c.identifier); if (cryptor) { return cryptor; diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index ec7f11386..96486b95f 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -41,7 +41,7 @@ export default class CryptoModule { return new this({ default: defaultCryptor }); } - getAllCryptors() { + private getAllCryptors() { return [this.defaultCryptor, ...this.cryptors]; } @@ -122,7 +122,7 @@ export default class CryptoModule { } } - getCryptor(header: string | CryptorHeaderV1) { + private getCryptor(header: string | CryptorHeaderV1) { if (header === '') { const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); if (cryptor) return cryptor; @@ -132,7 +132,7 @@ export default class CryptoModule { } } - getCryptorFromId(id: string) { + private getCryptorFromId(id: string) { const cryptor = this.getAllCryptors().find((c) => id === c.identifier); if (cryptor) { return cryptor; @@ -140,7 +140,7 @@ export default class CryptoModule { throw Error('unknown cryptor'); } - concatArrayBuffer(ab1: ArrayBuffer, ab2: ArrayBuffer) { + private concatArrayBuffer(ab1: ArrayBuffer, ab2: ArrayBuffer) { const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); tmp.set(new Uint8Array(ab1), 0); From efaea51a2b2085968d5ac985b9990a016cb639b8 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 26 Sep 2023 12:45:10 +0530 Subject: [PATCH 13/38] refactor-1 --- .../NodeCryptoModule/NodeCryptoModule.js | 32 +++++++------- .../WebCryptoModule/webCryptoModule.js | 22 +++++----- .../modules/NodeCryptoModule/legacyCryptor.ts | 4 +- .../NodeCryptoModule/nodeCryptoModule.ts | 42 +++++++++---------- .../WebCryptoModule/webCryptoModule.ts | 25 +++++------ .../steps/cryptoModule/cryptoModule.ts | 11 ++--- 6 files changed, 67 insertions(+), 69 deletions(-) diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 7b43de9db..77e8b69c0 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -64,10 +64,13 @@ 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 endpoint_1 = require("../../../core/components/endpoint"); 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; @@ -103,7 +106,7 @@ var CryptoModule = /** @class */ (function () { var encrypted, header, headerData, pos; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(data)]; + case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(Buffer.from(data))]; case 1: encrypted = _a.sent(); if (!encrypted.metadata) @@ -126,7 +129,6 @@ var CryptoModule = /** @class */ (function () { return __awaiter(this, void 0, void 0, function () { var encryptedData, header, cryptor, metadata; return __generator(this, function (_a) { - encryptedData = null; encryptedData = Buffer.from(data); header = CryptorHeader.tryParse(encryptedData); cryptor = this.getCryptor(header); @@ -302,7 +304,7 @@ var CryptoModule = /** @class */ (function () { CryptoModule.LEGACY_IDENTIFIER = ''; return CryptoModule; }()); -exports.default = CryptoModule; +exports.CryptoModule = CryptoModule; // CryptorHeader Utility var CryptorHeader = /** @class */ (function () { function CryptorHeader() { @@ -381,6 +383,7 @@ var CryptorHeader = /** @class */ (function () { CryptorHeader.SENTINEL = 'PNED'; CryptorHeader.LEGACY_IDENTIFIER = ''; CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; CryptorHeader.MAX_VERSION = 1; return CryptorHeader; }()); @@ -412,16 +415,16 @@ var CryptorHeaderV1 = /** @class */ (function () { }); Object.defineProperty(CryptorHeaderV1.prototype, "version", { get: function () { - return CryptorHeaderV1.VERSION; + return CryptorHeader.VERSION; }, enumerable: false, configurable: true }); Object.defineProperty(CryptorHeaderV1.prototype, "length", { get: function () { - return (CryptorHeaderV1.SENTINEL.length + + return (CryptorHeader.SENTINEL.length + 1 + - CryptorHeaderV1.IDENTIFIER_LENGTH + + CryptorHeader.IDENTIFIER_LENGTH + (this.metadataLength < 255 ? 1 : 3) + this.metadataLength); }, @@ -432,27 +435,24 @@ var CryptorHeaderV1 = /** @class */ (function () { get: function () { var pos = 0; var header = new Uint8Array(this.length); - header.set(Buffer.from(CryptorHeaderV1.SENTINEL)); - pos += CryptorHeaderV1.SENTINEL.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 += CryptorHeaderV1.IDENTIFIER_LENGTH; - var metadataSize = this.metadataLength; - if (metadataSize < 255) { - header[pos] = metadataSize; + pos += CryptorHeader.IDENTIFIER_LENGTH; + var metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; } else { - header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); } return header; }, enumerable: false, configurable: true }); - CryptorHeaderV1.IDENTIFIER_LENGTH = 4; - CryptorHeaderV1.SENTINEL = 'PNED'; - CryptorHeaderV1.VERSION = 1; return CryptorHeaderV1; }()); diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index 9adcd3555..52ba4848a 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -276,6 +276,7 @@ var CryptorHeader = /** @class */ (function () { CryptorHeader.SENTINEL = 'PNED'; CryptorHeader.LEGACY_IDENTIFIER = ''; CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; CryptorHeader.MAX_VERSION = 1; return CryptorHeader; }()); @@ -307,16 +308,16 @@ var CryptorHeaderV1 = /** @class */ (function () { }); Object.defineProperty(CryptorHeaderV1.prototype, "version", { get: function () { - return CryptorHeaderV1.VERSION; + return CryptorHeader.VERSION; }, enumerable: false, configurable: true }); Object.defineProperty(CryptorHeaderV1.prototype, "length", { get: function () { - return (CryptorHeaderV1.SENTINEL.length + + return (CryptorHeader.SENTINEL.length + 1 + - CryptorHeaderV1.IDENTIFIER_LENGTH + + CryptorHeader.IDENTIFIER_LENGTH + (this.metadataLength < 255 ? 1 : 3) + this.metadataLength); }, @@ -328,19 +329,19 @@ var CryptorHeaderV1 = /** @class */ (function () { var pos = 0; var header = new Uint8Array(this.length); var encoder = new TextEncoder(); - header.set(encoder.encode(CryptorHeaderV1.SENTINEL)); - pos += CryptorHeaderV1.SENTINEL.length; + 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 += CryptorHeaderV1.IDENTIFIER_LENGTH; - var metadataSize = this.metadataLength; - if (metadataSize < 255) { - header[pos] = metadataSize; + pos += CryptorHeader.IDENTIFIER_LENGTH; + var metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; } else { - header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); } return header; }, @@ -349,6 +350,5 @@ var CryptorHeaderV1 = /** @class */ (function () { }); CryptorHeaderV1.IDENTIFIER_LENGTH = 4; CryptorHeaderV1.SENTINEL = 'PNED'; - CryptorHeaderV1.VERSION = 1; return CryptorHeaderV1; }()); diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts index c6a6f7f7d..20c5b14aa 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -1,7 +1,7 @@ import Crypto from '../../../core/components/cryptography/index'; import FileCryptor from '../node'; import { EncryptedDataType } from './ICryptor'; -import { ILegacyCryptor, ArrayBufferLike, PubnubFile } from './ILegacyCryptor'; +import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; export default class LegacyCryptor implements ILegacyCryptor { config; @@ -18,7 +18,7 @@ export default class LegacyCryptor implements ILegacyCryptor { get identifier() { return ''; } - async encrypt(data: ArrayBufferLike) { + async encrypt(data: ArrayBuffer) { return { data: this.cryptor.encrypt(data), metadata: null, diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 6378a9b37..963ad48b7 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -5,6 +5,8 @@ import AesCbcCryptor from './aesCbcCryptor'; import { ICryptor } from './ICryptor'; import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; +export { LegacyCryptor, AesCbcCryptor }; + type CryptorType = ICryptor | ILegacyCryptor; type CryptoModuleConfiguration = { @@ -12,7 +14,7 @@ type CryptoModuleConfiguration = { cryptors?: Array; }; -export default class CryptoModule { +export class CryptoModule { static LEGACY_IDENTIFIER = ''; defaultCryptor: CryptorType; @@ -32,7 +34,7 @@ export default class CryptoModule { }); } - static aesCbcCryptoModule(config: { cipherKey: { cipherKey: string } }) { + static aesCbcCryptoModule(config: any) { return new this({ default: new AesCbcCryptor(config.cipherKey), cryptors: [new LegacyCryptor({ config })], @@ -51,8 +53,8 @@ export default class CryptoModule { return this.getAllCryptors().find((c) => c.identifier === ''); } - async encrypt(data: Buffer) { - const encrypted = await this.defaultCryptor.encrypt(data); + async encrypt(data: ArrayBuffer) { + const encrypted = await this.defaultCryptor.encrypt(Buffer.from(data)); if (!encrypted.metadata) return encrypted.data; const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); @@ -68,10 +70,8 @@ export default class CryptoModule { return Buffer.concat([headerData, encrypted.data]); } - async decrypt(data: Buffer) { - let encryptedData = null; - encryptedData = Buffer.from(data); - + async decrypt(data: ArrayBuffer) { + const encryptedData = Buffer.from(data); const header = CryptorHeader.tryParse(encryptedData); const cryptor = this.getCryptor(header); const metadata = @@ -216,6 +216,7 @@ class CryptorHeader { static SENTINEL = 'PNED'; static LEGACY_IDENTIFIER = ''; static IDENTIFIER_LENGTH = 4; + static VERSION = 1; static MAX_VERSION = 1; static from(id: string, metadata: Buffer) { @@ -291,11 +292,6 @@ class CryptorHeader { // v1 CryptorHeader class CryptorHeaderV1 { - static IDENTIFIER_LENGTH = 4; - - static SENTINEL = 'PNED'; - static VERSION = 1; - _identifier; _metadataLength; @@ -321,14 +317,14 @@ class CryptorHeaderV1 { } get version() { - return CryptorHeaderV1.VERSION; + return CryptorHeader.VERSION; } get length() { return ( - CryptorHeaderV1.SENTINEL.length + + CryptorHeader.SENTINEL.length + 1 + - CryptorHeaderV1.IDENTIFIER_LENGTH + + CryptorHeader.IDENTIFIER_LENGTH + (this.metadataLength < 255 ? 1 : 3) + this.metadataLength ); @@ -337,17 +333,17 @@ class CryptorHeaderV1 { get data() { let pos = 0; const header = new Uint8Array(this.length); - header.set(Buffer.from(CryptorHeaderV1.SENTINEL)); - pos += CryptorHeaderV1.SENTINEL.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 += CryptorHeaderV1.IDENTIFIER_LENGTH; - const metadataSize = this.metadataLength; - if (metadataSize < 255) { - header[pos] = metadataSize; + pos += CryptorHeader.IDENTIFIER_LENGTH; + const metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; } else { - header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); } return header; } diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index 96486b95f..02b48060c 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -30,7 +30,7 @@ export default class CryptoModule { }); } - static aesCbcCryptoModule(config: { cipherKey: { cipherKey: any } }) { + static aesCbcCryptoModule(config: any) { return new this({ default: new AesCbcCryptor(config.cipherKey), cryptors: [new LegacyCryptor({ config })], @@ -155,6 +155,7 @@ class CryptorHeader { static SENTINEL = 'PNED'; static LEGACY_IDENTIFIER = ''; static IDENTIFIER_LENGTH = 4; + static VERSION = 1; static MAX_VERSION = 1; static from(id: string, metadata: ArrayBuffer) { @@ -202,7 +203,7 @@ class CryptorHeaderV1 { static IDENTIFIER_LENGTH = 4; static SENTINEL = 'PNED'; - static VERSION = 1; + _identifier; _metadataLength; @@ -229,14 +230,14 @@ class CryptorHeaderV1 { } get version() { - return CryptorHeaderV1.VERSION; + return CryptorHeader.VERSION; } get length() { return ( - CryptorHeaderV1.SENTINEL.length + + CryptorHeader.SENTINEL.length + 1 + - CryptorHeaderV1.IDENTIFIER_LENGTH + + CryptorHeader.IDENTIFIER_LENGTH + (this.metadataLength < 255 ? 1 : 3) + this.metadataLength ); @@ -246,17 +247,17 @@ class CryptorHeaderV1 { let pos = 0; const header = new Uint8Array(this.length); const encoder = new TextEncoder(); - header.set(encoder.encode(CryptorHeaderV1.SENTINEL)); - pos += CryptorHeaderV1.SENTINEL.length; + 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 += CryptorHeaderV1.IDENTIFIER_LENGTH; - const metadataSize = this.metadataLength; - if (metadataSize < 255) { - header[pos] = metadataSize; + pos += CryptorHeader.IDENTIFIER_LENGTH; + const metadataLength = this.metadataLength; + if (metadataLength < 255) { + header[pos] = metadataLength; } else { - header.set([255, metadataSize >> 8, metadataSize & 0xff], pos); + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); } return header; } diff --git a/test/contract/steps/cryptoModule/cryptoModule.ts b/test/contract/steps/cryptoModule/cryptoModule.ts index 8a8f37785..c4193638c 100644 --- a/test/contract/steps/cryptoModule/cryptoModule.ts +++ b/test/contract/steps/cryptoModule/cryptoModule.ts @@ -1,11 +1,12 @@ -import { Given, When, Then, Before, After } from '@cucumber/cucumber'; +import { Given, When, Then, Before } from '@cucumber/cucumber'; import { expect } from 'chai'; -import { Blob } from 'buffer'; import fs from 'fs'; -import CryptoModule from '../../../../lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js'; -import AesCbcCryptor from '../../../../lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js'; -import LegacyCryptor from '../../../../lib/crypto/modules/NodeCryptoModule/legacyCryptor.js'; +import { + CryptoModule, + AesCbcCryptor, + LegacyCryptor, +} from '../../../../lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js'; Before(function () { this.grantPayload = {}; From a3f59305bf7533be687ad35ab87a9df60494273f Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 26 Sep 2023 12:50:39 +0530 Subject: [PATCH 14/38] lint, cleanup test --- src/crypto/modules/WebCryptoModule/webCryptoModule.ts | 1 - test/contract/steps/cryptoModule/cryptoModule.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index 02b48060c..61da1ac54 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -204,7 +204,6 @@ class CryptorHeaderV1 { static SENTINEL = 'PNED'; - _identifier; _metadataLength; diff --git a/test/contract/steps/cryptoModule/cryptoModule.ts b/test/contract/steps/cryptoModule/cryptoModule.ts index c4193638c..787123ed6 100644 --- a/test/contract/steps/cryptoModule/cryptoModule.ts +++ b/test/contract/steps/cryptoModule/cryptoModule.ts @@ -9,7 +9,6 @@ import { } from '../../../../lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js'; Before(function () { - this.grantPayload = {}; this.useRandomIVs = true; }); From 7be4f3965fe358103e45cf4de7843ad4e58c91f5 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 26 Sep 2023 13:58:59 +0530 Subject: [PATCH 15/38] refactor - 2 --- .../modules/NodeCryptoModule/nodeCryptoModule.ts | 14 ++++++++------ .../modules/WebCryptoModule/webCryptoModule.ts | 14 ++++++++------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 963ad48b7..e93fa1fd4 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -277,16 +277,18 @@ class CryptorHeader { } else { throw new PubNubError('decryption error'); } - let headerSize = null; - if (encryptedData.length > pos + 1) { - headerSize = encryptedData[pos]; + let metadataLength = null; + if (encryptedData.length >= pos + 1) { + metadataLength = encryptedData[pos]; + } else { + throw new PubNubError('decryption error'); } pos += 1; - if (headerSize === 255 && encryptedData.length >= pos + 2) { - headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce((acc, val) => (acc << 8) + val, 0); + 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'), headerSize!); + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); } } diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index 61da1ac54..06ae1bbf0 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -185,16 +185,18 @@ class CryptorHeader { } else { throw new PubNubError('decryption error'); } - let headerSize = null; - if (encryptedData.byteLength > pos + 1) { - headerSize = (encryptedData as Uint8Array)[pos]; + let metadataLength = null; + if (encryptedData.byteLength >= pos + 1) { + metadataLength = (encryptedData as Uint8Array)[pos]; + } else { + throw new PubNubError('decryption error'); } pos += 1; - if (headerSize === 255 && encryptedData.byteLength >= pos + 2) { - headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce((acc, val) => (acc << 8) + val, 0); + 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(identifier.toString('utf8'), headerSize!); + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); } } From 3e9c7218d457a3e67d47f2023f8053594ce1555b Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 26 Sep 2023 17:14:38 +0530 Subject: [PATCH 16/38] code cleanup in stream encryption with new cryptor --- .../NodeCryptoModule/NodeCryptoModule.js | 58 ++++++++++--------- .../NodeCryptoModule/nodeCryptoModule.ts | 6 +- 2 files changed, 33 insertions(+), 31 deletions(-) diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 77e8b69c0..460c8e19c 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -168,29 +168,28 @@ var CryptoModule = /** @class */ (function () { _c.data = _d.sent(), _c)])]; case 2: - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field - if (file.data instanceof stream_1.Readable) { - encryptedStream = this.defaultCryptor.encryptStream(file.data); - 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.data.pipe(output); - return [2 /*return*/, File.create({ - name: file.name, - mimeType: 'application/octet-stream', - stream: output, - })]; + if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 4]; + return [4 /*yield*/, this.defaultCryptor.encryptStream(file.data)]; + case 3: + encryptedStream = _d.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); } - return [2 /*return*/]; + 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 4: return [2 /*return*/]; } }); }); @@ -369,16 +368,19 @@ var CryptorHeader = /** @class */ (function () { else { throw new endpoint_1.PubNubError('decryption error'); } - var headerSize = null; - if (encryptedData.length > pos + 1) { - headerSize = encryptedData[pos]; + var metadataLength = null; + if (encryptedData.length >= pos + 1) { + metadataLength = encryptedData[pos]; + } + else { + throw new endpoint_1.PubNubError('decryption error'); } pos += 1; - if (headerSize === 255 && encryptedData.length >= pos + 2) { - headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + 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'), headerSize); + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); }; CryptorHeader.SENTINEL = 'PNED'; CryptorHeader.LEGACY_IDENTIFIER = ''; diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index e93fa1fd4..1937bd074 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -106,8 +106,8 @@ export class CryptoModule { if (file.data instanceof Readable) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. - const encryptedStream = this.defaultCryptor.encryptStream(file.data); - const header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); + 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; @@ -120,7 +120,7 @@ export class CryptoModule { const output = new PassThrough(); output.write(payload); - encryptedStream.data.pipe(output); + encryptedStream.stream.pipe(output); return File.create({ name: file.name, mimeType: 'application/octet-stream', From 671848981b6e3dcde683e5e118b1c9696b204b5b Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 26 Sep 2023 17:19:05 +0530 Subject: [PATCH 17/38] fix: lint issue. --- src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 1937bd074..c3da9aaa6 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -105,8 +105,8 @@ export class CryptoModule { //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Readable) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. - const encryptedStream = await(this.defaultCryptor as ICryptor).encryptStream(file.data); + //@ts-ignore: PubNubFile as value. + 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); From 230af9104ef07946f26e5360a1622c0ef313c669 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 26 Sep 2023 18:01:57 +0530 Subject: [PATCH 18/38] refactor: eliminate ts-ignores by defining file reated types --- .../NodeCryptoModule/ILegacyCryptor.ts | 19 +++++++--- .../modules/NodeCryptoModule/legacyCryptor.ts | 8 ++--- .../NodeCryptoModule/nodeCryptoModule.ts | 29 +++++---------- .../modules/WebCryptoModule/ICryptor.ts | 8 ++--- .../modules/WebCryptoModule/ILegacyCryptor.ts | 18 +++++++--- .../modules/WebCryptoModule/legacyCryptor.ts | 13 +++---- .../WebCryptoModule/webCryptoModule.ts | 36 ++++++------------- 7 files changed, 61 insertions(+), 70 deletions(-) diff --git a/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts index 5dfe4c31e..0869a6b06 100644 --- a/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts @@ -1,13 +1,22 @@ import { EncryptedDataType } from './ICryptor'; -import PubNubFile from '../../../file/modules/node'; -export type PubnubFile = typeof PubNubFile; -export type ArrayBufferLike = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | DataView | BufferSource; +export type PubNubFileType = { + stream: NodeJS.ReadStream; + data: NodeJS.ReadStream | Buffer; + name: string; + mimeType: string; -export interface ILegacyCryptor { + create(config: any): PubNubFileType; + + toBuffer(): Buffer; + toArrayBuffer(): ArrayBuffer; + toString(): string; +}; + +export interface ILegacyCryptor { get identifier(): string; - encrypt(data: ArrayBufferLike): Promise; + encrypt(data: ArrayBuffer): Promise; decrypt(data: EncryptedDataType): Promise; encryptFile(file: T, File: T): Promise; diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts index 20c5b14aa..f2b4c3339 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -1,9 +1,9 @@ import Crypto from '../../../core/components/cryptography/index'; import FileCryptor from '../node'; import { EncryptedDataType } from './ICryptor'; -import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; -export default class LegacyCryptor implements ILegacyCryptor { +export default class LegacyCryptor implements ILegacyCryptor { config; cryptor; @@ -29,11 +29,11 @@ export default class LegacyCryptor implements ILegacyCryptor { return this.cryptor.decrypt(encryptedData.data.toString()); } - async encryptFile(file: PubnubFile, File: PubnubFile) { + async encryptFile(file: PubNubFileType, File: PubNubFileType) { return this.fileCryptor.encryptFile(this.config.cipherKey, file, File); } - async decryptFile(file: PubnubFile, File: PubnubFile) { + 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 index c3da9aaa6..a8fcdd839 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -3,11 +3,11 @@ import { PubNubError } from '../../../core/components/endpoint'; import LegacyCryptor from './legacyCryptor'; import AesCbcCryptor from './aesCbcCryptor'; import { ICryptor } from './ICryptor'; -import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; export { LegacyCryptor, AesCbcCryptor }; -type CryptorType = ICryptor | ILegacyCryptor; +type CryptorType = ICryptor | ILegacyCryptor; type CryptoModuleConfiguration = { default: CryptorType; @@ -84,28 +84,20 @@ export class CryptoModule { }); } - async encryptFile(file: PubnubFile, File: PubnubFile) { + 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 instanceof LegacyCryptor) return this.defaultCryptor.encryptFile(file, File); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Buffer) { return File.create({ name: file.name, mimeType: 'application/octet-stream', - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field data: await this.encrypt(file.data!), }); } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field if (file.data instanceof Readable) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: PubNubFile as value. const encryptedStream = await (this.defaultCryptor as ICryptor).encryptStream(file.data); const header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata!); @@ -129,7 +121,7 @@ export class CryptoModule { } } - async decryptFile(file: any, File: PubnubFile) { + async decryptFile(file: PubNubFileType, File: PubNubFileType) { if (file?.data instanceof Buffer) { const header = CryptorHeader.tryParse(file.data); const cryptor = this.getCryptor(header); @@ -137,9 +129,8 @@ export class CryptoModule { * If It's legacyone then redirect it. * (as long as we support legacy need to check on instance type) */ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception - if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) + return (cryptor as ILegacyCryptor).decryptFile(file, File); return File.create({ name: file.name, data: await this.decrypt(file?.data), @@ -154,7 +145,7 @@ export class CryptoModule { } } - private async onStreamReadable(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { + private async onStreamReadable(stream: NodeJS.ReadableStream, file: PubNubFileType, File: PubNubFileType) { stream.removeAllListeners('readable'); const magicBytes = stream.read(4); @@ -175,12 +166,10 @@ export class CryptoModule { }); } - private async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubnubFile, File: PubnubFile) { + private async decryptLegacyFileStream(stream: NodeJS.ReadableStream, file: PubNubFileType, File: PubNubFileType) { const cryptor = this.getLegacyCryptor(); if (cryptor) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception - return cryptor.decryptFile( + return (cryptor as ILegacyCryptor).decryptFile( File.create({ name: file.name, stream: stream, diff --git a/src/crypto/modules/WebCryptoModule/ICryptor.ts b/src/crypto/modules/WebCryptoModule/ICryptor.ts index 7d9ef08d5..57eaf5322 100644 --- a/src/crypto/modules/WebCryptoModule/ICryptor.ts +++ b/src/crypto/modules/WebCryptoModule/ICryptor.ts @@ -1,10 +1,10 @@ export type EncryptedDataType = { - data: ArrayBufferLike; - metadata: ArrayBufferLike | null; + data: ArrayBuffer; + metadata: ArrayBuffer | null; }; export interface ICryptor { get identifier(): string; - encrypt(data: BufferSource): Promise; - decrypt(data: EncryptedDataType): Promise; + encrypt(data: ArrayBuffer): Promise; + decrypt(data: EncryptedDataType): Promise; } diff --git a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts index 608400162..2f434a079 100644 --- a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts @@ -1,12 +1,22 @@ import { EncryptedDataType } from './ICryptor'; -import PubNubFile from '../../../file/modules/web'; -export type PubnubFile = typeof PubNubFile; +export type PubNubFileType = { + data: Buffer; + name: string; + mimeType: string; -export interface ILegacyCryptor { + create(config: any): PubNubFileType; + + toArrayBuffer(): ArrayBuffer; + toBlob(): Blob; + toString(): string; + toFile(): File; +}; + +export interface ILegacyCryptor { get identifier(): string; - encrypt(data: ArrayBufferLike): Promise; + encrypt(data: ArrayBuffer): Promise; decrypt(data: EncryptedDataType): Promise; encryptFile(file: T, File: T): Promise; diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts index b4c689faa..65300c791 100644 --- a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -1,12 +1,9 @@ import Crypto from '../../../core/components/cryptography/index'; -import PubNubFile from '../../../file/modules/web'; import FileCryptor from '../web'; import { EncryptedDataType } from './ICryptor'; -import { ILegacyCryptor } from './ILegacyCryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; -export type PubnubFile = typeof PubNubFile; - -export default class LegacyCryptor implements ILegacyCryptor { +export default class LegacyCryptor implements ILegacyCryptor { config; cryptor; @@ -21,7 +18,7 @@ export default class LegacyCryptor implements ILegacyCryptor { get identifier() { return ''; } - async encrypt(data: ArrayBufferLike) { + async encrypt(data: ArrayBuffer) { return { data: this.cryptor.encrypt(data) as ArrayBuffer, metadata: null, @@ -32,13 +29,13 @@ export default class LegacyCryptor implements ILegacyCryptor { return this.cryptor.decrypt(encryptedData.data); } - async encryptFile(file: PubnubFile, File: PubnubFile) { + 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: PubnubFile, File: PubnubFile) { + 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 index 06ae1bbf0..18e6fb63c 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -2,9 +2,9 @@ import { PubNubError } from '../../../core/components/endpoint'; import LegacyCryptor from './legacyCryptor'; import AesCbcCryptor from './aesCbcCryptor'; import { ICryptor } from './ICryptor'; -import { ILegacyCryptor, PubnubFile } from './ILegacyCryptor'; +import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; -type CryptorType = ICryptor | ILegacyCryptor; +type CryptorType = ICryptor | ILegacyCryptor; type CryptoModuleConfiguration = { default: CryptorType; @@ -69,54 +69,40 @@ export default class CryptoModule { header.length > 0 ? encryptedData.slice(header.length - (header as CryptorHeaderV1).metadataLength, header.length) : null; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception - return cryptor.decrypt({ + return cryptor?.decrypt({ data: encryptedData.slice(header.length), metadata: metadata, }); } - async encryptFile(file: PubnubFile, File: PubnubFile) { + async encryptFile(file: PubNubFileType, File: PubNubFileType) { /** * Files handled differently in case of Legacy cryptor. * (as long as we support legacy need to check on default cryptor) */ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. - if (this.defaultCryptor.identifier === '') return this.defaultCryptor.encryptFile(file, File); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field - if (file.data instanceof Buffer) { + if (this.defaultCryptor.identifier === '') + return (this.defaultCryptor as ILegacyCryptor).encryptFile(file, File); + if (file.data instanceof ArrayBuffer) { return File.create({ name: file.name, mimeType: 'application/octet-stream', - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field data: await this.encrypt(file.data), }); } } - async decryptFile(file: PubnubFile, File: PubnubFile) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field - if (file.data instanceof Buffer) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field + async decryptFile(file: PubNubFileType, File: PubNubFileType) { + if (file.data instanceof ArrayBuffer) { 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) */ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception - if (cryptor.identifier === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) + return (cryptor as ILegacyCryptor).decryptFile(file, File); return File.create({ name: file.name, - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field data: await this.decrypt(file.data), }); } From 3c041ba5834e6881e754eaf6d4408309e90e6640 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 12:39:29 +0530 Subject: [PATCH 19/38] * integration of crypto module * refactoring cryptoModule --- src/core/components/base64_codec.ts | 52 +++++++++++++++++ src/core/components/subscription_manager.js | 45 +++++++++++++-- src/core/endpoints/fetch_messages.js | 10 ++-- .../endpoints/file_upload/publish_file.js | 3 +- src/core/endpoints/history/get_history.js | 10 ++-- src/core/endpoints/publish.js | 8 +-- src/core/pubnub-common.js | 39 +++++++++++-- src/core/utils.js | 10 ++++ .../modules/NodeCryptoModule/ICryptor.ts | 6 +- .../NodeCryptoModule/ILegacyCryptor.ts | 6 +- .../modules/NodeCryptoModule/aesCbcCryptor.ts | 15 +++-- .../modules/NodeCryptoModule/legacyCryptor.ts | 10 ++-- .../NodeCryptoModule/nodeCryptoModule.ts | 57 ++++++++++--------- .../modules/WebCryptoModule/ICryptor.ts | 2 +- .../modules/WebCryptoModule/ILegacyCryptor.ts | 6 +- .../modules/WebCryptoModule/aesCbcCryptor.ts | 7 ++- .../modules/WebCryptoModule/legacyCryptor.ts | 7 ++- .../WebCryptoModule/webCryptoModule.ts | 35 ++++++------ src/crypto/modules/node.js | 4 +- src/crypto/modules/web.js | 8 ++- src/file/modules/node.js | 11 ++-- src/node/index.ts | 9 ++- src/web/index.js | 8 +++ .../steps/cryptoModule/cryptoModule.ts | 38 +++++++++---- 24 files changed, 293 insertions(+), 113 deletions(-) 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/subscription_manager.js b/src/core/components/subscription_manager.js index 1e0e40165..8ca18a2b9 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,19 @@ 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; + if (console && console.log) { + console.log('decryption error', e.message); + } + } + if (decryptedPayload !== null) { msgPayload = decryptedPayload; } } @@ -727,8 +744,24 @@ 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; + // eslint-disable-next-line + if (console && console.log) { + console.log('decryption error', e.message); //eslint-disable-line + } + } + 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..c4f232452 100644 --- a/src/core/endpoints/fetch_messages.js +++ b/src/core/endpoints/fetch_messages.js @@ -11,12 +11,14 @@ import operationConstants from '../constants/operations'; import utils from '../utils'; function __processMessage(modules, message) { - const { config, crypto } = modules; - if (!config.cipherKey) return message; - + if (!modules.cryptoModule) return message; try { - return crypto.decrypt(message); + const decryptedData = modules.cryptoModule.decrypt(message); + const decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + return decryptedPayload; } catch (e) { + if (console && console.log) console.log('decryption error', e.message); return message; } } diff --git a/src/core/endpoints/file_upload/publish_file.js b/src/core/endpoints/file_upload/publish_file.js index 9f56f9ded..2a27ee199 100644 --- a/src/core/endpoints/file_upload/publish_file.js +++ b/src/core/endpoints/file_upload/publish_file.js @@ -8,7 +8,8 @@ const preparePayload = ({ crypto, config }, payload) => { let stringifiedPayload = JSON.stringify(payload); if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + const encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } diff --git a/src/core/endpoints/history/get_history.js b/src/core/endpoints/history/get_history.js index afa3c952e..51f2c901a 100644 --- a/src/core/endpoints/history/get_history.js +++ b/src/core/endpoints/history/get_history.js @@ -5,12 +5,14 @@ import operationConstants from '../../constants/operations'; import utils from '../../utils'; function __processMessage(modules, message) { - const { config, crypto } = modules; - if (!config.cipherKey) return message; - + if (!modules.cryptoModule) return message; try { - return crypto.decrypt(message); + const decryptedData = modules.cryptoModule.decrypt(message); + const decryptedPayload = + decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + return decryptedPayload; } catch (e) { + if (console && console.log) console.log('decryption error', e.message); return message; } } diff --git a/src/core/endpoints/publish.js b/src/core/endpoints/publish.js index 3bfc71d9f..8cec47a45 100644 --- a/src/core/endpoints/publish.js +++ b/src/core/endpoints/publish.js @@ -3,16 +3,16 @@ 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; } diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index 1c15e342c..0347ae5b9 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'; @@ -279,7 +280,7 @@ export default class { this._config = config; const crypto = new Crypto({ config }); // LEGACY - const { cryptography } = setup; + const { cryptography, cryptoModule } = setup; networking.init(config); @@ -300,12 +301,25 @@ export default class { tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, + cryptoModule: setup.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' && cryptoModule) { + file = key; + return cryptoModule.encryptFile(file, this.File); + } + return cryptography.encryptFile(key, file, this.File); + }; + this.decryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && cryptoModule) { + file = key; + return 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); @@ -341,6 +355,7 @@ export default class { config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), + cryptoModule: setup.cryptoModule, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); @@ -664,8 +679,22 @@ 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' && cryptoModule) { + const encrypted = 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 = cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? encode(decrypted) : decrypted; + } else { + return crypto.decrypt(data, key); + } + }; /* config */ this.getAuthKey = modules.config.getAuthKey.bind(modules.config); 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 index 387f07042..5e73cee31 100644 --- a/src/crypto/modules/NodeCryptoModule/ICryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/ICryptor.ts @@ -1,5 +1,5 @@ export type EncryptedDataType = { - data: Buffer; + data: Buffer | string; metadata: Buffer | null; }; @@ -11,8 +11,8 @@ export type EncryptedStream = { export interface ICryptor { get identifier(): string; - encrypt(data: BufferSource): Promise; - decrypt(data: EncryptedDataType): Promise; + 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 index 0869a6b06..9a63aa455 100644 --- a/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/ILegacyCryptor.ts @@ -5,19 +5,21 @@ export type PubNubFileType = { 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: ArrayBuffer): Promise; - decrypt(data: EncryptedDataType): Promise; + 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 index 289e5c5fd..fc84987b2 100644 --- a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts @@ -28,11 +28,12 @@ export default class AesCbcCryptor implements ICryptor { return Buffer.from(sha.digest()); } - async encrypt(data: Buffer) { + encrypt(data: ArrayBuffer | string) { const iv = this.getIv(); const key = this.getKey(); - - const bPlain = Buffer.from(data); + const plainData = data instanceof ArrayBuffer ? data : new TextEncoder().encode(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 { @@ -41,14 +42,18 @@ export default class AesCbcCryptor implements ICryptor { }; } - async decrypt(encryptedData: EncryptedDataType) { + 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 Buffer.concat([aes.update(encryptedData.data), aes.final()]); + return Uint8Array.from(Buffer.concat([aes.update(data), aes.final()])); } 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 { diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts index f2b4c3339..c8a28fc6b 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -1,4 +1,5 @@ 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'; @@ -14,19 +15,20 @@ export default class LegacyCryptor implements ILegacyCryptor { this.cryptor = new Crypto({ config }); this.fileCryptor = new FileCryptor(); } - get identifier() { return ''; } - async encrypt(data: ArrayBuffer) { + encrypt(data: string) { + if (data.length === 0) throw new Error('encryption error. empty content'); return { data: this.cryptor.encrypt(data), metadata: null, }; } - async decrypt(encryptedData: EncryptedDataType) { - return this.cryptor.decrypt(encryptedData.data.toString()); + 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) { diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index a8fcdd839..18acf5ab4 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -1,5 +1,5 @@ import { Readable, PassThrough } from 'stream'; -import { PubNubError } from '../../../core/components/endpoint'; +import { decode } from '../../../core/components/base64_codec'; import LegacyCryptor from './legacyCryptor'; import AesCbcCryptor from './aesCbcCryptor'; import { ICryptor } from './ICryptor'; @@ -40,7 +40,6 @@ export class CryptoModule { cryptors: [new LegacyCryptor({ config })], }); } - static withDefaultCryptor(defaultCryptor: CryptorType) { return new this({ default: defaultCryptor }); } @@ -53,8 +52,8 @@ export class CryptoModule { return this.getAllCryptors().find((c) => c.identifier === ''); } - async encrypt(data: ArrayBuffer) { - const encrypted = await this.defaultCryptor.encrypt(Buffer.from(data)); + 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); @@ -62,22 +61,20 @@ export class CryptoModule { const headerData = new Uint8Array(header!.length); let pos = 0; headerData.set(header!.data, pos); - pos += header!.length; - if (encrypted.metadata) { - pos -= encrypted.metadata.length; - headerData.set(encrypted.metadata, pos); - } - return Buffer.concat([headerData, encrypted.data]); + pos = header!.length - encrypted.metadata.length; + headerData.set(encrypted.metadata, pos); + return Buffer.concat([headerData, Buffer.from(encrypted.data)]).buffer; } - async decrypt(data: ArrayBuffer) { - const encryptedData = Buffer.from(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, @@ -89,18 +86,19 @@ export class CryptoModule { * Files handled differently in case of Legacy cryptor. * (as long as we support legacy need to check on intsance type) */ - if (this.defaultCryptor instanceof LegacyCryptor) return this.defaultCryptor.encryptFile(file, File); + 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: await this.encrypt(file.data!), + 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); @@ -109,7 +107,6 @@ export class CryptoModule { pos -= encryptedStream.metadata.length; payload.set(encryptedStream.metadata, pos); } - const output = new PassThrough(); output.write(payload); encryptedStream.stream.pipe(output); @@ -133,7 +130,7 @@ export class CryptoModule { return (cryptor as ILegacyCryptor).decryptFile(file, File); return File.create({ name: file.name, - data: await this.decrypt(file?.data), + data: Buffer.from(this.decrypt(file?.data) as ArrayBuffer), }); } @@ -147,9 +144,9 @@ export class CryptoModule { 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); } @@ -158,7 +155,8 @@ export class CryptoModule { 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', @@ -167,6 +165,7 @@ export class CryptoModule { } 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( @@ -177,7 +176,7 @@ export class CryptoModule { File, ); } else { - throw new PubNubError('unknown cryptor'); + throw new Error('unknown cryptor error'); } } @@ -185,7 +184,7 @@ export class CryptoModule { if (header === '') { const cryptor = this.getAllCryptors().find((c) => c.identifier === ''); if (cryptor) return cryptor; - throw new Error('unknown cryptor'); + throw new Error('unknown cryptor error'); } else if (header instanceof CryptorHeaderV1) { return this.getCryptorFromId(header.identifier); } @@ -196,7 +195,7 @@ export class CryptoModule { if (cryptor) { return cryptor; } - throw Error('unknown cryptor'); + throw new Error('unknown cryptor error'); } } @@ -207,6 +206,7 @@ class CryptorHeader { 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; @@ -220,13 +220,13 @@ class CryptorHeader { } static validateVersion(data: number) { - if (data && data > CryptorHeader.MAX_VERSION) throw new PubNubError('decryption error'); + 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 PubNubError('unknown cryptor'); + throw new Error('unknown cryptor error. decryption failed'); } else { return data.toString('utf8'); } @@ -243,6 +243,7 @@ class CryptorHeader { 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 = ''; @@ -255,22 +256,22 @@ class CryptorHeader { if (encryptedData.length >= 5) { version = encryptedData[4]; } else { - throw new PubNubError('decryption error'); + throw new Error('decryption error. invalid header version'); } - if (version > CryptorHeader.MAX_VERSION) throw new PubNubError('unknown cryptor'); + 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 PubNubError('decryption error'); + throw new Error('decryption error. invalid crypto identifier'); } let metadataLength = null; if (encryptedData.length >= pos + 1) { metadataLength = encryptedData[pos]; } else { - throw new PubNubError('decryption error'); + throw new Error('decryption error. invalid metadata length'); } pos += 1; if (metadataLength === 255 && encryptedData.length >= pos + 2) { diff --git a/src/crypto/modules/WebCryptoModule/ICryptor.ts b/src/crypto/modules/WebCryptoModule/ICryptor.ts index 57eaf5322..ebaf26b99 100644 --- a/src/crypto/modules/WebCryptoModule/ICryptor.ts +++ b/src/crypto/modules/WebCryptoModule/ICryptor.ts @@ -5,6 +5,6 @@ export type EncryptedDataType = { export interface ICryptor { get identifier(): string; - encrypt(data: ArrayBuffer): Promise; + encrypt(data: ArrayBuffer | string): Promise; decrypt(data: EncryptedDataType): Promise; } diff --git a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts index 2f434a079..9538fa18a 100644 --- a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts @@ -1,7 +1,7 @@ import { EncryptedDataType } from './ICryptor'; export type PubNubFileType = { - data: Buffer; + data: ArrayBuffer; name: string; mimeType: string; @@ -16,8 +16,8 @@ export type PubNubFileType = { export interface ILegacyCryptor { get identifier(): string; - encrypt(data: ArrayBuffer): Promise; - decrypt(data: EncryptedDataType): Promise; + 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 index 03ef53b43..74dfb8796 100644 --- a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -29,13 +29,14 @@ export default class AesCbcCryptor implements ICryptor { return crypto.subtle.importKey('raw', abHash, 'AES-CBC', true, ['encrypt', 'decrypt']); } - async encrypt(data: BufferSource) { + async encrypt(data: ArrayBuffer | string) { + const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; + if (dataBytes.byteLength === 0) throw new Error('encryption error. empty content'); const abIv = this._getIv(); const key = await this._getKey(); - return { metadata: abIv, - data: await crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, data), + data: await crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, dataBytes), }; } diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts index 65300c791..c0f62ce55 100644 --- a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -18,14 +18,15 @@ export default class LegacyCryptor implements ILegacyCryptor { get identifier() { return ''; } - async encrypt(data: ArrayBuffer) { + encrypt(data: ArrayBuffer | string) { + const stringData = typeof data === 'string' ? data : new TextDecoder().decode(data); return { - data: this.cryptor.encrypt(data) as ArrayBuffer, + data: this.cryptor.encrypt(stringData), metadata: null, }; } - async decrypt(encryptedData: EncryptedDataType) { + decrypt(encryptedData: EncryptedDataType) { return this.cryptor.decrypt(encryptedData.data); } diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index 18e6fb63c..b4e3f93ff 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -4,6 +4,8 @@ import AesCbcCryptor from './aesCbcCryptor'; import { ICryptor } from './ICryptor'; import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; +export { LegacyCryptor, AesCbcCryptor }; + type CryptorType = ICryptor | ILegacyCryptor; type CryptoModuleConfiguration = { @@ -11,7 +13,7 @@ type CryptoModuleConfiguration = { cryptors?: Array; }; -export default class CryptoModule { +export class CryptoModule { static LEGACY_IDENTIFIER = ''; defaultCryptor: CryptorType; cryptors: Array; @@ -45,31 +47,30 @@ export default class CryptoModule { return [this.defaultCryptor, ...this.cryptors]; } - async encrypt(data: ArrayBuffer) { + async encrypt(data: ArrayBuffer | string) { const encrypted = await this.defaultCryptor.encrypt(data); if (!encrypted.metadata) return encrypted.data; const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - const headerData = new Uint8Array((header as CryptorHeaderV1).length); + const headerData = new Uint8Array(header!.length); let pos = 0; - headerData.set((header as CryptorHeaderV1).data, pos); - pos += (header as CryptorHeaderV1).length; - if (encrypted.metadata) { - pos -= encrypted.metadata.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - } + headerData.set(header!.data, pos); + pos += header!.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); return this.concatArrayBuffer(headerData.buffer, encrypted.data); } - async decrypt(encryptedData: ArrayBuffer) { + async decrypt(data: ArrayBuffer | string) { + const encryptedData = typeof data === 'string' ? new TextEncoder().encode(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; - return cryptor?.decrypt({ + if (encryptedData.slice(header.length).byteLength <= 0) throw new Error('decryption error. empty content'); + return cryptor!.decrypt({ data: encryptedData.slice(header.length), metadata: metadata, }); @@ -80,7 +81,7 @@ export default class CryptoModule { * Files handled differently in case of Legacy cryptor. * (as long as we support legacy need to check on default cryptor) */ - if (this.defaultCryptor.identifier === '') + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return (this.defaultCryptor as ILegacyCryptor).encryptFile(file, File); if (file.data instanceof ArrayBuffer) { return File.create({ @@ -123,7 +124,7 @@ export default class CryptoModule { if (cryptor) { return cryptor; } - throw Error('unknown cryptor'); + throw Error('unknown cryptor error'); } private concatArrayBuffer(ab1: ArrayBuffer, ab2: ArrayBuffer) { @@ -160,22 +161,22 @@ class CryptorHeader { if (encryptedData.byteLength >= 5) { version = (encryptedData as Uint8Array)[4] as number; } else { - throw new PubNubError('decryption error'); + throw new Error('decryption error. invalid header version'); } - if (version > CryptorHeader.MAX_VERSION) throw new PubNubError('unknown cryptor'); + if (version > CryptorHeader.MAX_VERSION) throw new PubNubError('unknown cryptor error'); let identifier: any = ''; let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; if (encryptedData.byteLength >= pos) { identifier = encryptedData.slice(5, pos); } else { - throw new PubNubError('decryption error'); + throw new Error('decryption error. invalid crypto identifier'); } let metadataLength = null; if (encryptedData.byteLength >= pos + 1) { metadataLength = (encryptedData as Uint8Array)[pos]; } else { - throw new PubNubError('decryption error'); + throw new Error('decryption error. invalid metadata length'); } pos += 1; if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { diff --git a/src/crypto/modules/node.js b/src/crypto/modules/node.js index bf63cc427..11055962c 100644 --- a/src/crypto/modules/node.js +++ b/src/crypto/modules/node.js @@ -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,7 +120,7 @@ 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()]); diff --git a/src/crypto/modules/web.js b/src/crypto/modules/web.js index 31cabdd2b..90d0280c3 100644 --- a/src/crypto/modules/web.js +++ b/src/crypto/modules/web.js @@ -55,6 +55,7 @@ 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(); @@ -98,7 +99,12 @@ export default class WebCryptography { async decryptArrayBuffer(key, ciphertext) { const abIv = ciphertext.slice(0, 16); - const data = await 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; } 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/node/index.ts b/src/node/index.ts index 5d7b3cd73..b156d5810 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -8,7 +8,7 @@ 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 { constructor(setup: any) { setup.cbor = new Cbor((buffer: ArrayBuffer) => CborReader.decode(Buffer.from(buffer)), decode); @@ -27,6 +27,13 @@ export = class extends PubNubCore { setup.PubNubFile = PubNubFile; setup.cryptography = new NodeCryptography(); + if (setup.cipherKey) { + setup.cryptoModule = new CryptoModule({ + default: new LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), + cryptors: [new AesCbcCryptor({ cipherKey: setup.cipherKey })], + }); + } + if (!('ssl' in setup)) { setup.ssl = true; } diff --git a/src/web/index.js b/src/web/index.js index 52564ae17..3f4664eab 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) { @@ -40,6 +41,13 @@ export default class extends PubNubCore { setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); + if (setup.cipherKey) { + setup.cryptoModule = new CryptoModule({ + default: new LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), + cryptors: [new AesCbcCryptor({ cipherKey: setup.cipherKey })], + }); + } + super(setup); if (listenToBrowserNetworkEvents) { diff --git a/test/contract/steps/cryptoModule/cryptoModule.ts b/test/contract/steps/cryptoModule/cryptoModule.ts index 787123ed6..c7785b85d 100644 --- a/test/contract/steps/cryptoModule/cryptoModule.ts +++ b/test/contract/steps/cryptoModule/cryptoModule.ts @@ -30,6 +30,11 @@ Given('with {string} cipher key', function (cipherKey: string) { 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) { @@ -52,12 +57,6 @@ When('I decrypt {string} file', async function (fileName: string) { }); When('I decrypt {string} file as {string}', async function (fileName: string, format: string) { - this._initCryptor = (id: string) => { - return id === 'legacy' - ? new LegacyCryptor({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }) - : new AesCbcCryptor({ cipherKey: this.cipherKey }); - }; - if (this.defaultCryptorId && this.additionalCryptorId) { this.cryptoModule = new CryptoModule({ default: this._initCryptor(this.defaultCryptorId), @@ -76,7 +75,11 @@ When('I decrypt {string} file as {string}', async function (fileName: string, fo name: fileName, data: fs.readFileSync(this.getFilePath(fileName)), }); - this.binaryFileResult = await this.cryptoModule.decryptFile(encrypteFile, pubnub.File); + 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)); @@ -84,7 +87,11 @@ When('I decrypt {string} file as {string}', async function (fileName: string, fo name: fileName, stream: filestream, }); - this.streamFileResult = await this.cryptoModule.decryptFile(this.file, pubnub.File); + try { + this.streamFileResult = await this.cryptoModule.decryptFile(this.file, pubnub.File); + } catch (e: any) { + this.errorMessage = e?.message; + } } }); @@ -111,11 +118,12 @@ Then('Decrypted file content equal to the {string} file content', async function expect(this.binaryFileResult.data.equals(fs.readFileSync(this.getFilePath(sourceFile)))).to.be.true; }); -Then('I receive {string}', function (result: string) { +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(result).to.have.string(this.errorMessage); + expect(this.errorMessage).to.have.string(result); } }); @@ -140,8 +148,16 @@ When('I encrypt {string} file as {string}', async function (fileName: string, fo 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; } - this.encryptedFile = await this.cryptoModule.encryptFile(this.file, this.pubnub.File); }); Then('Successfully decrypt an encrypted file with legacy code', async function () { From 720b9ef76df42b522fad61d097e0611cb759525f Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 12:40:03 +0530 Subject: [PATCH 20/38] lib and dist --- dist/web/pubnub.js | 583 +++++++++++++++++- dist/web/pubnub.min.js | 4 +- lib/core/components/base64_codec.js | 42 +- lib/core/components/subscription_manager.js | 44 +- lib/core/endpoints/fetch_messages.js | 9 +- .../endpoints/file_upload/publish_file.js | 3 +- lib/core/endpoints/history/get_history.js | 9 +- lib/core/endpoints/publish.js | 7 +- lib/core/pubnub-common.js | 41 +- lib/core/utils.js | 9 + .../NodeCryptoModule/NodeCryptoModule.js | 179 +++--- .../modules/NodeCryptoModule/aesCbcCryptor.js | 38 +- .../modules/NodeCryptoModule/legacyCryptor.js | 22 +- .../modules/WebCryptoModule/aesCbcCryptor.js | 7 +- .../modules/WebCryptoModule/legacyCryptor.js | 19 +- .../WebCryptoModule/webCryptoModule.js | 66 +- lib/crypto/modules/node.js | 6 + lib/crypto/modules/web.js | 9 +- lib/file/modules/node.js | 9 +- lib/node/index.js | 7 + lib/web/index.js | 7 + 21 files changed, 880 insertions(+), 240 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 476b332b6..e99fdb340 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -841,6 +841,45 @@ } return data; } + function encode$2(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 */ /* @@ -1764,11 +1803,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, }; /* */ @@ -1795,7 +1843,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; @@ -1804,6 +1852,7 @@ this._subscribeEndpoint = subscribeEndpoint; this._getFileUrl = getFileUrl; this._crypto = crypto; + this._cryptoModule = cryptoModule; this._channels = {}; this._presenceChannels = {}; this._heartbeatChannels = {}; @@ -1819,6 +1868,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; @@ -2286,9 +2337,20 @@ 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; + if (console && console.log) { + console.log('decryption error', e.message); + } + } + if (decryptedPayload !== null) { msgPayload = decryptedPayload; } } @@ -2322,8 +2384,26 @@ 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; + // eslint-disable-next-line + if (console && console.log) { + console.log('decryption error', e.message); //eslint-disable-line + } + } + if (decryptedPayload != null) { + announce.message = decryptedPayload; + } + else { + announce.message = message.payload; + } } else { announce.message = message.payload; @@ -4623,10 +4703,11 @@ /** */ var preparePayload = function (_a, payload) { - var crypto = _a.crypto, config = _a.config; + _a.crypto; var config = _a.config; var stringifiedPayload = JSON.stringify(payload); if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; @@ -5996,10 +6077,10 @@ /* */ 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$2(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload; @@ -6135,13 +6216,16 @@ /* */ function __processMessage$1(modules, message) { - var config = modules.config, crypto = modules.crypto; - if (!config.cipherKey) + if (!modules.cryptoModule) return message; try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + return decryptedPayload; } catch (e) { + if (console && console.log) + console.log('decryption error', e.message); return message; } } @@ -6331,13 +6415,16 @@ /* */ function __processMessage(modules, message) { - var config = modules.config, crypto = modules.crypto; - if (!config.cipherKey) + if (!modules.cryptoModule) return message; try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + return decryptedPayload; } catch (e) { + if (console && console.log) + console.log('decryption error', e.message); return message; } } @@ -7367,7 +7454,7 @@ var config = new default_1$b({ setup: setup }); this._config = config; var crypto = new default_1$a({ config: config }); // LEGACY - var cryptography = setup.cryptography; + var cryptography = setup.cryptography, cryptoModule = setup.cryptoModule; networking.init(config); var tokenManager = new default_1$4(config, cbor); this._tokenManager = tokenManager; @@ -7383,10 +7470,23 @@ tokenManager: tokenManager, telemetryManager: telemetryManager, PubNubFile: setup.PubNubFile, + cryptoModule: setup.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' && cryptoModule) { + file = key; + return cryptoModule.encryptFile(file, this.File); + } + return cryptography.encryptFile(key, file, this.File); + }; + this.decryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && cryptoModule) { + file = key; + return 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); @@ -7417,6 +7517,7 @@ config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, + cryptoModule: setup.cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -7706,8 +7807,24 @@ 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' && cryptoModule) { + var encrypted = cryptoModule.encrypt(data); + return typeof encrypted === 'string' ? encrypted : encode$2(encrypted); + } + else { + return crypto.encrypt(data, key); + } + }; + this.decrypt = function (data, key) { + if (typeof key === 'undefined' && cryptoModule) { + var decrypted = cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? encode$2(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); @@ -9612,7 +9729,7 @@ } }; - var encode = function encode(str, defaultEncoder, charset, kind, format) { + var encode$1 = 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) { @@ -9734,7 +9851,7 @@ combine: combine, compact: compact, decode: decode, - encode: encode, + encode: encode$1, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, @@ -12542,7 +12659,10 @@ 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()]; @@ -12620,7 +12740,9 @@ switch (_a.label) { case 0: abIv = ciphertext.slice(0, 16); - return [4 /*yield*/, 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'); + 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]; @@ -12780,6 +12902,409 @@ _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) { + return this.cryptor.decrypt(encryptedData.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; + } + 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, 'AES-CBC', true, ['encrypt', 'decrypt'])]; + } + }); + }); + }; + AesCbcCryptor.prototype.encrypt = function (data) { + return __awaiter(this, void 0, void 0, function () { + var dataBytes, abIv, key; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + dataBytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; + if (dataBytes.byteLength === 0) + throw new Error('encryption error. empty content'); + abIv = this._getIv(); + return [4 /*yield*/, this._getKey()]; + case 1: + key = _b.sent(); + _a = { + metadata: abIv + }; + return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, dataBytes)]; + case 2: return [2 /*return*/, (_a.data = _b.sent(), + _a)]; + } + }); + }); + }; + AesCbcCryptor.prototype.decrypt = function (encryptedData) { + return __awaiter(this, void 0, void 0, function () { + var key, decryptedData; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this._getKey()]; + case 1: + key = _a.sent(); + return [4 /*yield*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)]; + case 2: + decryptedData = _a.sent(); + return [2 /*return*/, decryptedData]; + } + }); + }); + }; + 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 (_a) { + var config = _a.config; + return new this({ + default: new LegacyCryptor({ config: config }), + cryptors: [new AesCbcCryptor(config.cipherKey)], + }); + }; + CryptoModule.aesCbcCryptoModule = function (config) { + return new this({ + default: new AesCbcCryptor(config.cipherKey), + cryptors: [new LegacyCryptor({ config: config })], + }); + }; + 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) { + return __awaiter(this, void 0, void 0, function () { + var encrypted, header, headerData, pos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(data)]; + case 1: + encrypted = _a.sent(); + if (!encrypted.metadata) + return [2 /*return*/, encrypted.data]; + header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + headerData = new Uint8Array(header.length); + pos = 0; + headerData.set(header.data, pos); + pos += header.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + return [2 /*return*/, this.concatArrayBuffer(headerData.buffer, encrypted.data)]; + } + }); + }); + }; + CryptoModule.prototype.decrypt = function (data) { + return __awaiter(this, void 0, void 0, function () { + var encryptedData, header, cryptor, metadata; + return __generator(this, function (_a) { + encryptedData = typeof data === 'string' ? new TextEncoder().encode(data) : data; + header = CryptorHeader.tryParse(encryptedData); + cryptor = this.getCryptor(header); + 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 [2 /*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 _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on default cryptor) + */ + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) + return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; + if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; + _b = (_a = File).create; + _c = { + name: file.name, + mimeType: 'application/octet-stream' + }; + return [4 /*yield*/, this.encrypt(file.data)]; + case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + _c)])]; + case 2: return [2 /*return*/]; + } + }); + }); + }; + CryptoModule.prototype.decryptFile = function (file, File) { + return __awaiter(this, void 0, void 0, function () { + var header, cryptor, _a, _b; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; + 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)]; + _b = (_a = File).create; + _c = { + name: file.name + }; + return [4 /*yield*/, this.decrypt(file.data)]; + case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + _c)])]; + case 2: 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'); + } + 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.LEGACY_IDENTIFIER = ''; + 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 (encryptedData) { + var sentinel = ''; + var version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (sentinel.toString('utf8') !== 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 PubNubError('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(identifier.toString('utf8'), metadataLength); + }; + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + 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) { @@ -12808,6 +13333,12 @@ setup.cbor = new default_1$1(function (arrayBuffer) { return stringifyBufferKeys(CborReader.decode(arrayBuffer)); }, decode$1); setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); + if (setup.cipherKey) { + setup.cryptoModule = new CryptoModule({ + default: new LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), + cryptors: [new AesCbcCryptor({ cipherKey: setup.cipherKey })], + }); + } _this = _super.call(this, setup) || this; if (listenToBrowserNetworkEvents) { // mount network events. diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 51f1d8024..7ea58a6d8 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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 k;if(f<0)for(k=[];!h();)k.push(e());else for(k=new Array(f),o=0;o0&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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}var v,m,_,O,S,P=P||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=(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 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=P,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],O=e[i+13],S=e[i+14],P=e[i+15],w=t(w=a[0],E=a[1],T=a[2],k=a[3],u,7,c[0]),k=t(k,w,E,T,s,12,c[1]),T=t(T,k,w,E,l,17,c[2]),E=t(E,T,k,w,p,22,c[3]);w=t(w,E,T,k,f,7,c[4]),k=t(k,w,E,T,h,12,c[5]),T=t(T,k,w,E,d,17,c[6]),E=t(E,T,k,w,y,22,c[7]),w=t(w,E,T,k,g,7,c[8]),k=t(k,w,E,T,b,12,c[9]),T=t(T,k,w,E,v,17,c[10]),E=t(E,T,k,w,m,22,c[11]),w=t(w,E,T,k,_,7,c[12]),k=t(k,w,E,T,O,12,c[13]),T=t(T,k,w,E,S,17,c[14]),w=n(w,E=t(E,T,k,w,P,22,c[15]),T,k,s,5,c[16]),k=n(k,w,E,T,d,9,c[17]),T=n(T,k,w,E,m,14,c[18]),E=n(E,T,k,w,u,20,c[19]),w=n(w,E,T,k,h,5,c[20]),k=n(k,w,E,T,v,9,c[21]),T=n(T,k,w,E,P,14,c[22]),E=n(E,T,k,w,f,20,c[23]),w=n(w,E,T,k,b,5,c[24]),k=n(k,w,E,T,S,9,c[25]),T=n(T,k,w,E,p,14,c[26]),E=n(E,T,k,w,g,20,c[27]),w=n(w,E,T,k,O,5,c[28]),k=n(k,w,E,T,l,9,c[29]),T=n(T,k,w,E,y,14,c[30]),w=r(w,E=n(E,T,k,w,_,20,c[31]),T,k,h,4,c[32]),k=r(k,w,E,T,g,11,c[33]),T=r(T,k,w,E,m,16,c[34]),E=r(E,T,k,w,S,23,c[35]),w=r(w,E,T,k,s,4,c[36]),k=r(k,w,E,T,f,11,c[37]),T=r(T,k,w,E,y,16,c[38]),E=r(E,T,k,w,v,23,c[39]),w=r(w,E,T,k,O,4,c[40]),k=r(k,w,E,T,u,11,c[41]),T=r(T,k,w,E,p,16,c[42]),E=r(E,T,k,w,d,23,c[43]),w=r(w,E,T,k,b,4,c[44]),k=r(k,w,E,T,_,11,c[45]),T=r(T,k,w,E,P,16,c[46]),w=o(w,E=r(E,T,k,w,l,23,c[47]),T,k,u,6,c[48]),k=o(k,w,E,T,y,10,c[49]),T=o(T,k,w,E,S,15,c[50]),E=o(E,T,k,w,h,21,c[51]),w=o(w,E,T,k,_,6,c[52]),k=o(k,w,E,T,p,10,c[53]),T=o(T,k,w,E,v,15,c[54]),E=o(E,T,k,w,s,21,c[55]),w=o(w,E,T,k,g,6,c[56]),k=o(k,w,E,T,P,10,c[57]),T=o(T,k,w,E,d,15,c[58]),E=o(E,T,k,w,O,21,c[59]),w=o(w,E,T,k,f,6,c[60]),k=o(k,w,E,T,m,10,c[61]),T=o(T,k,w,E,l,15,c[62]),E=o(E,T,k,w,b,21,c[63]);a[0]=a[0]+w|0,a[1]=a[1]+E|0,a[2]=a[2]+T|0,a[3]=a[3]+k|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=P,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=P,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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)}(),P.mode.ECB=((S=P.lib.BlockCipherMode.extend()).Encryptor=S.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),S.Decryptor=S.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),S);var w=P;function k(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 N(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function C(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var j={signPamFromParams:function(e){return C(e).map((function(t){return"".concat(t,"=").concat(N(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:N},M={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory"},R=function(){function e(e){var t=e.subscribeEndpoint,n=e.leaveEndpoint,r=e.heartbeatEndpoint,o=e.setStateEndpoint,i=e.timeEndpoint,a=e.getFileUrl,s=e.config,u=e.crypto,c=e.listenerManager;this._listenerManager=c,this._config=s,this._leaveEndpoint=n,this._heartbeatEndpoint=r,this._setStateEndpoint=o,this._subscribeEndpoint=t,this._getFileUrl=a,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 E({timeEndpoint:i}),this._dedupingManager=new A({config:s})}return e.prototype.adaptStateChange=function(e,t){var n=this,r=e.state,o=e.channels,i=void 0===o?[]:o,a=e.channelGroups,s=void 0===a?[]:a,u=e.withHeartbeat,c=void 0!==u&&u;if(i.forEach((function(e){e in n._channels&&(n._channels[e].state=r)})),s.forEach((function(e){e in n._channelGroups&&(n._channelGroups[e].state=r)})),c){var l={};return i.forEach((function(e){return l[e]=r})),s.forEach((function(e){return l[e]=r})),this._heartbeatEndpoint({channels:i,channelGroups:s,state:l},t)}return this._setStateEndpoint({state:r,channels:i,channelGroups:s},t)},e.prototype.adaptPresenceChange=function(e){var t=this,n=e.connected,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i;n?(o.forEach((function(e){t._heartbeatChannels[e]={state:{}}})),a.forEach((function(e){t._heartbeatChannelGroups[e]={state:{}}}))):(o.forEach((function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]})),a.forEach((function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]})),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:o,channelGroups:a},(function(e){t._listenerManager.announceStatus(e)}))),this.reconnect()},e.prototype.adaptSubscribeChange=function(e){var t=this,n=e.timetoken,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i,s=e.withPresence,u=void 0!==s&&s,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),o.forEach((function(e){t._channels[e]={state:{}},u&&(t._presenceChannels[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannels[e]={}),t._pendingChannelSubscriptions.push(e)})),a.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,o=void 0===r?[]:r,i=e.channelGroups,a=void 0===i?[]:i,s=[],u=[];o.forEach((function(e){e in n._channels&&(delete n._channels[e],s.push(e),e in n._heartbeatChannels&&delete n._heartbeatChannels[e]),e in n._presenceChannels&&(delete n._presenceChannels[e],s.push(e))})),a.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===s.length&&0===u.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:s,channelGroups:u},(function(e){e.affectedChannels=s,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 o=e._channels[r].state;Object.keys(o).length&&(t[r]=o),n.push(r)})),Object.keys(this._presenceChannels).forEach((function(e){n.push("".concat(e,"-pnpres"))})),Object.keys(this._channelGroups).forEach((function(n){var o=e._channelGroups[n].state;Object.keys(o).length&&(t[n]=o),r.push(n)})),Object.keys(this._presenceChannelGroups).forEach((function(e){r.push("".concat(e,"-pnpres"))})),0!==n.length||0!==r.length){var o={channels:n,channelGroups:r,state:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(o,this._processSubscribeResponse.bind(this))}},e.prototype._processSubscribeResponse=function(e,t){var o=this;if(e.error){if(e.errorData&&"Aborted"===e.errorData.message)return;e.category===M.PNTimeoutCategory?this._startSubscribeLoop():e.category===M.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection((function(){o._config.autoNetworkDetection&&!o._isOnline&&(o._isOnline=!0,o._listenerManager.announceNetworkUp()),o.reconnect(),o._subscriptionStatusAnnounced=!0;var t={category:M.PNReconnectedCategory,operation:e.operation,lastTimetoken:o._lastTimetoken,currentTimetoken:o._currentTimetoken};o._listenerManager.announceStatus(t)})),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===M.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 i={};i.category=M.PNConnectedCategory,i.operation=e.operation,i.affectedChannels=this._pendingChannelSubscriptions,i.subscribedChannels=this.getSubscribedChannels(),i.affectedChannelGroups=this._pendingChannelGroupSubscriptions,i.lastTimetoken=this._lastTimetoken,i.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(i),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var a=t.messages||[],s=this._config,u=s.requestMessageCountThreshold,c=s.dedupeOnSubscribe;if(u&&a.length>=u){var l={};l.category=M.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(j.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._config.cipherKey){var d=o._crypto.decrypt(e.payload);"object"==typeof d&&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;(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._config.cipherKey?y.message=o._crypto.decrypt(e.payload):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}(),U={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!==U.PNSubscribeOperation&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(e!==U.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 U.PNPublishOperation:t="pub";break;case U.PNSignalOperation:t="sig";break;case U.PNHistoryOperation:case U.PNFetchMessagesOperation:case U.PNDeleteMessagesOperation:case U.PNMessageCounts:t="hist";break;case U.PNUnsubscribeOperation:case U.PNWhereNowOperation:case U.PNHereNowOperation:case U.PNHeartbeatOperation:case U.PNSetStateOperation:case U.PNGetStateOperation:t="pres";break;case U.PNAddChannelsToGroupOperation:case U.PNRemoveChannelsFromGroupOperation:case U.PNChannelGroupsOperation:case U.PNRemoveGroupOperation:case U.PNChannelsForGroupOperation:t="cg";break;case U.PNPushNotificationEnabledChannelsOperation:case U.PNRemoveAllPushNotificationsOperation:t="push";break;case U.PNCreateUserOperation:case U.PNUpdateUserOperation:case U.PNDeleteUserOperation:case U.PNGetUserOperation:case U.PNGetUsersOperation:case U.PNCreateSpaceOperation:case U.PNUpdateSpaceOperation:case U.PNDeleteSpaceOperation:case U.PNGetSpaceOperation:case U.PNGetSpacesOperation:case U.PNGetMembersOperation:case U.PNUpdateMembersOperation:case U.PNGetMembershipsOperation:case U.PNUpdateMembershipsOperation:t="obj";break;case U.PNAddMessageActionOperation:case U.PNRemoveMessageActionOperation:case U.PNGetMessageActionsOperation:t="msga";break;case U.PNAccessManagerGrant:case U.PNAccessManagerAudit:t="pam";break;case U.PNAccessManagerGrantToken:case U.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),I=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,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}(I),F=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}(I),G=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}(I),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 F(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 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}(),L=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=M.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=M.PNNetworkDownCategory,this.announceStatus(e)},e}(),B=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}(),H=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 q(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}function z(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 V(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 W(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=W(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(j.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 J(e,t){for(var r=[],o=2;o0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.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 ae=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 se=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 ue=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 ce=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(i),"/uuid/").concat(j.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 le=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 pe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 fe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 he=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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}}),de={getOperation:function(){return U.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(j.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}}},ye={getOperation:function(){return U.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(j.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}}},ge={getOperation:function(){return U.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=e.crypto,r=e.config,o=JSON.stringify(t);return r.cipherKey&&(o=n.encrypt(o),o=JSON.stringify(o)),o||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(j.encodeString(t.channel),"/0/").concat(j.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]}}},be=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,k,T,E,A,N,C,j,M,R,U,x,I,D,F,G,K,L;return i(this,(function(i){switch(i.label){case 0:if(!a)throw new H("Validation failed, check status for details",q("channel can't be empty"));if(!p)throw new H("Validation failed, check status for details",q("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(k=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,k.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(A=(E=l).POSTFILE,N=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,A.apply(E,N.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,x=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,x.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(I=i.sent()).response&&"string"==typeof I.response.text?(D=I.response.text,F=/(.*)<\/Message>/gi.exec(D),new H(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",I)):new H("Upload to bucket failed.",I);case 19:if(204!==P.status)throw new H("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,K=!1,L={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return L=i.sent(),K=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!K&&G>0)return[3,20];i.label=24;case 24:if(K)return[2,{timetoken:L.timetoken,id:_,name:O}];throw new H("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},ve=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 H("Validation failed, check status for details",q("channel can't be empty"));if(!r)throw new H("Validation failed, check status for details",q("file id can't be empty"));if(!o)throw new H("Validation failed, check status for details",q("file name can't be empty"));var u="/v1/files/".concat(i.subscribeKey,"/channels/").concat(j.encodeString(n),"/files/").concat(r,"/").concat(o),c={};c.uuid=i.getUUID(),c.pnsdk=V(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)},me={getOperation:function(){return U.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(j.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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},_e={getOperation:function(){return U.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(j.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 U.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}}},Se={getOperation:function(){return U.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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}}},Pe={getOperation:function(){return U.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(j.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}}},we={getOperation:function(){return U.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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}}},ke={getOperation:function(){return U.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}}},Te={getOperation:function(){return U.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(j.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}}},Ee={getOperation:function(){return U.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(j.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}}},Ae={getOperation:function(){return U.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(j.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}}},Ne={getOperation:function(){return U.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(j.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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Ce={getOperation:function(){return U.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(j.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}}},je={getOperation:function(){return U.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Me={getOperation:function(){return U.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(j.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 Re=Object.freeze({__proto__:null,getOperation:function(){return U.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 Ue=Object.freeze({__proto__:null,getOperation:function(){return U.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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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 Ie(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(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]=Ie(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Ie(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Ie(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]=Ie(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Ie(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Ie(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]=Ie(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Ie(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Ie(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]=Ie(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Ie(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Ie(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Fe=Object.freeze({__proto__:null,getOperation:function(){return U.PNAccessManagerGrantToken},extractPermissions:Ie,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 De(0,t)},handleResponse:function(e,t){return t.data.token}}),Ge={getOperation:function(){return U.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(j.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,o=JSON.stringify(t);return r.cipherKey&&(o=n.encrypt(o),o=JSON.stringify(o)),o}var Le=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(r),"/0/").concat(j.encodeString(o))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(j.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 Be=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.encodeString(o),"/0/").concat(j.encodeString(a))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});function He(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}var qe=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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={timetoken:t.timetoken,entry:He(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var ze=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 U.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(j.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 U.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(j.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={};o.channel=r,o.timetoken=t.timetoken,o.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),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=Object.freeze({__proto__:null,getOperation:function(){return U.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 Je=Object.freeze({__proto__:null,getOperation:function(){return U.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(j.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 U.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(j.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 U.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(j.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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}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(Nt())];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(Et(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof H?[2,t.transition(At(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(Ot(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof H?[2,t.transition(St(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 xt=new Ze("RECEIVE_FAILURE");xt.on(Ct.type,(function(e){return It.with(n(n({},e),{attempts:0}))})),xt.on(bt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var It=new Ze("RECEIVE_RECONNECTING");It.onEnter((function(e){return dt(e)})),It.onExit((function(){return dt.cancel})),It.on(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),It.on(At.type,(function(e,t){return It.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),It.on(Nt.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),It.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(kt.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?Kt.with(void 0):Dt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Dt.on(Tt.type,(function(e,t){return It.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(Et.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ht(t.payload.events)])})),Ft.on(At.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(Nt.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?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: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 Kt=new Ze("UNSUBSCRIBED");Kt.on(gt.type,(function(e,t){return Gt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Lt=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(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=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 T({config:i}),c=e.cryptography;r.init(i);var l=new B(i,o);this._tokenManager=l;var p=new x({maximumSamplesCount:6e4});this._telemetryManager=p;var f={config:i,networking:r,crypto:a,cryptography:c,tokenManager:l,telemetryManager:p,PubNubFile:e.PubNubFile};this.File=e.PubNubFile,this.encryptFile=function(e,n){return c.encryptFile(e,n,t.File)},this.decryptFile=function(e,n){return c.decryptFile(e,n,t.File)};var h=J.bind(this,f,$e),d=J.bind(this,f,ie),y=J.bind(this,f,se),b=J.bind(this,f,ce),v=J.bind(this,f,Je),m=new L;if(this._listenerManager=m,this.iAmHere=J.bind(this,f,se),this.iAmAway=J.bind(this,f,ie),this.setPresenceState=J.bind(this,f,ce),this.handshake=J.bind(this,f,Qe),this.receiveMessages=J.bind(this,f,Xe),!0===i.enableSubscribeBeta){var _=new Lt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=_.subscribe.bind(_),this.unsubscribe=_.unsubscribe.bind(_),this.eventEngine=_}else{var O=new R({timeEndpoint:h,leaveEndpoint:d,heartbeatEndpoint:y,setStateEndpoint:b,subscribeEndpoint:v,crypto:f.crypto,config:f.config,listenerManager:m,getFileUrl:function(e){return ve(f,e)}});this.subscribe=O.adaptSubscribeChange.bind(O),this.unsubscribe=O.adaptUnsubscribeChange.bind(O),this.disconnect=O.disconnect.bind(O),this.reconnect=O.reconnect.bind(O),this.unsubscribeAll=O.unsubscribeAll.bind(O),this.getSubscribedChannels=O.getSubscribedChannels.bind(O),this.getSubscribedChannelGroups=O.getSubscribedChannelGroups.bind(O),this.setState=O.adaptStateChange.bind(O),this.presence=O.adaptPresenceChange.bind(O),this.destroy=function(e){O.unsubscribeAll(e),O.disconnect()}}this.addListener=m.addListener.bind(m),this.removeListener=m.removeListener.bind(m),this.removeAllListeners=m.removeAllListeners.bind(m),this.parseToken=l.parseToken.bind(l),this.setToken=l.setToken.bind(l),this.getToken=l.getToken.bind(l),this.channelGroups={listGroups:J.bind(this,f,Z),listChannels:J.bind(this,f,ee),addChannels:J.bind(this,f,Q),removeChannels:J.bind(this,f,X),deleteGroup:J.bind(this,f,Y)},this.push={addChannels:J.bind(this,f,te),removeChannels:J.bind(this,f,ne),deleteDevice:J.bind(this,f,oe),listChannels:J.bind(this,f,re)},this.hereNow=J.bind(this,f,le),this.whereNow=J.bind(this,f,ae),this.getState=J.bind(this,f,ue),this.grant=J.bind(this,f,Ue),this.grantToken=J.bind(this,f,Fe),this.audit=J.bind(this,f,Re),this.revokeToken=J.bind(this,f,Ge),this.publish=J.bind(this,f,Le),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=J.bind(this,f,Be),this.history=J.bind(this,f,qe),this.deleteMessages=J.bind(this,f,ze),this.messageCounts=J.bind(this,f,Ve),this.fetchMessages=J.bind(this,f,We),this.addMessageAction=J.bind(this,f,pe),this.removeMessageAction=J.bind(this,f,fe),this.getMessageActions=J.bind(this,f,he),this.listFiles=J.bind(this,f,de);var S=J.bind(this,f,ye);this.publishFile=J.bind(this,f,ge),this.sendFile=be({generateUploadUrl:S,publishFile:this.publishFile,modules:f}),this.getFileUrl=function(e){return ve(f,e)},this.downloadFile=J.bind(this,f,me),this.deleteFile=J.bind(this,f,_e),this.objects={getAllUUIDMetadata:J.bind(this,f,Oe),getUUIDMetadata:J.bind(this,f,Se),setUUIDMetadata:J.bind(this,f,Pe),removeUUIDMetadata:J.bind(this,f,we),getAllChannelMetadata:J.bind(this,f,ke),getChannelMetadata:J.bind(this,f,Te),setChannelMetadata:J.bind(this,f,Ee),removeChannelMetadata:J.bind(this,f,Ae),getChannelMembers:J.bind(this,f,Ne),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 M.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return M.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return M.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return M.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return M.PNNetworkIssuesCategory;if(e.timeout)return M.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return M.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return M.PNBadRequestCategory;if(e.response.forbidden)return M.PNAccessDeniedCategory}return M.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(Jt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn(Jt,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(Jt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void tn(Jt,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=Kn(e),r=n.length>0?n[0]:"",o=Ln("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,Un([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Sn(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&&(Nn[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:{}})),$n="function"==typeof Map&&Map.prototype,Jn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Qn=$n&&Jn&&"function"==typeof Jn.get?Jn.get:null,Xn=$n&&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,Or="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Sr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Or||"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 kr(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,Er=Tr.custom,Ar=Rr(Er)?Er:null;function Nr(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]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}function Mr(e){return!("[object RegExp]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}function Rr(e){if(Or)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 xr(e,t){return Ur.call(e,t)}function Ir(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 Nr(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 Kr(e){return"Object("+e+")"}function Lr(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(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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?kr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?kr(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 xr(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=Or?lr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):_r.call(t);return"object"!=typeof t||Or?y:Kr(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]"!==Ir(e)||Sr&&"object"==typeof e&&Sr 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(Ar&&"function"==typeof t[Ar]&&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 O=[];return Xn&&Xn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Br("Map",Qn.call(t),O,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 S=[];return tr&&tr.call(t,(function(e){S.push(f(e,t))})),Br("Set",er.call(t),S,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 Lr("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 Lr("WeakSet");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{return or.call(e),!0}catch(e){}return!1}(t))return Lr("WeakRef");if(function(e){return!("[object Number]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(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 Kr(f(vr.call(t)));if(function(e){return!("[object Boolean]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(ir.call(t));if(function(e){return!("[object String]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Ir(e)||Sr&&"object"==typeof e&&Sr in e)}(t)&&!Mr(t)){var P=qr(t,f),w=wr?wr(t)===Object.prototype:t instanceof Object||t.constructor===Object,k=t instanceof Object?"":"null prototype",T=!w&&Sr&&Object(t)===t&&Sr in t?cr.call(Ir(t),8,-1):k?"Object":"",E=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||k?"["+yr.call(dr.call([],T||[],k||[]),": ")+"] ":"");return 0===P.length?E+"{}":p?E+"{"+Hr(P,p)+"}":E+"{ "+yr.call(P,", ")+" }"}return String(t)},$r=zr("%TypeError%"),Jr=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 k=Object.keys(v);P=c?k.sort(c):k}for(var T=o&&_o(v)&&1===v.length?n+"[]":n,E=0;E-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&&No.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return ko;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||ko.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=ko.filter;return("function"==typeof e.filter||_o(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:ko.addQueryPrefix,allowDots:void 0===e.allowDots?ko.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ko.charsetSentinel,delimiter:void 0===e.delimiter?ko.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:ko.encode,encoder:"function"==typeof e.encoder?e.encoder:ko.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:ko.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:ko.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:ko.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ko.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:""},Io={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||Ao.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),No.call(r,c)?r[c]=Ao.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,Ko=Do.hasOwn;var Lo=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(Ko(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)Ko(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)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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");Ko(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 $o(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 Jo(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 Jo(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 Jo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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=k,y.delete=k,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:M.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:return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return n=t.slice(0,16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,t.slice(16))];case 1:return[2,r.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);function hi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var di=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:hi,getfile:oi,postfile:ri}),t.cbor=new zt((function(e){return qt(f.decode(e))}),b),t.PubNubFile=fi,t.cryptography=new pi,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}(Bt);return di})); +!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.setCipherKey(o.cipherKey),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)}}return e.prototype.getAuthKey=function(){return this.authKey},e.prototype.setAuthKey=function(e){return this.authKey=e,this},e.prototype.setCipherKey=function(e){return this.cipherKey=e,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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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,l=e.cryptoModule;r.init(i);var p=new H(i,o);this._tokenManager=p;var f=new x({maximumSamplesCount:6e4});this._telemetryManager=f;var h={config:i,networking:r,crypto:a,cryptography:c,tokenManager:p,telemetryManager:f,PubNubFile:e.PubNubFile,cryptoModule:e.cryptoModule};this.File=e.PubNubFile,this.encryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&l?(t=e,l.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&l?(t=e,l.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:e.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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),this.parseToken=p.parseToken.bind(p),this.setToken=p.setToken.bind(p),this.getToken=p.getToken.bind(p),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.cipherKey&&(t.cryptoModule=new bi({default:new yi({cipherKey:t.cipherKey,useRandomIVs:t.useRandomIVs}),cryptors:[new gi({cipherKey:t.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}(qt);return Oi})); 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/subscription_manager.js b/lib/core/components/subscription_manager.js index 6e5bdc4ca..985efe9b1 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,20 @@ 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; + if (console && console.log) { + console.log('decryption error', e.message); + } + } + if (decryptedPayload !== null) { msgPayload = decryptedPayload; } } @@ -558,8 +572,26 @@ 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; + // eslint-disable-next-line + if (console && console.log) { + console.log('decryption error', e.message); //eslint-disable-line + } + } + 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..c844a1098 100644 --- a/lib/core/endpoints/fetch_messages.js +++ b/lib/core/endpoints/fetch_messages.js @@ -8,13 +8,16 @@ 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) + if (!modules.cryptoModule) return message; try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + return decryptedPayload; } catch (e) { + if (console && console.log) + console.log('decryption error', e.message); return message; } } diff --git a/lib/core/endpoints/file_upload/publish_file.js b/lib/core/endpoints/file_upload/publish_file.js index e03aa7543..96fc6e715 100644 --- a/lib/core/endpoints/file_upload/publish_file.js +++ b/lib/core/endpoints/file_upload/publish_file.js @@ -10,7 +10,8 @@ var preparePayload = function (_a, payload) { var crypto = _a.crypto, config = _a.config; var stringifiedPayload = JSON.stringify(payload); if (config.cipherKey) { - stringifiedPayload = crypto.encrypt(stringifiedPayload); + var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; diff --git a/lib/core/endpoints/history/get_history.js b/lib/core/endpoints/history/get_history.js index 239653806..4e877cb0f 100644 --- a/lib/core/endpoints/history/get_history.js +++ b/lib/core/endpoints/history/get_history.js @@ -8,13 +8,16 @@ 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) + if (!modules.cryptoModule) return message; try { - return crypto.decrypt(message); + var decryptedData = modules.cryptoModule.decrypt(message); + var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; + return decryptedPayload; } catch (e) { + if (console && console.log) + console.log('decryption error', e.message); return message; } } diff --git a/lib/core/endpoints/publish.js b/lib/core/endpoints/publish.js index 2e45b6db6..5bafeff87 100644 --- a/lib/core/endpoints/publish.js +++ b/lib/core/endpoints/publish.js @@ -7,11 +7,12 @@ 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; diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index 804ecc67a..251a80d8a 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -60,6 +60,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")); @@ -133,7 +134,7 @@ var default_1 = /** @class */ (function () { var config = new config_1.default({ setup: setup }); this._config = config; var crypto = new index_1.default({ config: config }); // LEGACY - var cryptography = setup.cryptography; + var cryptography = setup.cryptography, cryptoModule = setup.cryptoModule; networking.init(config); var tokenManager = new token_manager_1.default(config, cbor); this._tokenManager = tokenManager; @@ -149,10 +150,23 @@ var default_1 = /** @class */ (function () { tokenManager: tokenManager, telemetryManager: telemetryManager, PubNubFile: setup.PubNubFile, + cryptoModule: setup.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' && cryptoModule) { + file = key; + return cryptoModule.encryptFile(file, this.File); + } + return cryptography.encryptFile(key, file, this.File); + }; + this.decryptFile = function (key, file) { + if (arguments.length == 1 && typeof key != 'string' && cryptoModule) { + file = key; + return 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); @@ -183,6 +197,7 @@ var default_1 = /** @class */ (function () { config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, + cryptoModule: setup.cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -472,8 +487,24 @@ 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' && cryptoModule) { + var encrypted = 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 = cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? (0, base64_codec_1.encode)(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); 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/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 460c8e19c..951e9576a 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -66,7 +66,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.CryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; var stream_1 = require("stream"); -var endpoint_1 = require("../../../core/components/endpoint"); +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")); @@ -102,76 +102,56 @@ var CryptoModule = /** @class */ (function () { return this.getAllCryptors().find(function (c) { return c.identifier === ''; }); }; CryptoModule.prototype.encrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - var encrypted, header, headerData, pos; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(Buffer.from(data))]; - case 1: - encrypted = _a.sent(); - if (!encrypted.metadata) - return [2 /*return*/, encrypted.data]; - header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - headerData = new Uint8Array(header.length); - pos = 0; - headerData.set(header.data, pos); - pos += header.length; - if (encrypted.metadata) { - pos -= encrypted.metadata.length; - headerData.set(encrypted.metadata, pos); - } - return [2 /*return*/, Buffer.concat([headerData, encrypted.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)]).buffer; }; CryptoModule.prototype.decrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - var encryptedData, header, cryptor, metadata; - return __generator(this, function (_a) { - encryptedData = Buffer.from(data); - header = CryptorHeader.tryParse(encryptedData); - cryptor = this.getCryptor(header); - metadata = header.length > 0 - ? encryptedData.slice(header.length - header.metadataLength, header.length) - : null; - return [2 /*return*/, cryptor.decrypt({ - data: encryptedData.slice(header.length), - metadata: metadata, - })]; - }); + 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 _a, _b, encryptedStream, header, payload, pos, output; - var _c; - return __generator(this, function (_d) { - switch (_d.label) { + 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 instanceof legacyCryptor_1.default) + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; - if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; - _b = (_a = File).create; - _c = { - name: file.name, - mimeType: 'application/octet-stream' - }; - return [4 /*yield*/, this.encrypt(file.data)]; - case 1: return [2 /*return*/, _b.apply(_a, [( - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field - _c.data = _d.sent(), - _c)])]; - case 2: - if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 4]; + 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 3: - encryptedStream = _d.sent(); + case 1: + encryptedStream = _a.sent(); header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata); payload = new Uint8Array(header.length); pos = 0; @@ -189,46 +169,37 @@ var CryptoModule = /** @class */ (function () { mimeType: 'application/octet-stream', stream: output, })]; - case 4: return [2 /*return*/]; + case 2: return [2 /*return*/]; } }); }); }; CryptoModule.prototype.decryptFile = function (file, File) { return __awaiter(this, void 0, void 0, function () { - var header, cryptor, _a, _b, stream_2; - var _c; + var header, cryptor, stream_2; var _this = this; - return __generator(this, function (_d) { - switch (_d.label) { - case 0: - if (!((file === null || file === void 0 ? void 0 : file.data) instanceof Buffer)) return [3 /*break*/, 2]; - 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) - */ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception - if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) - return [2 /*return*/, cryptor.decryptFile(file, File)]; - _b = (_a = File).create; - _c = { - name: file.name - }; - return [4 /*yield*/, this.decrypt(file === null || file === void 0 ? void 0 : file.data)]; - case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), - _c)])]; - case 2: - 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*/]; + 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*/]; }); }); }; @@ -242,6 +213,8 @@ var CryptoModule = /** @class */ (function () { 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)]; } @@ -250,6 +223,8 @@ var CryptoModule = /** @class */ (function () { 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, @@ -266,17 +241,17 @@ var CryptoModule = /** @class */ (function () { 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) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception return [2 /*return*/, cryptor.decryptFile(File.create({ name: file.name, stream: stream, }), File)]; } else { - throw new endpoint_1.PubNubError('unknown cryptor'); + throw new Error('unknown cryptor error'); } return [2 /*return*/]; }); @@ -287,7 +262,7 @@ var CryptoModule = /** @class */ (function () { var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); if (cryptor) return cryptor; - throw new Error('unknown cryptor'); + throw new Error('unknown cryptor error'); } else if (header instanceof CryptorHeaderV1) { return this.getCryptorFromId(header.identifier); @@ -298,7 +273,7 @@ var CryptoModule = /** @class */ (function () { if (cryptor) { return cryptor; } - throw Error('unknown cryptor'); + throw new Error('unknown cryptor error'); }; CryptoModule.LEGACY_IDENTIFIER = ''; return CryptoModule; @@ -321,12 +296,12 @@ var CryptorHeader = /** @class */ (function () { }; CryptorHeader.validateVersion = function (data) { if (data && data > CryptorHeader.MAX_VERSION) - throw new endpoint_1.PubNubError('decryption error'); + throw new Error('decryption error. invalid header version'); return data; }; CryptorHeader.tryGetIdentifier = function (data) { if (data.byteLength < 4) { - throw new endpoint_1.PubNubError('unknown cryptor'); + throw new Error('unknown cryptor error. decryption failed'); } else { return data.toString('utf8'); @@ -343,6 +318,7 @@ var CryptorHeader = /** @class */ (function () { 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 = ''; @@ -356,24 +332,24 @@ var CryptorHeader = /** @class */ (function () { version = encryptedData[4]; } else { - throw new endpoint_1.PubNubError('decryption error'); + throw new Error('decryption error. invalid header version'); } if (version > CryptorHeader.MAX_VERSION) - throw new endpoint_1.PubNubError('unknown cryptor'); + 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 endpoint_1.PubNubError('decryption error'); + throw new Error('decryption error. invalid crypto identifier'); } var metadataLength = null; if (encryptedData.length >= pos + 1) { metadataLength = encryptedData[pos]; } else { - throw new endpoint_1.PubNubError('decryption error'); + throw new Error('decryption error. invalid metadata length'); } pos += 1; if (metadataLength === 255 && encryptedData.length >= pos + 2) { @@ -387,6 +363,7 @@ var CryptorHeader = /** @class */ (function () { CryptorHeader.IDENTIFIER_LENGTH = 4; CryptorHeader.VERSION = 1; CryptorHeader.MAX_VERSION = 1; + CryptorHeader.MIN_HEADER_LEGTH = 10; return CryptorHeader; }()); // v1 CryptorHeader diff --git a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js index 8ae2a5467..34c964471 100644 --- a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js @@ -65,28 +65,24 @@ var AesCbcCryptor = /** @class */ (function () { return Buffer.from(sha.digest()); }; AesCbcCryptor.prototype.encrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - var iv, key, bPlain, aes; - return __generator(this, function (_a) { - iv = this.getIv(); - key = this.getKey(); - bPlain = Buffer.from(data); - aes = (0, crypto_1.createCipheriv)(this.algo, key, iv); - return [2 /*return*/, { - metadata: iv, - data: Buffer.concat([aes.update(bPlain), aes.final()]), - }]; - }); - }); + var iv = this.getIv(); + var key = this.getKey(); + var plainData = data instanceof ArrayBuffer ? data : new TextEncoder().encode(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) { - return __awaiter(this, void 0, void 0, function () { - var aes; - return __generator(this, function (_a) { - aes = (0, crypto_1.createDecipheriv)(this.algo, this.getKey(), encryptedData.metadata); - return [2 /*return*/, Buffer.concat([aes.update(encryptedData.data), aes.final()])]; - }); - }); + 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()])); }; AesCbcCryptor.prototype.encryptStream = function (stream) { return __awaiter(this, void 0, void 0, function () { @@ -94,6 +90,8 @@ var AesCbcCryptor = /** @class */ (function () { 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*/, { diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js index 86163e55c..21273869f 100644 --- a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -40,6 +40,7 @@ var __importDefault = (this && this.__importDefault) || function (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) { @@ -55,21 +56,16 @@ var LegacyCryptor = /** @class */ (function () { configurable: true }); LegacyCryptor.prototype.encrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, { - data: this.cryptor.encrypt(data), - metadata: null, - }]; - }); - }); + if (data.length === 0) + throw new Error('encryption error. empty content'); + return { + data: this.cryptor.encrypt(data), + metadata: null, + }; }; LegacyCryptor.prototype.decrypt = function (encryptedData) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this.cryptor.decrypt(encryptedData.data.toString())]; - }); - }); + 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 () { diff --git a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js index 83df01db6..3b35ddc41 100644 --- a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js @@ -74,11 +74,14 @@ var AesCbcCryptor = /** @class */ (function () { }; AesCbcCryptor.prototype.encrypt = function (data) { return __awaiter(this, void 0, void 0, function () { - var abIv, key; + var dataBytes, abIv, key; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: + dataBytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; + if (dataBytes.byteLength === 0) + throw new Error('encryption error. empty content'); abIv = this._getIv(); return [4 /*yield*/, this._getKey()]; case 1: @@ -86,7 +89,7 @@ var AesCbcCryptor = /** @class */ (function () { _a = { metadata: abIv }; - return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, data)]; + return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, dataBytes)]; case 2: return [2 /*return*/, (_a.data = _b.sent(), _a)]; } diff --git a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js index 0666c878d..a6ac9416f 100644 --- a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js @@ -55,21 +55,14 @@ var LegacyCryptor = /** @class */ (function () { configurable: true }); LegacyCryptor.prototype.encrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, { - data: this.cryptor.encrypt(data), - metadata: null, - }]; - }); - }); + var stringData = typeof data === 'string' ? data : new TextDecoder().decode(data); + return { + data: this.cryptor.encrypt(stringData), + metadata: null, + }; }; LegacyCryptor.prototype.decrypt = function (encryptedData) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this.cryptor.decrypt(encryptedData.data)]; - }); - }); + return this.cryptor.decrypt(encryptedData.data); }; LegacyCryptor.prototype.encryptFile = function (file, File) { var _a; diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index 52ba4848a..167337a47 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -64,9 +64,12 @@ 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 endpoint_1 = require("../../../core/components/endpoint"); 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; @@ -108,27 +111,25 @@ var CryptoModule = /** @class */ (function () { headerData = new Uint8Array(header.length); pos = 0; headerData.set(header.data, pos); - pos += header.length; - if (encrypted.metadata) { - pos -= encrypted.metadata.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - } + pos += header.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); return [2 /*return*/, this.concatArrayBuffer(headerData.buffer, encrypted.data)]; } }); }); }; - CryptoModule.prototype.decrypt = function (encryptedData) { + CryptoModule.prototype.decrypt = function (data) { return __awaiter(this, void 0, void 0, function () { - var header, cryptor, metadata; + var encryptedData, header, cryptor, metadata; return __generator(this, function (_a) { + encryptedData = typeof data === 'string' ? new TextEncoder().encode(data) : data; header = CryptorHeader.tryParse(encryptedData); cryptor = this.getCryptor(header); metadata = header.length > 0 ? encryptedData.slice(header.length - header.metadataLength, header.length) : null; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception + if (encryptedData.slice(header.length).byteLength <= 0) + throw new Error('decryption error. empty content'); return [2 /*return*/, cryptor.decrypt({ data: encryptedData.slice(header.length), metadata: metadata, @@ -147,21 +148,16 @@ var CryptoModule = /** @class */ (function () { * Files handled differently in case of Legacy cryptor. * (as long as we support legacy need to check on default cryptor) */ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: default cryptor will be there. As long as legacy cryptor supported. - if (this.defaultCryptor.identifier === '') + if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; - if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; + if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; _b = (_a = File).create; _c = { name: file.name, mimeType: 'application/octet-stream' }; return [4 /*yield*/, this.encrypt(file.data)]; - case 1: return [2 /*return*/, _b.apply(_a, [( - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field - _c.data = _d.sent(), + case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), _c)])]; case 2: return [2 /*return*/]; } @@ -175,26 +171,21 @@ var CryptoModule = /** @class */ (function () { return __generator(this, function (_d) { switch (_d.label) { case 0: - if (!(file.data instanceof Buffer)) return [3 /*break*/, 2]; + if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; 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) */ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: cryptor will be there or unreachable due to exception - if (cryptor.identifier === CryptoModule.LEGACY_IDENTIFIER) + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) return [2 /*return*/, cryptor.decryptFile(file, File)]; _b = (_a = File).create; _c = { name: file.name }; return [4 /*yield*/, this.decrypt(file.data)]; - case 1: return [2 /*return*/, _b.apply(_a, [( - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore: can not infer that PubNubFile has data field - _c.data = _d.sent(), + case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), _c)])]; case 2: return [2 /*return*/]; } @@ -217,7 +208,7 @@ var CryptoModule = /** @class */ (function () { if (cryptor) { return cryptor; } - throw Error('unknown cryptor'); + throw Error('unknown cryptor error'); }; CryptoModule.prototype.concatArrayBuffer = function (ab1, ab2) { var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); @@ -228,7 +219,7 @@ var CryptoModule = /** @class */ (function () { CryptoModule.LEGACY_IDENTIFIER = ''; return CryptoModule; }()); -exports.default = CryptoModule; +exports.CryptoModule = CryptoModule; // CryptorHeader Utility var CryptorHeader = /** @class */ (function () { function CryptorHeader() { @@ -250,28 +241,31 @@ var CryptorHeader = /** @class */ (function () { version = encryptedData[4]; } else { - throw new endpoint_1.PubNubError('decryption error'); + throw new Error('decryption error. invalid header version'); } if (version > CryptorHeader.MAX_VERSION) - throw new endpoint_1.PubNubError('unknown cryptor'); + throw new endpoint_1.PubNubError('unknown cryptor error'); var identifier = ''; var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; if (encryptedData.byteLength >= pos) { identifier = encryptedData.slice(5, pos); } else { - throw new endpoint_1.PubNubError('decryption error'); + throw new Error('decryption error. invalid crypto identifier'); } - var headerSize = null; - if (encryptedData.byteLength > pos + 1) { - headerSize = encryptedData[pos]; + var metadataLength = null; + if (encryptedData.byteLength >= pos + 1) { + metadataLength = encryptedData[pos]; + } + else { + throw new Error('decryption error. invalid metadata length'); } pos += 1; - if (headerSize === 255 && encryptedData.byteLength >= pos + 2) { - headerSize = new Uint16Array(encryptedData.slice(pos, pos + 3)).reduce(function (acc, val) { return (acc << 8) + val; }, 0); + 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(identifier.toString('utf8'), headerSize); + return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); }; CryptorHeader.SENTINEL = 'PNED'; CryptorHeader.LEGACY_IDENTIFIER = ''; diff --git a/lib/crypto/modules/node.js b/lib/crypto/modules/node.js index 63ece807c..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,6 +180,8 @@ 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()]); }; diff --git a/lib/crypto/modules/web.js b/lib/crypto/modules/web.js index 58ab3bb8f..83501135a 100644 --- a/lib/crypto/modules/web.js +++ b/lib/crypto/modules/web.js @@ -129,7 +129,10 @@ 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()]; @@ -207,7 +210,9 @@ var WebCryptography = /** @class */ (function () { switch (_a.label) { case 0: abIv = ciphertext.slice(0, 16); - return [4 /*yield*/, 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'); + 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]; 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/node/index.js b/lib/node/index.js index 643cff838..0dbbbaf15 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -26,6 +26,7 @@ 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")); +var nodeCryptoModule_1 = require("../crypto/modules/NodeCryptoModule/nodeCryptoModule"); module.exports = /** @class */ (function (_super) { __extends(class_1, _super); function class_1(setup) { @@ -44,6 +45,12 @@ module.exports = /** @class */ (function (_super) { setup.sdkFamily = 'Nodejs'; setup.PubNubFile = node_3.default; setup.cryptography = new node_2.default(); + if (setup.cipherKey) { + setup.cryptoModule = new nodeCryptoModule_1.CryptoModule({ + default: new nodeCryptoModule_1.LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), + cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: setup.cipherKey })], + }); + } if (!('ssl' in setup)) { setup.ssl = true; } diff --git a/lib/web/index.js b/lib/web/index.js index e704201ed..04f6b775b 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,12 @@ 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(); + if (setup.cipherKey) { + setup.cryptoModule = new webCryptoModule_1.CryptoModule({ + default: new webCryptoModule_1.LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), + cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: setup.cipherKey })], + }); + } _this = _super.call(this, setup) || this; if (listenToBrowserNetworkEvents) { // mount network events. From 44fc0fd1c83ae8fc0e5d7f42b5ac70dae70ea96a Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 13:35:26 +0530 Subject: [PATCH 21/38] support for setCipherKey --- dist/web/pubnub.js | 34 ++++++++++++++++++++++------------ dist/web/pubnub.min.js | 2 +- lib/core/components/config.js | 7 +++++-- lib/core/pubnub-common.js | 10 ++++++---- lib/node/index.js | 17 +++++++++++------ lib/web/index.js | 17 +++++++++++------ src/core/components/config.js | 8 ++++++-- src/core/pubnub-common.js | 11 ++++++----- src/node/index.ts | 17 +++++++++++------ src/web/index.js | 17 +++++++++++------ 10 files changed, 90 insertions(+), 50 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index e99fdb340..3bbc047db 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -636,7 +636,8 @@ this.sdkFamily = setup.sdkFamily; this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); - this.setCipherKey(setup.cipherKey); + this.cryptoModule = setup.cryptoModule; + this.setCipherKey(setup.cipherKey, setup); 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.'); @@ -704,8 +705,10 @@ this.authKey = val; return this; }; - default_1.prototype.setCipherKey = function (val) { + default_1.prototype.setCipherKey = function (val, setup) { + var _a; this.cipherKey = val; + this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: (_a = this.useRandomIVs) !== null && _a !== void 0 ? _a : true }); return this; }; default_1.prototype.getUUID = function () { @@ -7454,7 +7457,7 @@ var config = new default_1$b({ setup: setup }); this._config = config; var crypto = new default_1$a({ config: config }); // LEGACY - var cryptography = setup.cryptography, cryptoModule = setup.cryptoModule; + var cryptography = setup.cryptography; networking.init(config); var tokenManager = new default_1$4(config, cbor); this._tokenManager = tokenManager; @@ -7462,6 +7465,7 @@ maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; + var cryptoModule = config.cryptoModule; var modules = { config: config, networking: networking, @@ -7470,7 +7474,7 @@ tokenManager: tokenManager, telemetryManager: telemetryManager, PubNubFile: setup.PubNubFile, - cryptoModule: setup.cryptoModule, + cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; this.encryptFile = function (key, file) { @@ -7517,7 +7521,7 @@ config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, - cryptoModule: setup.cryptoModule, + cryptoModule: cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -7828,13 +7832,14 @@ /* 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); }; this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { this.setProxy = function (proxy) { @@ -13333,12 +13338,17 @@ setup.cbor = new default_1$1(function (arrayBuffer) { return stringifyBufferKeys(CborReader.decode(arrayBuffer)); }, decode$1); setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); - if (setup.cipherKey) { - setup.cryptoModule = new CryptoModule({ - default: new LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), - cryptors: [new AesCbcCryptor({ cipherKey: setup.cipherKey })], - }); - } + setup.initCryptoModule = function (cryptoConfiguration) { + if (setup.cipherKey) { + setup.cryptoModule = 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. diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 7ea58a6d8..6e874664d 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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,l=e.cryptoModule;r.init(i);var p=new H(i,o);this._tokenManager=p;var f=new x({maximumSamplesCount:6e4});this._telemetryManager=f;var h={config:i,networking:r,crypto:a,cryptography:c,tokenManager:p,telemetryManager:f,PubNubFile:e.PubNubFile,cryptoModule:e.cryptoModule};this.File=e.PubNubFile,this.encryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&l?(t=e,l.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&l?(t=e,l.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:e.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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),this.parseToken=p.parseToken.bind(p),this.setToken=p.setToken.bind(p),this.getToken=p.getToken.bind(p),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.cipherKey&&(t.cryptoModule=new bi({default:new yi({cipherKey:t.cipherKey,useRandomIVs:t.useRandomIVs}),cryptors:[new gi({cipherKey:t.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}(qt);return Oi})); +!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.setCipherKey(o.cipherKey,o),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)}}return e.prototype.getAuthKey=function(){return this.authKey},e.prototype.setAuthKey=function(e){return this.authKey=e,this},e.prototype.setCipherKey=function(e,t){var n;return this.cipherKey=e,this.cryptoModule=t.initCryptoModule({cipherKey:this.cipherKey,useRandomIVs:null===(n=this.useRandomIVs)||void 0===n||n}),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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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=i.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&&f?(t=e,f.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&f?(t=e,f.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:f});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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.initCryptoModule=function(e){t.cipherKey&&(t.cryptoModule=new bi({default:new yi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new gi({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}(qt);return Oi})); diff --git a/lib/core/components/config.js b/lib/core/components/config.js index 11286ca01..49736eaf4 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -22,7 +22,8 @@ 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.setCipherKey(setup.cipherKey, setup); 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.'); @@ -90,8 +91,10 @@ var default_1 = /** @class */ (function () { this.authKey = val; return this; }; - default_1.prototype.setCipherKey = function (val) { + default_1.prototype.setCipherKey = function (val, setup) { + var _a; this.cipherKey = val; + this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: (_a = this.useRandomIVs) !== null && _a !== void 0 ? _a : true }); return this; }; default_1.prototype.getUUID = function () { diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index 251a80d8a..d89f7e650 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -134,7 +134,7 @@ var default_1 = /** @class */ (function () { var config = new config_1.default({ setup: setup }); this._config = config; var crypto = new index_1.default({ config: config }); // LEGACY - var cryptography = setup.cryptography, cryptoModule = setup.cryptoModule; + var cryptography = setup.cryptography; networking.init(config); var tokenManager = new token_manager_1.default(config, cbor); this._tokenManager = tokenManager; @@ -142,6 +142,7 @@ var default_1 = /** @class */ (function () { maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; + var cryptoModule = config.cryptoModule; var modules = { config: config, networking: networking, @@ -150,7 +151,7 @@ var default_1 = /** @class */ (function () { tokenManager: tokenManager, telemetryManager: telemetryManager, PubNubFile: setup.PubNubFile, - cryptoModule: setup.cryptoModule, + cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; this.encryptFile = function (key, file) { @@ -197,7 +198,7 @@ var default_1 = /** @class */ (function () { config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, - cryptoModule: setup.cryptoModule, + cryptoModule: cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -508,13 +509,14 @@ var default_1 = /** @class */ (function () { /* 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); }; this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { this.setProxy = function (proxy) { diff --git a/lib/node/index.js b/lib/node/index.js index 0dbbbaf15..14df51d40 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -45,12 +45,17 @@ module.exports = /** @class */ (function (_super) { setup.sdkFamily = 'Nodejs'; setup.PubNubFile = node_3.default; setup.cryptography = new node_2.default(); - if (setup.cipherKey) { - setup.cryptoModule = new nodeCryptoModule_1.CryptoModule({ - default: new nodeCryptoModule_1.LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), - cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: setup.cipherKey })], - }); - } + setup.initCryptoModule = function (cryptoConfiguration) { + if (setup.cipherKey) { + setup.cryptoModule = 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; } diff --git a/lib/web/index.js b/lib/web/index.js index 04f6b775b..b2b6fec44 100644 --- a/lib/web/index.js +++ b/lib/web/index.js @@ -57,12 +57,17 @@ 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(); - if (setup.cipherKey) { - setup.cryptoModule = new webCryptoModule_1.CryptoModule({ - default: new webCryptoModule_1.LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), - cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: setup.cipherKey })], - }); - } + setup.initCryptoModule = function (cryptoConfiguration) { + if (setup.cipherKey) { + setup.cryptoModule = 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. diff --git a/src/core/components/config.js b/src/core/components/config.js index d3e93ad35..de145292a 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -142,6 +142,8 @@ export default class { useRandomIVs; enableSubscribeBeta; + cryptoModule; + constructor({ setup }) { this._PNSDKSuffix = {}; @@ -153,7 +155,8 @@ export default class { this.sdkFamily = setup.sdkFamily; this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); - this.setCipherKey(setup.cipherKey); + this.cryptoModule = setup.cryptoModule; + this.setCipherKey(setup.cipherKey, setup); this.setFilterExpression(setup.filterExpression); @@ -239,8 +242,9 @@ export default class { return this; } - setCipherKey(val) { + setCipherKey(val, setup) { this.cipherKey = val; + this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs ?? true }); return this; } diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index 0347ae5b9..f83ffc316 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -280,7 +280,7 @@ export default class { this._config = config; const crypto = new Crypto({ config }); // LEGACY - const { cryptography, cryptoModule } = setup; + const { cryptography } = setup; networking.init(config); @@ -292,6 +292,7 @@ export default class { }); this._telemetryManager = telemetryManager; + const cryptoModule = config.cryptoModule; const modules = { config, @@ -301,7 +302,7 @@ export default class { tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, - cryptoModule: setup.cryptoModule, + cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; @@ -355,7 +356,7 @@ export default class { config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), - cryptoModule: setup.cryptoModule, + cryptoModule: cryptoModule, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); @@ -699,14 +700,14 @@ export default class { /* 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); this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { diff --git a/src/node/index.ts b/src/node/index.ts index b156d5810..26b636f28 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -27,12 +27,17 @@ export = class extends PubNubCore { setup.PubNubFile = PubNubFile; setup.cryptography = new NodeCryptography(); - if (setup.cipherKey) { - setup.cryptoModule = new CryptoModule({ - default: new LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), - cryptors: [new AesCbcCryptor({ cipherKey: setup.cipherKey })], - }); - } + setup.initCryptoModule = (cryptoConfiguration: any) => { + if (setup.cipherKey) { + setup.cryptoModule = 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 3f4664eab..a6ff8a79e 100644 --- a/src/web/index.js +++ b/src/web/index.js @@ -41,12 +41,17 @@ export default class extends PubNubCore { setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); - if (setup.cipherKey) { - setup.cryptoModule = new CryptoModule({ - default: new LegacyCryptor({ cipherKey: setup.cipherKey, useRandomIVs: setup.useRandomIVs }), - cryptors: [new AesCbcCryptor({ cipherKey: setup.cipherKey })], - }); - } + setup.initCryptoModule = (cryptoConfiguration) => { + if (setup.cipherKey) { + setup.cryptoModule = new CryptoModule({ + default: new LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); + } + }; super(setup); From ee976bf28ae6ab386883cd3b0d1d27e7fbee33d9 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 18:47:42 +0530 Subject: [PATCH 22/38] fix: setCipherKey() --- src/core/components/config.js | 3 ++- src/core/pubnub-common.js | 4 ++-- src/node/index.ts | 4 ++-- src/web/index.js | 4 ++-- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/core/components/config.js b/src/core/components/config.js index de145292a..ba8817698 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -242,9 +242,10 @@ export default class { return this; } - setCipherKey(val, setup) { + setCipherKey(val, setup, modules) { this.cipherKey = val; this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs ?? true }); + if (modules) modules.cryptoModule = this.cryptoModule; return this; } diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index f83ffc316..a409d6e5f 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -292,7 +292,7 @@ export default class { }); this._telemetryManager = telemetryManager; - const cryptoModule = config.cryptoModule; + const cryptoModule = this._config.cryptoModule; const modules = { config, @@ -707,7 +707,7 @@ export default class { 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); + 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/node/index.ts b/src/node/index.ts index 26b636f28..a2450ba1b 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -28,8 +28,8 @@ export = class extends PubNubCore { setup.cryptography = new NodeCryptography(); setup.initCryptoModule = (cryptoConfiguration: any) => { - if (setup.cipherKey) { - setup.cryptoModule = new CryptoModule({ + if (cryptoConfiguration.cipherKey) { + return new CryptoModule({ default: new LegacyCryptor({ cipherKey: cryptoConfiguration.cipherKey, useRandomIVs: cryptoConfiguration.useRandomIVs, diff --git a/src/web/index.js b/src/web/index.js index a6ff8a79e..44b9d42cb 100644 --- a/src/web/index.js +++ b/src/web/index.js @@ -42,8 +42,8 @@ export default class extends PubNubCore { setup.cryptography = new WebCryptography(); setup.initCryptoModule = (cryptoConfiguration) => { - if (setup.cipherKey) { - setup.cryptoModule = new CryptoModule({ + if (cryptoConfiguration.cipherKey) { + return new CryptoModule({ default: new LegacyCryptor({ cipherKey: cryptoConfiguration.cipherKey, useRandomIVs: cryptoConfiguration.useRandomIVs, From 929191d171b0aa4a3f56aaf047652e45d22382a1 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 18:48:00 +0530 Subject: [PATCH 23/38] lib and dist files --- dist/web/pubnub.js | 12 +++++++----- dist/web/pubnub.min.js | 2 +- lib/core/components/config.js | 4 +++- lib/core/pubnub-common.js | 4 ++-- lib/node/index.js | 4 ++-- lib/web/index.js | 4 ++-- 6 files changed, 17 insertions(+), 13 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 3bbc047db..7933f62ae 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -705,10 +705,12 @@ this.authKey = val; return this; }; - default_1.prototype.setCipherKey = function (val, setup) { + default_1.prototype.setCipherKey = function (val, setup, modules) { var _a; this.cipherKey = val; this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: (_a = this.useRandomIVs) !== null && _a !== void 0 ? _a : true }); + if (modules) + modules.cryptoModule = this.cryptoModule; return this; }; default_1.prototype.getUUID = function () { @@ -7465,7 +7467,7 @@ maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; - var cryptoModule = config.cryptoModule; + var cryptoModule = this._config.cryptoModule; var modules = { config: config, networking: networking, @@ -7839,7 +7841,7 @@ 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); }; + 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) { @@ -13339,8 +13341,8 @@ setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); setup.initCryptoModule = function (cryptoConfiguration) { - if (setup.cipherKey) { - setup.cryptoModule = new CryptoModule({ + if (cryptoConfiguration.cipherKey) { + return new CryptoModule({ default: new LegacyCryptor({ cipherKey: cryptoConfiguration.cipherKey, useRandomIVs: cryptoConfiguration.useRandomIVs, diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 6e874664d..3a81f6f2a 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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=i.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&&f?(t=e,f.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&f?(t=e,f.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:f});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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.initCryptoModule=function(e){t.cipherKey&&(t.cryptoModule=new bi({default:new yi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new gi({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}(qt);return Oi})); +!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.setCipherKey(o.cipherKey,o),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)}}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.cryptoModule=t.initCryptoModule({cipherKey:this.cipherKey,useRandomIVs:null===(r=this.useRandomIVs)||void 0===r||r}),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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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&&f?(t=e,f.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&f?(t=e,f.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:f});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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.initCryptoModule=function(e){if(e.cipherKey)return new bi({default:new yi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new gi({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}(qt);return Oi})); diff --git a/lib/core/components/config.js b/lib/core/components/config.js index 49736eaf4..15afe9e7b 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -91,10 +91,12 @@ var default_1 = /** @class */ (function () { this.authKey = val; return this; }; - default_1.prototype.setCipherKey = function (val, setup) { + default_1.prototype.setCipherKey = function (val, setup, modules) { var _a; this.cipherKey = val; this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: (_a = this.useRandomIVs) !== null && _a !== void 0 ? _a : true }); + if (modules) + modules.cryptoModule = this.cryptoModule; return this; }; default_1.prototype.getUUID = function () { diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index d89f7e650..5fbc02585 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -142,7 +142,7 @@ var default_1 = /** @class */ (function () { maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; - var cryptoModule = config.cryptoModule; + var cryptoModule = this._config.cryptoModule; var modules = { config: config, networking: networking, @@ -516,7 +516,7 @@ var default_1 = /** @class */ (function () { 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); }; + 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/node/index.js b/lib/node/index.js index 14df51d40..2fd00ed2a 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -46,8 +46,8 @@ module.exports = /** @class */ (function (_super) { setup.PubNubFile = node_3.default; setup.cryptography = new node_2.default(); setup.initCryptoModule = function (cryptoConfiguration) { - if (setup.cipherKey) { - setup.cryptoModule = new nodeCryptoModule_1.CryptoModule({ + if (cryptoConfiguration.cipherKey) { + return new nodeCryptoModule_1.CryptoModule({ default: new nodeCryptoModule_1.LegacyCryptor({ cipherKey: cryptoConfiguration.cipherKey, useRandomIVs: cryptoConfiguration.useRandomIVs, diff --git a/lib/web/index.js b/lib/web/index.js index b2b6fec44..735aa5515 100644 --- a/lib/web/index.js +++ b/lib/web/index.js @@ -58,8 +58,8 @@ var default_1 = /** @class */ (function (_super) { setup.PubNubFile = web_2.default; setup.cryptography = new web_1.default(); setup.initCryptoModule = function (cryptoConfiguration) { - if (setup.cipherKey) { - setup.cryptoModule = new webCryptoModule_1.CryptoModule({ + if (cryptoConfiguration.cipherKey) { + return new webCryptoModule_1.CryptoModule({ default: new webCryptoModule_1.LegacyCryptor({ cipherKey: cryptoConfiguration.cipherKey, useRandomIVs: cryptoConfiguration.useRandomIVs, From 7cef59d4256563113155db88cb92ba654cdd3c04 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 19:25:11 +0530 Subject: [PATCH 24/38] fix: staticIV support --- src/core/components/config.js | 8 +++++--- src/node/index.ts | 16 +++++++--------- src/web/index.js | 16 +++++++--------- 3 files changed, 19 insertions(+), 21 deletions(-) diff --git a/src/core/components/config.js b/src/core/components/config.js index ba8817698..e13fe786e 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -156,7 +156,6 @@ export default class { this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); this.cryptoModule = setup.cryptoModule; - this.setCipherKey(setup.cipherKey, setup); this.setFilterExpression(setup.filterExpression); @@ -230,6 +229,7 @@ export default class { this.setUUID(setup.uuid); } + this.setCipherKey(setup.cipherKey, setup); } // exposed setters @@ -244,8 +244,10 @@ export default class { setCipherKey(val, setup, modules) { this.cipherKey = val; - this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs ?? true }); - if (modules) modules.cryptoModule = this.cryptoModule; + if (this.cipherKey) { + this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + if (modules) modules.cryptoModule = this.cryptoModule; + } return this; } diff --git a/src/node/index.ts b/src/node/index.ts index a2450ba1b..d84670951 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -28,15 +28,13 @@ export = class extends PubNubCore { setup.cryptography = new NodeCryptography(); setup.initCryptoModule = (cryptoConfiguration: any) => { - if (cryptoConfiguration.cipherKey) { - return new CryptoModule({ - default: new LegacyCryptor({ - cipherKey: cryptoConfiguration.cipherKey, - useRandomIVs: cryptoConfiguration.useRandomIVs, - }), - cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); - } + return new CryptoModule({ + default: new LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); }; if (!('ssl' in setup)) { diff --git a/src/web/index.js b/src/web/index.js index 44b9d42cb..7ee3067cc 100644 --- a/src/web/index.js +++ b/src/web/index.js @@ -42,15 +42,13 @@ export default class extends PubNubCore { setup.cryptography = new WebCryptography(); setup.initCryptoModule = (cryptoConfiguration) => { - if (cryptoConfiguration.cipherKey) { - return new CryptoModule({ - default: new LegacyCryptor({ - cipherKey: cryptoConfiguration.cipherKey, - useRandomIVs: cryptoConfiguration.useRandomIVs, - }), - cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); - } + return new CryptoModule({ + default: new LegacyCryptor({ + cipherKey: cryptoConfiguration.cipherKey, + useRandomIVs: cryptoConfiguration.useRandomIVs, + }), + cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], + }); }; super(setup); From f88042f36978376943ff1a48089122b431e5e0e0 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 5 Oct 2023 19:25:31 +0530 Subject: [PATCH 25/38] lib and dist --- dist/web/pubnub.js | 27 +++++++++++++-------------- dist/web/pubnub.min.js | 2 +- lib/core/components/config.js | 11 ++++++----- lib/node/index.js | 16 +++++++--------- lib/web/index.js | 16 +++++++--------- 5 files changed, 34 insertions(+), 38 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 7933f62ae..2ef0ca19c 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -637,7 +637,6 @@ this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); this.cryptoModule = setup.cryptoModule; - this.setCipherKey(setup.cipherKey, setup); 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.'); @@ -696,6 +695,7 @@ } this.setUUID(setup.uuid); } + this.setCipherKey(setup.cipherKey, setup); } // exposed setters default_1.prototype.getAuthKey = function () { @@ -706,11 +706,12 @@ return this; }; default_1.prototype.setCipherKey = function (val, setup, modules) { - var _a; this.cipherKey = val; - this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: (_a = this.useRandomIVs) !== null && _a !== void 0 ? _a : true }); - if (modules) - modules.cryptoModule = this.cryptoModule; + if (this.cipherKey) { + this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + if (modules) + modules.cryptoModule = this.cryptoModule; + } return this; }; default_1.prototype.getUUID = function () { @@ -13341,15 +13342,13 @@ setup.PubNubFile = PubNubFile; setup.cryptography = new WebCryptography(); setup.initCryptoModule = function (cryptoConfiguration) { - if (cryptoConfiguration.cipherKey) { - return new CryptoModule({ - default: new LegacyCryptor({ - cipherKey: cryptoConfiguration.cipherKey, - useRandomIVs: cryptoConfiguration.useRandomIVs, - }), - cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); - } + 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) { diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 3a81f6f2a..d093a9d6d 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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&&f?(t=e,f.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&f?(t=e,f.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:f});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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.initCryptoModule=function(e){if(e.cipherKey)return new bi({default:new yi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new gi({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}(qt);return Oi})); +!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){return this.cipherKey=e,this.cipherKey&&(this.cryptoModule=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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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&&f?(t=e,f.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&f?(t=e,f.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:f});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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.initCryptoModule=function(e){return new bi({default:new yi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new gi({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}(qt);return Oi})); diff --git a/lib/core/components/config.js b/lib/core/components/config.js index 15afe9e7b..578c73f57 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -23,7 +23,6 @@ var default_1 = /** @class */ (function () { this.partnerId = setup.partnerId; this.setAuthKey(setup.authKey); this.cryptoModule = setup.cryptoModule; - this.setCipherKey(setup.cipherKey, setup); 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.'); @@ -82,6 +81,7 @@ var default_1 = /** @class */ (function () { } this.setUUID(setup.uuid); } + this.setCipherKey(setup.cipherKey, setup); } // exposed setters default_1.prototype.getAuthKey = function () { @@ -92,11 +92,12 @@ var default_1 = /** @class */ (function () { return this; }; default_1.prototype.setCipherKey = function (val, setup, modules) { - var _a; this.cipherKey = val; - this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: (_a = this.useRandomIVs) !== null && _a !== void 0 ? _a : true }); - if (modules) - modules.cryptoModule = this.cryptoModule; + if (this.cipherKey) { + this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + if (modules) + modules.cryptoModule = this.cryptoModule; + } return this; }; default_1.prototype.getUUID = function () { diff --git a/lib/node/index.js b/lib/node/index.js index 2fd00ed2a..4e8bd742d 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -46,15 +46,13 @@ module.exports = /** @class */ (function (_super) { setup.PubNubFile = node_3.default; setup.cryptography = new node_2.default(); setup.initCryptoModule = function (cryptoConfiguration) { - if (cryptoConfiguration.cipherKey) { - return new nodeCryptoModule_1.CryptoModule({ - default: new nodeCryptoModule_1.LegacyCryptor({ - cipherKey: cryptoConfiguration.cipherKey, - useRandomIVs: cryptoConfiguration.useRandomIVs, - }), - cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); - } + 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; diff --git a/lib/web/index.js b/lib/web/index.js index 735aa5515..57954665d 100644 --- a/lib/web/index.js +++ b/lib/web/index.js @@ -58,15 +58,13 @@ var default_1 = /** @class */ (function (_super) { setup.PubNubFile = web_2.default; setup.cryptography = new web_1.default(); setup.initCryptoModule = function (cryptoConfiguration) { - if (cryptoConfiguration.cipherKey) { - return new webCryptoModule_1.CryptoModule({ - default: new webCryptoModule_1.LegacyCryptor({ - cipherKey: cryptoConfiguration.cipherKey, - useRandomIVs: cryptoConfiguration.useRandomIVs, - }), - cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); - } + 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) { From 8c57c01882cdf4316707e0cc73240fd825df7d9b Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 9 Oct 2023 12:02:24 +0530 Subject: [PATCH 26/38] refactor: cryptoModule, * added support for PubNub.CryptoModule factory --- src/core/components/config.js | 6 +- .../endpoints/file_upload/publish_file.js | 8 +- src/core/endpoints/publish.js | 2 +- src/core/pubnub-common.js | 16 +-- .../modules/NodeCryptoModule/legacyCryptor.ts | 2 +- .../NodeCryptoModule/nodeCryptoModule.ts | 6 +- .../modules/WebCryptoModule/ICryptor.ts | 7 +- .../modules/WebCryptoModule/aesCbcCryptor.ts | 69 ++++++++--- .../modules/WebCryptoModule/legacyCryptor.ts | 8 +- .../WebCryptoModule/webCryptoModule.ts | 111 ++++++++++-------- src/node/index.ts | 2 + src/web/index.js | 2 +- tsconfig.json | 13 +- 13 files changed, 154 insertions(+), 98 deletions(-) diff --git a/src/core/components/config.js b/src/core/components/config.js index e13fe786e..ef1fcfea7 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -142,6 +142,9 @@ export default class { useRandomIVs; enableSubscribeBeta; + /* + set cryptoModule to encrypt/decrypt messages and files. + */ cryptoModule; constructor({ setup }) { @@ -245,7 +248,8 @@ export default class { setCipherKey(val, setup, modules) { this.cipherKey = val; if (this.cipherKey) { - this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + this.cryptoModule = + setup.cryptoModule ?? setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); if (modules) modules.cryptoModule = this.cryptoModule; } return this; diff --git a/src/core/endpoints/file_upload/publish_file.js b/src/core/endpoints/file_upload/publish_file.js index 2a27ee199..3a111935f 100644 --- a/src/core/endpoints/file_upload/publish_file.js +++ b/src/core/endpoints/file_upload/publish_file.js @@ -1,18 +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) { + 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/publish.js b/src/core/endpoints/publish.js index 8cec47a45..2cb90f0e8 100644 --- a/src/core/endpoints/publish.js +++ b/src/core/endpoints/publish.js @@ -13,7 +13,7 @@ function prepareMessagePayload(modules, messagePayload) { 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 a409d6e5f..e85ea9831 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -308,16 +308,16 @@ export default class { this.File = setup.PubNubFile; this.encryptFile = function (key, file) { - if (arguments.length == 1 && typeof key != 'string' && cryptoModule) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; - return cryptoModule.encryptFile(file, this.File); + 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' && cryptoModule) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; - return cryptoModule.decryptFile(file, this.File); + return modules.cryptoModule.decryptFile(file, this.File); } return cryptography.decryptFile(key, file, this.File); }; @@ -356,7 +356,7 @@ export default class { config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), - cryptoModule: cryptoModule, + cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); @@ -681,8 +681,8 @@ export default class { // mount crypto this.encrypt = function (data, key) { - if (typeof key === 'undefined' && cryptoModule) { - const encrypted = cryptoModule.encrypt(data); + 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); @@ -690,7 +690,7 @@ export default class { }; this.decrypt = function (data, key) { if (typeof key === 'undefined' && cryptoModule) { - const decrypted = cryptoModule.decrypt(data); + const decrypted = modules.cryptoModule.decrypt(data); return decrypted instanceof ArrayBuffer ? encode(decrypted) : decrypted; } else { return crypto.decrypt(data, key); diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts index c8a28fc6b..3fadc4125 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -12,7 +12,7 @@ export default class LegacyCryptor implements ILegacyCryptor { constructor(config: any) { this.config = config; - this.cryptor = new Crypto({ config }); + this.cryptor = new Crypto(config); this.fileCryptor = new FileCryptor(); } get identifier() { diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 18acf5ab4..610fff8b2 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -27,16 +27,16 @@ export class CryptoModule { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: type detection issue with old Config type assignment - static legacyCryptoModule({ config }) { + static legacyCryptoModule(config) { return new this({ default: new LegacyCryptor({ config }), - cryptors: [new AesCbcCryptor(config.cipherKey)], + cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); } static aesCbcCryptoModule(config: any) { return new this({ - default: new AesCbcCryptor(config.cipherKey), + default: new AesCbcCryptor({ cipherKey: config.cipherKey }), cryptors: [new LegacyCryptor({ config })], }); } diff --git a/src/crypto/modules/WebCryptoModule/ICryptor.ts b/src/crypto/modules/WebCryptoModule/ICryptor.ts index ebaf26b99..b15709c75 100644 --- a/src/crypto/modules/WebCryptoModule/ICryptor.ts +++ b/src/crypto/modules/WebCryptoModule/ICryptor.ts @@ -5,6 +5,9 @@ export type EncryptedDataType = { export interface ICryptor { get identifier(): string; - encrypt(data: ArrayBuffer | string): Promise; - decrypt(data: EncryptedDataType): Promise; + encrypt(data: ArrayBuffer | string): EncryptedDataType; + decrypt(data: EncryptedDataType): ArrayBuffer; + + encryptFileData(data: ArrayBuffer): Promise; + decryptFileData(data: EncryptedDataType): Promise; } diff --git a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts index 74dfb8796..e210a50b5 100644 --- a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -1,14 +1,19 @@ import { ICryptor, EncryptedDataType } from './ICryptor'; +import CryptoJS from '../../../core/components/cryptography/hmac-sha256'; +import { decode } from '../../../core/components/base64_codec'; +// ts check disabled: CryptoJs does not have types specified export default class AesCbcCryptor implements ICryptor { static BLOCK_SIZE = 16; static encoder = new TextEncoder(); static decoder = new TextDecoder(); cipherKey: string; + encryptedKey: any; - constructor(configuration: { cipherKey: any }) { + constructor(configuration: { cipherKey: string }) { this.cipherKey = configuration.cipherKey; + this.encryptedKey = CryptoJS.SHA256(this.cipherKey); } get algo() { @@ -19,34 +24,62 @@ export default class AesCbcCryptor implements ICryptor { return 'ACRH'; } - _getIv() { + private getIv() { return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); } - async _getKey() { + 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, 'AES-CBC', true, ['encrypt', 'decrypt']); + return crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt']); } - async encrypt(data: ArrayBuffer | string) { - const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; - if (dataBytes.byteLength === 0) throw new Error('encryption error. empty content'); - const abIv = this._getIv(); - const key = await this._getKey(); + 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: await crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, dataBytes), + data: decode( + CryptoJS.AES.encrypt(data, this.encryptedKey, { + iv: this.bufferToWordArray(abIv), + mode: CryptoJS.mode.CBC, + }).ciphertext.toString(CryptoJS.enc.Base64), + ), }; } - async decrypt(encryptedData: EncryptedDataType) { - const key = await this._getKey(); - const decryptedData = await crypto.subtle.decrypt( - { name: this.algo, iv: encryptedData.metadata! }, - key, - encryptedData.data, - ); - return decryptedData; + decrypt(encryptedData: EncryptedDataType) { + const iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata)); + const data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); + return AesCbcCryptor.encoder.encode( + CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { + iv, + mode: CryptoJS.mode.CBC, + }).toString(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) { + const wa = []; + let i; + for (i = 0; i < b.length; i += 1) { + wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); + } + return CryptoJS.lib.WordArray.create(wa, b.length); } } diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts index c0f62ce55..81fc1b06f 100644 --- a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -2,6 +2,7 @@ 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; @@ -9,9 +10,9 @@ export default class LegacyCryptor implements ILegacyCryptor { cryptor; fileCryptor; - constructor(config: { config: any }) { + constructor(config: any) { this.config = config; - this.cryptor = new Crypto({ config }); + this.cryptor = new Crypto(config); this.fileCryptor = new FileCryptor(); } @@ -27,7 +28,8 @@ export default class LegacyCryptor implements ILegacyCryptor { } decrypt(encryptedData: EncryptedDataType) { - return this.cryptor.decrypt(encryptedData.data); + const data = typeof encryptedData.data === 'string' ? encryptedData.data : encode(encryptedData.data); + return this.cryptor.decrypt(data); } async encryptFile(file: PubNubFileType, File: PubNubFileType) { diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index b4e3f93ff..e292eb426 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -1,8 +1,8 @@ -import { PubNubError } from '../../../core/components/endpoint'; import LegacyCryptor from './legacyCryptor'; import AesCbcCryptor from './aesCbcCryptor'; -import { ICryptor } from './ICryptor'; +import { EncryptedDataType, ICryptor } from './ICryptor'; import { ILegacyCryptor, PubNubFileType } from './ILegacyCryptor'; +import { decode } from '../../../core/components/base64_codec'; export { LegacyCryptor, AesCbcCryptor }; @@ -15,6 +15,8 @@ type CryptoModuleConfiguration = { export class CryptoModule { static LEGACY_IDENTIFIER = ''; + static encoder = new TextEncoder(); + static decoder = new TextDecoder(); defaultCryptor: CryptorType; cryptors: Array; @@ -25,16 +27,16 @@ export class CryptoModule { // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: type detection issue with old Config type assignment - static legacyCryptoModule({ config }) { + static legacyCryptoModule(config) { return new this({ default: new LegacyCryptor({ config }), - cryptors: [new AesCbcCryptor(config.cipherKey)], + cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); } static aesCbcCryptoModule(config: any) { return new this({ - default: new AesCbcCryptor(config.cipherKey), + default: new AesCbcCryptor({ cipherKey: config.cipherKey }), cryptors: [new LegacyCryptor({ config })], }); } @@ -47,22 +49,15 @@ export class CryptoModule { return [this.defaultCryptor, ...this.cryptors]; } - async encrypt(data: ArrayBuffer | string) { - const encrypted = await this.defaultCryptor.encrypt(data); + encrypt(data: ArrayBuffer | string) { + const encrypted = (this.defaultCryptor as ICryptor).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.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - return this.concatArrayBuffer(headerData.buffer, encrypted.data); + const headerData = this.getHeaderData(encrypted); + return this.concatArrayBuffer(headerData!, encrypted.data); } - async decrypt(data: ArrayBuffer | string) { - const encryptedData = typeof data === 'string' ? new TextEncoder().encode(data) : 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 = @@ -77,43 +72,38 @@ export class CryptoModule { } async encryptFile(file: PubNubFileType, File: PubNubFileType) { - /** - * Files handled differently in case of Legacy cryptor. - * (as long as we support legacy need to check on default cryptor) - */ if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return (this.defaultCryptor as ILegacyCryptor).encryptFile(file, File); - if (file.data instanceof ArrayBuffer) { - return File.create({ - name: file.name, - mimeType: 'application/octet-stream', - data: await this.encrypt(file.data), - }); - } + const fileData = 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) { - if (file.data instanceof ArrayBuffer) { - 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: await this.decrypt(file.data), - }); - } + const header = CryptorHeader.tryParse(file.data); + const cryptor = this.getCryptor(header); + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) + return (cryptor as ILegacyCryptor).decryptFile(file, File); + const fileData = this.getFileData(file.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: file.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'); + throw new Error('unknown cryptor error'); } else if (header instanceof CryptorHeaderV1) { return this.getCryptorFromId(header.identifier); } @@ -135,6 +125,27 @@ export class CryptoModule { 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 getFileData(input: any) { + 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 decryption supports only string or ArrayBuffer'); + } } // CryptorHeader Utility @@ -144,26 +155,27 @@ class CryptorHeader { 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(encryptedData: ArrayBuffer) { + 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 (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) return ''; + 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 PubNubError('unknown cryptor error'); + if (version > CryptorHeader.MAX_VERSION) throw new Error('unknown cryptor error'); let identifier: any = ''; let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; @@ -183,14 +195,13 @@ class CryptorHeader { metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); pos += 2; } - return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength); + return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); } } // v1 CryptorHeader class CryptorHeaderV1 { static IDENTIFIER_LENGTH = 4; - static SENTINEL = 'PNED'; _identifier; diff --git a/src/node/index.ts b/src/node/index.ts index d84670951..c95b77ae3 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -9,7 +9,9 @@ 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({ diff --git a/src/web/index.js b/src/web/index.js index 7ee3067cc..24008da2e 100644 --- a/src/web/index.js +++ b/src/web/index.js @@ -22,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, diff --git a/tsconfig.json b/tsconfig.json index 3fe149522..17ec80642 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,18 +1,21 @@ { "$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", + "./src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts" + ] +} \ No newline at end of file From 34ac252a7a0770c9b53dcc3738c2c860e1f4bcc6 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 9 Oct 2023 12:07:56 +0530 Subject: [PATCH 27/38] fix: types --- .../modules/WebCryptoModule/aesCbcCryptor.ts | 28 ++++++++++--------- tsconfig.json | 3 +- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts index e210a50b5..0fb2600f7 100644 --- a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -1,5 +1,5 @@ import { ICryptor, EncryptedDataType } from './ICryptor'; -import CryptoJS from '../../../core/components/cryptography/hmac-sha256'; +import cryptoJS from '../../../core/components/cryptography/hmac-sha256'; import { decode } from '../../../core/components/base64_codec'; // ts check disabled: CryptoJs does not have types specified @@ -10,10 +10,12 @@ export default class AesCbcCryptor implements ICryptor { cipherKey: string; encryptedKey: any; + CryptoJS: any; constructor(configuration: { cipherKey: string }) { this.cipherKey = configuration.cipherKey; - this.encryptedKey = CryptoJS.SHA256(this.cipherKey); + this.CryptoJS = cryptoJS; + this.encryptedKey = this.CryptoJS.SHA256(this.cipherKey); } get algo() { @@ -41,22 +43,22 @@ export default class AesCbcCryptor implements ICryptor { return { metadata: abIv, data: decode( - CryptoJS.AES.encrypt(data, this.encryptedKey, { + this.CryptoJS.AES.encrypt(data, this.encryptedKey, { iv: this.bufferToWordArray(abIv), - mode: CryptoJS.mode.CBC, - }).ciphertext.toString(CryptoJS.enc.Base64), + mode: this.CryptoJS.mode.CBC, + }).ciphertext.toString(this.CryptoJS.enc.Base64), ), }; } decrypt(encryptedData: EncryptedDataType) { - const iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata)); + const iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata!)); const data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); return AesCbcCryptor.encoder.encode( - CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { + this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { iv, - mode: CryptoJS.mode.CBC, - }).toString(CryptoJS.enc.Utf8), + mode: this.CryptoJS.mode.CBC, + }).toString(this.CryptoJS.enc.Utf8), ).buffer; } @@ -71,15 +73,15 @@ export default class AesCbcCryptor implements ICryptor { async decryptFileData(encryptedData: EncryptedDataType): Promise { const key = await this.getKey(); - return crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data); + return crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata! }, key, encryptedData.data); } - private bufferToWordArray(b) { - const wa = []; + 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 CryptoJS.lib.WordArray.create(wa, b.length); + return this.CryptoJS.lib.WordArray.create(wa, b.length); } } diff --git a/tsconfig.json b/tsconfig.json index 17ec80642..2103f09c5 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,7 +15,6 @@ "src/**/*" ], "exclude": [ - "node_modules", - "./src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts" + "node_modules" ] } \ No newline at end of file From 78391643e268a5e6199523b1bd3ae6690638c01e Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 9 Oct 2023 12:08:27 +0530 Subject: [PATCH 28/38] dist and libs --- dist/web/pubnub.js | 250 ++++++++++-------- dist/web/pubnub.min.js | 2 +- lib/core/components/config.js | 4 +- .../endpoints/file_upload/publish_file.js | 8 +- lib/core/endpoints/publish.js | 2 +- lib/core/pubnub-common.js | 16 +- .../NodeCryptoModule/NodeCryptoModule.js | 7 +- .../modules/NodeCryptoModule/legacyCryptor.js | 2 +- .../modules/WebCryptoModule/aesCbcCryptor.js | 71 +++-- .../modules/WebCryptoModule/legacyCryptor.js | 6 +- .../WebCryptoModule/webCryptoModule.js | 139 +++++----- lib/node/index.js | 69 ++--- lib/web/index.js | 1 + 13 files changed, 317 insertions(+), 260 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 2ef0ca19c..cba073996 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -706,9 +706,11 @@ return this; }; default_1.prototype.setCipherKey = function (val, setup, modules) { + var _a; this.cipherKey = val; if (this.cipherKey) { - this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + this.cryptoModule = + (_a = setup.cryptoModule) !== null && _a !== void 0 ? _a : setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); if (modules) modules.cryptoModule = this.cryptoModule; } @@ -847,7 +849,7 @@ } return data; } - function encode$2(input) { + function encode$1(input) { var base64 = ''; var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var bytes = new Uint8Array(input); @@ -4708,12 +4710,11 @@ }; /** */ - var preparePayload = function (_a, payload) { - _a.crypto; var config = _a.config; + var preparePayload = function (modules, payload) { var stringifiedPayload = JSON.stringify(payload); - if (config.cipherKey) { + if (modules.cryptoModule) { var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); - stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$1(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; @@ -6086,10 +6087,10 @@ var stringifiedPayload = JSON.stringify(messagePayload); if (modules.cryptoModule) { var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); - stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$2(encrypted); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$1(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } - return stringifiedPayload; + return stringifiedPayload || ''; } function getOperation$7() { return OPERATIONS.PNPublishOperation; @@ -7481,16 +7482,16 @@ }; this.File = setup.PubNubFile; this.encryptFile = function (key, file) { - if (arguments.length == 1 && typeof key != 'string' && cryptoModule) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; - return cryptoModule.encryptFile(file, this.File); + 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' && cryptoModule) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; - return cryptoModule.decryptFile(file, this.File); + return modules.cryptoModule.decryptFile(file, this.File); } return cryptography.decryptFile(key, file, this.File); }; @@ -7524,7 +7525,7 @@ config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, - cryptoModule: cryptoModule, + cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -7815,9 +7816,9 @@ // --- deprecated ------------------ // mount crypto this.encrypt = function (data, key) { - if (typeof key === 'undefined' && cryptoModule) { - var encrypted = cryptoModule.encrypt(data); - return typeof encrypted === 'string' ? encrypted : encode$2(encrypted); + 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); @@ -7825,8 +7826,8 @@ }; this.decrypt = function (data, key) { if (typeof key === 'undefined' && cryptoModule) { - var decrypted = cryptoModule.decrypt(data); - return decrypted instanceof ArrayBuffer ? encode$2(decrypted) : decrypted; + var decrypted = modules.cryptoModule.decrypt(data); + return decrypted instanceof ArrayBuffer ? encode$1(decrypted) : decrypted; } else { return crypto.decrypt(data, key); @@ -9737,7 +9738,7 @@ } }; - var encode$1 = function encode(str, defaultEncoder, charset, kind, format) { + 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) { @@ -9859,7 +9860,7 @@ combine: combine, compact: compact, decode: decode, - encode: encode$1, + encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, @@ -12913,7 +12914,7 @@ var LegacyCryptor = /** @class */ (function () { function LegacyCryptor(config) { this.config = config; - this.cryptor = new default_1$a({ config: config }); + this.cryptor = new default_1$a(config); this.fileCryptor = new WebCryptography(); } Object.defineProperty(LegacyCryptor.prototype, "identifier", { @@ -12931,7 +12932,8 @@ }; }; LegacyCryptor.prototype.decrypt = function (encryptedData) { - return this.cryptor.decrypt(encryptedData.data); + 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; @@ -12955,9 +12957,12 @@ return LegacyCryptor; }()); + // ts check disabled: CryptoJs does not have types specified 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 () { @@ -12973,10 +12978,10 @@ enumerable: false, configurable: true }); - AesCbcCryptor.prototype._getIv = function () { + AesCbcCryptor.prototype.getIv = function () { return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); }; - AesCbcCryptor.prototype._getKey = function () { + AesCbcCryptor.prototype.getKey = function () { return __awaiter(this, void 0, void 0, function () { var bKey, abHash; return __generator(this, function (_a) { @@ -12986,51 +12991,72 @@ return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; case 1: abHash = _a.sent(); - return [2 /*return*/, crypto.subtle.importKey('raw', abHash, 'AES-CBC', true, ['encrypt', 'decrypt'])]; + 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 dataBytes, abIv, key; + var key, iv; var _a; return __generator(this, function (_b) { switch (_b.label) { - case 0: - dataBytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; - if (dataBytes.byteLength === 0) - throw new Error('encryption error. empty content'); - abIv = this._getIv(); - return [4 /*yield*/, this._getKey()]; + case 0: return [4 /*yield*/, this.getKey()]; case 1: key = _b.sent(); - _a = { - metadata: abIv - }; - return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, dataBytes)]; + 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.decrypt = function (encryptedData) { + AesCbcCryptor.prototype.decryptFileData = function (encryptedData) { return __awaiter(this, void 0, void 0, function () { - var key, decryptedData; + var key; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this._getKey()]; + case 0: return [4 /*yield*/, this.getKey()]; case 1: key = _a.sent(); - return [4 /*yield*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)]; - case 2: - decryptedData = _a.sent(); - return [2 /*return*/, decryptedData]; + 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(); @@ -13045,16 +13071,15 @@ } // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: type detection issue with old Config type assignment - CryptoModule.legacyCryptoModule = function (_a) { - var config = _a.config; + CryptoModule.legacyCryptoModule = function (config) { return new this({ default: new LegacyCryptor({ config: config }), - cryptors: [new AesCbcCryptor(config.cipherKey)], + cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); }; CryptoModule.aesCbcCryptoModule = function (config) { return new this({ - default: new AesCbcCryptor(config.cipherKey), + default: new AesCbcCryptor({ cipherKey: config.cipherKey }), cryptors: [new LegacyCryptor({ config: config })], }); }; @@ -13065,96 +13090,70 @@ return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); }; CryptoModule.prototype.encrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - var encrypted, header, headerData, pos; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(data)]; - case 1: - encrypted = _a.sent(); - if (!encrypted.metadata) - return [2 /*return*/, encrypted.data]; - header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - headerData = new Uint8Array(header.length); - pos = 0; - headerData.set(header.data, pos); - pos += header.length - encrypted.metadata.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - return [2 /*return*/, this.concatArrayBuffer(headerData.buffer, encrypted.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) { - return __awaiter(this, void 0, void 0, function () { - var encryptedData, header, cryptor, metadata; - return __generator(this, function (_a) { - encryptedData = typeof data === 'string' ? new TextEncoder().encode(data) : data; - header = CryptorHeader.tryParse(encryptedData); - cryptor = this.getCryptor(header); - 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 [2 /*return*/, cryptor.decrypt({ - data: encryptedData.slice(header.length), - metadata: metadata, - })]; - }); + 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 _a, _b; - var _c; - return __generator(this, function (_d) { - switch (_d.label) { + var fileData, encrypted; + 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 default cryptor) - */ if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; - if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; - _b = (_a = File).create; - _c = { - name: file.name, - mimeType: 'application/octet-stream' - }; - return [4 /*yield*/, this.encrypt(file.data)]; - case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), - _c)])]; - case 2: return [2 /*return*/]; + fileData = this.getFileData(file.data); + return [4 /*yield*/, this.defaultCryptor.encryptFileData(fileData)]; + case 1: + 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 header, cryptor, _a, _b; + var header, cryptor, fileData, metadata, _a, _b; var _c; return __generator(this, function (_d) { switch (_d.label) { case 0: - if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; 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)]; + fileData = this.getFileData(file.data); + metadata = fileData.slice(header.length - header.metadataLength, header.length); _b = (_a = File).create; _c = { name: file.name }; - return [4 /*yield*/, this.decrypt(file.data)]; + return [4 /*yield*/, this.defaultCryptor.decryptFileData({ + data: file.data.slice(header.length), + metadata: metadata, + })]; case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), _c)])]; - case 2: return [2 /*return*/]; } }); }); @@ -13164,7 +13163,7 @@ var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); if (cryptor) return cryptor; - throw new Error('unknown cryptor'); + throw new Error('unknown cryptor error'); } else if (header instanceof CryptorHeaderV1) { return this.getCryptorFromId(header.identifier); @@ -13183,7 +13182,29 @@ 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) { + 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 decryption supports only string or ArrayBuffer'); + }; CryptoModule.LEGACY_IDENTIFIER = ''; + CryptoModule.encoder = new TextEncoder(); + CryptoModule.decoder = new TextDecoder(); return CryptoModule; }()); // CryptorHeader Utility @@ -13195,12 +13216,13 @@ return; return new CryptorHeaderV1(id, metadata.byteLength); }; - CryptorHeader.tryParse = function (encryptedData) { + CryptorHeader.tryParse = function (data) { + var encryptedData = new Uint8Array(data); var sentinel = ''; var version = null; if (encryptedData.byteLength >= 4) { sentinel = encryptedData.slice(0, 4); - if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) return ''; } if (encryptedData.byteLength >= 5) { @@ -13210,7 +13232,7 @@ throw new Error('decryption error. invalid header version'); } if (version > CryptorHeader.MAX_VERSION) - throw new PubNubError('unknown cryptor error'); + throw new Error('unknown cryptor error'); var identifier = ''; var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; if (encryptedData.byteLength >= pos) { @@ -13231,13 +13253,14 @@ 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); + 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 @@ -13362,6 +13385,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 d093a9d6d..b4cad2705 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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 $(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,o){var i=e.config,a=e.crypto,s=$(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=function(e,t){e.crypto;var n=e.config,r=JSON.stringify(t);if(n.cipherKey){var o=modules.cryptoModule.encrypt(r);r="string"==typeof o?o:encode(o),r=JSON.stringify(r)}return r||""},ve={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={message:t.message,file:{name:t.fileName,id:t.fileId}},a=be(e,i);return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(M.encodeString(t.channel),"/0/").concat(M.encodeString(a))},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]}}},me=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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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}},_e=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&&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(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},Oe={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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},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}}},Pe={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}}},we={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}}},Ee={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}}},Te={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}}},Ae={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}}},Ne={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}}},ke={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}}},Ce={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}}},je={getOperation:function(){return I.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(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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},Me={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}}},Re={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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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}}},Ue={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 Ie=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 xe=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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.join(",")),s.length>0&&(w["target-uuid"]=s.join(",")),(u||0===u)&&(w.ttl=u),w},handleResponse:function(){return{}}});function De(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 Fe(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 Ge(e,t){if(De(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(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]=Fe(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=Fe(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=Fe(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]=Fe(p[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.channels[e]=Fe(f[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.groups[e]=Fe(h[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Le=Object.freeze({__proto__:null,getOperation:function(){return I.PNAccessManagerGrantToken},extractPermissions:Fe,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 De(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 Ge(0,t)},handleResponse:function(e,t){return t.data.token}}),Ke={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 Be(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 He=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=Be(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 Be(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 qe=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]}}});function ze(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var Ve=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={timetoken:t.timetoken,entry:ze(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var We=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 $e=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Qe=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 Xe=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}}}),Ye={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}}},Ze={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}}}},et=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}(),tt=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}(),nt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new tt(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(et),rt=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 ot(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(gt.type,ft((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(jt())];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(kt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Ct(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(bt.type,ft((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(Et())];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(Pt(r.metadata))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(wt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(rt),Ut=new tt("STOPPED");Ut.on(vt.type,(function(e,t){return Ut.with({channels:t.payload.channels,groups:t.payload.groups})})),Ut.on(_t.type,(function(e){return Kt.with(n({},e))}));var It=new tt("HANDSHAKE_FAILURE");It.on(Tt.type,(function(e){return Lt.with(n(n({},e),{attempts:0}))})),It.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var xt=new tt("STOPPED");xt.on(vt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(_t.type,(function(e){return Gt.with(n({},e))}));var Dt=new tt("RECEIVE_FAILURE");Dt.on(Mt.type,(function(e){return Ft.with(n(n({},e),{attempts:0}))})),Dt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new tt("RECEIVE_RECONNECTING");Ft.onEnter((function(e){return gt(e)})),Ft.onExit((function(){return gt.cancel})),Ft.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Ft.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ft.on(jt.type,(function(e){return Dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Ft.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new tt("RECEIVING");Gt.onEnter((function(e){return dt(e.channels,e.groups,e.cursor)})),Gt.onExit((function(){return dt.cancel})),Gt.on(At.type,(function(e,t){return Gt.with(n(n({},e),{cursor:t.payload.cursor}),[yt(t.payload.events)])})),Gt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Gt.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Gt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{attempts:0,reason:t.payload}))})),Gt.on(mt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Lt=new tt("HANDSHAKE_RECONNECTING");Lt.onEnter((function(e){return bt(e)})),Lt.onExit((function(){return gt.cancel})),Lt.on(kt.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[yt(t.payload.events)])})),Lt.on(Ct.type,(function(e,t){return Lt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Lt.on(jt.type,(function(e){return It.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Lt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Kt=new tt("HANDSHAKING");Kt.onEnter((function(e){return ht(e.channels,e.groups)})),Kt.onExit((function(){return ht.cancel})),Kt.on(vt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Bt.with(void 0):Kt.with({channels:t.payload.channels,groups:t.payload.groups})})),Kt.on(Ot.type,(function(e,t){return Gt.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Kt.on(St.type,(function(e,t){return Lt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Kt.on(mt.type,(function(e){return Ut.with({channels:e.channels,groups:e.groups})}));var Bt=new tt("UNSUBSCRIBED");Bt.on(vt.type,(function(e,t){return Kt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Ht=function(){function e(e){var t=this;this.engine=new nt,this.channels=[],this.groups=[],this.dispatcher=new Rt(this.engine,e),this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Bt,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(vt(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(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(vt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(_t())},e.prototype.disconnect=function(){this.engine.transition(mt())},e}(),qt=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&&f?(t=e,f.encryptFile(t,this.File)):c.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&f?(t=e,f.decryptFile(t,this.File)):c.decryptFile(e,t,this.File)};var d=Q.bind(this,h,Qe),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Xe),O=new B;if(this._listenerManager=O,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,Ye),this.receiveMessages=Q.bind(this,h,Ze),!0===i.enableSubscribeBeta){var S=new Ht({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,getFileUrl:function(e){return _e(h,e)},cryptoModule:f});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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,xe),this.grantToken=Q.bind(this,h,Le),this.audit=Q.bind(this,h,Ie),this.revokeToken=Q.bind(this,h,Ke),this.publish=Q.bind(this,h,He),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,h,qe),this.history=Q.bind(this,h,Ve),this.deleteMessages=Q.bind(this,h,We),this.messageCounts=Q.bind(this,h,$e),this.fetchMessages=Q.bind(this,h,Je),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,ve),this.sendFile=me({generateUploadUrl:w,publishFile:this.publishFile,modules:h}),this.getFileUrl=function(e){return _e(h,e)},this.downloadFile=Q.bind(this,h,Oe),this.deleteFile=Q.bind(this,h,Se),this.objects={getAllUUIDMetadata:Q.bind(this,h,Pe),getUUIDMetadata:Q.bind(this,h,we),setUUIDMetadata:Q.bind(this,h,Ee),removeUUIDMetadata:Q.bind(this,h,Te),getAllChannelMetadata:Q.bind(this,h,Ae),getChannelMetadata:Q.bind(this,h,Ne),setChannelMetadata:Q.bind(this,h,ke),removeChannelMetadata:Q.bind(this,h,Ce),getChannelMembers:Q.bind(this,h,je),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 Vt(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)?Vt(a):a})),n}var Wt=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}(),$t={exports:{}},Jt={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 rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function sn(e,t,n,r){void 0===r&&(r=tn());var o,i=un(e,"",0,[],void 0,0,r)||e;try{o=0===en.length?JSON.stringify(i,t,n):JSON.stringify(i,cn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Zt.length;){var a=Zt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function un(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void rn(Xt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void rn(Xt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Sn('"allowMissing" argument must be a boolean');var n=Bn(e),r=n.length>0?n[0]:"",o=Hn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],Dn(n,xn([0,1],u)));for(var c=1,l=!0;c=n.length){var d=wn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=In(a,p),a=a[p];l&&!s&&(jn[i]=a)}}return a},zn={exports:{}};!function(e){var t=vn,n=qn,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}(zn);var Vn=qn,Wn=zn.exports,$n=Wn(Vn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),Qn="function"==typeof Map&&Map.prototype,Xn=Object.getOwnPropertyDescriptor&&Qn?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yn=Qn&&Xn&&"function"==typeof Xn.get?Xn.get:null,Zn=Qn&&Map.prototype.forEach,er="function"==typeof Set&&Set.prototype,tr=Object.getOwnPropertyDescriptor&&er?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,nr=er&&tr&&"function"==typeof tr.get?tr.get:null,rr=er&&Set.prototype.forEach,or="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,ir="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,sr=Boolean.prototype.valueOf,ur=Object.prototype.toString,cr=Function.prototype.toString,lr=String.prototype.match,pr=String.prototype.slice,fr=String.prototype.replace,hr=String.prototype.toUpperCase,dr=String.prototype.toLowerCase,yr=RegExp.prototype.test,gr=Array.prototype.concat,br=Array.prototype.join,vr=Array.prototype.slice,mr=Math.floor,_r="function"==typeof BigInt?BigInt.prototype.valueOf:null,Or=Object.getOwnPropertySymbols,Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Pr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,wr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Pr||"symbol")?Symbol.toStringTag:null,Er=Object.prototype.propertyIsEnumerable,Tr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Ar(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||yr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-mr(-e):mr(e);if(r!==e){var o=String(r),i=pr.call(t,o.length+1);return fr.call(o,n,"$&_")+"."+fr.call(fr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fr.call(t,n,"$&_")}var Nr=Jn,kr=Nr.custom,Cr=Ir(kr)?kr:null;function jr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Mr(e){return fr.call(String(e),/"/g,""")}function Rr(e){return!("[object Array]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ur(e){return!("[object RegExp]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}function Ir(e){if(Pr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Sr)return!1;try{return Sr.call(e),!0}catch(e){}return!1}var xr=Object.prototype.hasOwnProperty||function(e){return e in this};function Dr(e,t){return xr.call(e,t)}function Fr(e){return ur.call(e)}function Gr(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 Lr(pr.call(e,0,t.maxStringLength),t)+r}return jr(fr.call(fr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Kr),"single",t)}function Kr(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":"")+hr.call(t.toString(16))}function Br(e){return"Object("+e+")"}function Hr(e){return e+" { ? }"}function qr(e,t,n,r){return e+" ("+t+") {"+(r?zr(n,r):br.call(n,", "))+"}"}function zr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+br.call(e,","+n)+"\n"+t.prev}function Vr(e,t){var n=Rr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Wn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(Dr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Dr(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=!Dr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Dr(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(Dr(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 Lr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Ar(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Ar(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 Rr(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=br.call(Array(e.indent+1)," ")}return{base:n,prev:br.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Gr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=vr.call(o)).push(n),a){var s={depth:i.depth};return Dr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Ur(t)){var h=function(e){if(e.name)return e.name;var t=lr.call(cr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=Vr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+br.call(d,", ")+" }":"")}if(Ir(t)){var y=Pr?fr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Sr.call(t);return"object"!=typeof t||Pr?y:Br(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="<"+dr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Rr(t)){if(0===t.length)return"[]";var m=Vr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+zr(m,p)+"]":"[ "+br.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)){var _=Vr(t,f);return"cause"in Error.prototype||!("cause"in t)||Er.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+br.call(_,", ")+" }":"{ ["+String(t)+"] "+br.call(gr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(Cr&&"function"==typeof t[Cr]&&Nr)return Nr(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yn||!e||"object"!=typeof e)return!1;try{Yn.call(e);try{nr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Zn&&Zn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),qr("Map",Yn.call(t),O,p)}if(function(e){if(!nr||!e||"object"!=typeof e)return!1;try{nr.call(e);try{Yn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return rr&&rr.call(t,(function(e){S.push(f(e,t))})),qr("Set",nr.call(t),S,p)}if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{ir.call(e,ir)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Hr("WeakMap");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{ir.call(e,ir);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Hr("WeakSet");if(function(e){if(!ar||!e||"object"!=typeof e)return!1;try{return ar.call(e),!0}catch(e){}return!1}(t))return Hr("WeakRef");if(function(e){return!("[object Number]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!_r)return!1;try{return _r.call(e),!0}catch(e){}return!1}(t))return Br(f(_r.call(t)));if(function(e){return!("[object Boolean]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(sr.call(t));if(function(e){return!("[object String]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t))return Br(f(String(t)));if(!function(e){return!("[object Date]"!==Fr(e)||wr&&"object"==typeof e&&wr in e)}(t)&&!Ur(t)){var P=Vr(t,f),w=Tr?Tr(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&wr&&Object(t)===t&&wr in t?pr.call(Fr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+br.call(gr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+zr(P,p)+"}":A+"{ "+br.call(P,", ")+" }"}return String(t)},Qr=Wr("%TypeError%"),Xr=Wr("%WeakMap%",!0),Yr=Wr("%Map%",!0),Zr=$r("WeakMap.prototype.get",!0),eo=$r("WeakMap.prototype.set",!0),to=$r("WeakMap.prototype.has",!0),no=$r("Map.prototype.get",!0),ro=$r("Map.prototype.set",!0),oo=$r("Map.prototype.has",!0),io=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},ao=String.prototype.replace,so=/%20/g,uo="RFC3986",co={default:uo,formatters:{RFC1738:function(e){return ao.call(e,so,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:uo},lo=co,po=Object.prototype.hasOwnProperty,fo=Array.isArray,ho=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),yo=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(fo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===lo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=ho[u]:u<2048?a+=ho[192|u>>6]+ho[128|63&u]:u<55296||u>=57344?a+=ho[224|u>>12]+ho[128|u>>6&63]+ho[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=ho[240|u>>18]+ho[128|u>>12&63]+ho[128|u>>6&63]+ho[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(fo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(So(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&So(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},xo=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&&jo.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)}},Do=function(e,t){var n,r=e,o=function(e){if(!e)return Ao;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||Ao.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=mo.default;if(void 0!==e.format){if(!_o.call(mo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=mo.formatters[n],o=Ao.filter;return("function"==typeof e.filter||So(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ao.addQueryPrefix,allowDots:void 0===e.allowDots?Ao.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ao.charsetSentinel,delimiter:void 0===e.delimiter?Ao.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ao.encode,encoder:"function"==typeof e.encoder?e.encoder:Ao.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ao.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ao.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ao.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ao.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):So(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Oo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Oo[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=bo(),l=0;l0?h+f:""},Fo={formats:co,parse:function(e,t){var n=function(e){if(!e)return Ro;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?Ro.charset:e.charset;return{allowDots:void 0===e.allowDots?Ro.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Ro.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Ro.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Ro.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ro.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Ro.comma,decoder:"function"==typeof e.decoder?e.decoder:Ro.decoder,delimiter:"string"==typeof e.delimiter||Co.isRegExp(e.delimiter)?e.delimiter:Ro.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Ro.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Ro.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Ro.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Ro.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ro.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=Mo(l)?[l]:l),jo.call(r,c)?r[c]=Co.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])}}(Go);const Lo=Jn,Ko=Go.isObject,Bo=Go.hasOwn;var Ho=qo;function qo(){}qo.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},qo.prototype.parse=function(e){return this._parser=e,this},qo.prototype.responseType=function(e){return this._responseType=e,this},qo.prototype.serialize=function(e){return this._serializer=e,this},qo.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(Bo(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},qo.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 zo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),Vo=new Set([408,413,429,500,502,503,504,521,522,524]);qo.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&&Vo.has(t.status))return!0;if(e){if(e.code&&zo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},qo.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()},qo.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)},qo.prototype.catch=function(e){return this.then(void 0,e)},qo.prototype.use=function(e){return e(this),this},qo.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},qo.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},qo.prototype.get=function(e){return this._header[e.toLowerCase()]},qo.prototype.getHeader=qo.prototype.get,qo.prototype.set=function(e,t){if(Ko(e)){for(const t in e)Bo(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},qo.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},qo.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(Ko(e)){for(const t in e)Bo(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Bo(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},qo.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Lo.gte(process.version,"v13.0.0")&&Lo.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},qo.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},qo.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},qo.prototype.redirects=function(e){return this._maxRedirects=e,this},qo.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},qo.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},qo.prototype.send=function(e){const t=Ko(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&&Ko(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Bo(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},qo.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},qo.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("&")}}},qo.prototype._appendQueryString=()=>{console.warn("Unsupported")},qo.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)},qo.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 Wo=Go;var $o=Jo;function Jo(){}function Qo(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 Xo(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 Xo(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 Xo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}($t,$t.exports);var ni=$t.exports;function ri(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 oi(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ri)),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 ii(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=ni.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 ai(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function si(e,t,n){var r=ni.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function ui(e,t,n,r){var o=ni.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function ci(e,t,n,r){var o=ni.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return oi.call(this,o,n,r)}function li(e,t,n){var r=ni.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return oi.call(this,r,t,n)}function pi(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 fi,hi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=pi,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=pi(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}(),di=(fi=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}(),fi.supportsFile="undefined"!=typeof File,fi.supportsBlob="undefined"!=typeof Blob,fi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,fi.supportsBuffer=!1,fi.supportsStream=!1,fi.supportsString=!0,fi.supportsEncryptFile=!0,fi.supportsFileUri=!1,fi),yi=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new hi}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){return this.cryptor.decrypt(e.data)},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}(),gi=function(){function e(e){this.cipherKey=e.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,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:if(0===(t="string"==typeof e?(new TextEncoder).encode(e):e).byteLength)throw new Error("encryption error. empty content");return n=this._getIv(),[4,this._getKey()];case 1:return r=i.sent(),o={metadata:n},[4,crypto.subtle.encrypt({name:this.algo,iv:n},r,t)];case 2:return[2,(o.data=i.sent(),o)]}}))}))},e.prototype.decrypt=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(),[4,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)];case 2:return[2,n.sent()]}}))}))},e.BLOCK_SIZE=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(e){var t;this.defaultCryptor=e.default,this.cryptors=null!==(t=e.cryptors)&&void 0!==t?t:[]}return e.legacyCryptoModule=function(e){var t=e.config;return new this({default:new yi({config:t}),cryptors:[new gi(t.cipherKey)]})},e.aesCbcCryptoModule=function(e){return new this({default:new gi(e.cipherKey),cryptors:[new yi({config:e})]})},e.withDefaultCryptor=function(e){return new this({default:e})},e.prototype.getAllCryptors=function(){return u([this.defaultCryptor],s(this.cryptors),!1)},e.prototype.encrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,this.defaultCryptor.encrypt(e)];case 1:return(t=i.sent()).metadata?(n=vi.from(this.defaultCryptor.identifier,t.metadata),r=new Uint8Array(n.length),o=0,r.set(n.data,o),o+=n.length-t.metadata.byteLength,r.set(new Uint8Array(t.metadata),o),[2,this.concatArrayBuffer(r.buffer,t.data)]):[2,t.data]}}))}))},e.prototype.decrypt=function(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return i(this,(function(i){if(t="string"==typeof e?(new TextEncoder).encode(e):e,n=vi.tryParse(t),r=this.getCryptor(n),o=n.length>0?t.slice(n.length-n.metadataLength,n.length):null,t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return[2,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,o;return i(this,(function(i){switch(i.label){case 0:return this.defaultCryptor.identifier===vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:e.data instanceof ArrayBuffer?(r=(n=t).create,o={name:e.name,mimeType:"application/octet-stream"},[4,this.encrypt(e.data)]):[3,2];case 1:return[2,r.apply(n,[(o.data=i.sent(),o)])];case 2:return[2]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u;return i(this,(function(i){switch(i.label){case 0:return t.data instanceof ArrayBuffer?(r=vi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(s=(a=n).create,u={name:t.name},[4,this.decrypt(t.data)])):[3,2];case 1:return[2,s.apply(a,[(u.data=i.sent(),u)])];case 2:return[2]}}))}))},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")}if(e instanceof mi)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.LEGACY_IDENTIFIER="",e}(),vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new mi(t,n.byteLength)},e.tryParse=function(t){if(t.byteLength>=4&&t.slice(0,4).toString("utf8")!==e.SENTINEL)return"";if(!(t.byteLength>=5))throw new Error("decryption error. invalid header version");if(t[4]>e.MAX_VERSION)throw new q("unknown cryptor error");var n="",r=5+e.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("decryption error. invalid crypto identifier");n=t.slice(5,r);var o=null;if(!(t.byteLength>=r+1))throw new Error("decryption error. invalid metadata length");return o=t[r],r+=1,255===o&&t.byteLength>=r+2&&(o=new Uint16Array(t.slice(r,r+2)).reduce((function(e,t){return(e<<8)+t}),0),r+=2),new mi(n.toString("utf8"),o)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e}(),mi=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 vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return vi.SENTINEL.length+1+vi.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(vi.SENTINEL)),t[e+=vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=vi.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 _i(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Oi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new zt({del:li,get:si,post:ui,patch:ci,sendBeacon:_i,getfile:ai,postfile:ii}),t.cbor=new Wt((function(e){return Vt(f.decode(e))}),b),t.PubNubFile=di,t.cryptography=new hi,t.initCryptoModule=function(e){return new bi({default:new yi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new gi({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}(qt);return Oi})); +!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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A(e),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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;return i(this,(function(i){switch(i.label){case 0:return r=bi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(a=this.getFileData(t.data),s=a.slice(r.length-r.metadataLength,r.length),c=(u=n).create,l={name:t.name},[4,this.defaultCryptor.decryptFileData({data:t.data.slice(r.length),metadata:s})]);case 1:return[2,c.apply(u,[(l.data=i.sent(),l)])]}}))}))},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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); diff --git a/lib/core/components/config.js b/lib/core/components/config.js index 578c73f57..3512450ed 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -92,9 +92,11 @@ var default_1 = /** @class */ (function () { return this; }; default_1.prototype.setCipherKey = function (val, setup, modules) { + var _a; this.cipherKey = val; if (this.cipherKey) { - this.cryptoModule = setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); + this.cryptoModule = + (_a = setup.cryptoModule) !== null && _a !== void 0 ? _a : setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs }); if (modules) modules.cryptoModule = this.cryptoModule; } diff --git a/lib/core/endpoints/file_upload/publish_file.js b/lib/core/endpoints/file_upload/publish_file.js index 96fc6e715..9a0a5584a 100644 --- a/lib/core/endpoints/file_upload/publish_file.js +++ b/lib/core/endpoints/file_upload/publish_file.js @@ -6,12 +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) { + if (modules.cryptoModule) { var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); - stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode(encrypted); + stringifiedPayload = typeof encrypted === 'string' ? encrypted : (0, base64_codec_1.encode)(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; diff --git a/lib/core/endpoints/publish.js b/lib/core/endpoints/publish.js index 5bafeff87..6799ecc64 100644 --- a/lib/core/endpoints/publish.js +++ b/lib/core/endpoints/publish.js @@ -15,7 +15,7 @@ function prepareMessagePayload(modules, messagePayload) { 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 5fbc02585..23aac74b2 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -155,16 +155,16 @@ var default_1 = /** @class */ (function () { }; this.File = setup.PubNubFile; this.encryptFile = function (key, file) { - if (arguments.length == 1 && typeof key != 'string' && cryptoModule) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; - return cryptoModule.encryptFile(file, this.File); + 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' && cryptoModule) { + if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; - return cryptoModule.decryptFile(file, this.File); + return modules.cryptoModule.decryptFile(file, this.File); } return cryptography.decryptFile(key, file, this.File); }; @@ -198,7 +198,7 @@ var default_1 = /** @class */ (function () { config: modules.config, listenerManager: listenerManager, getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, - cryptoModule: cryptoModule, + cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -489,8 +489,8 @@ var default_1 = /** @class */ (function () { // --- deprecated ------------------ // mount crypto this.encrypt = function (data, key) { - if (typeof key === 'undefined' && cryptoModule) { - var encrypted = cryptoModule.encrypt(data); + if (typeof key === 'undefined' && modules.cryptoModule) { + var encrypted = modules.cryptoModule.encrypt(data); return typeof encrypted === 'string' ? encrypted : (0, base64_codec_1.encode)(encrypted); } else { @@ -499,7 +499,7 @@ var default_1 = /** @class */ (function () { }; this.decrypt = function (data, key) { if (typeof key === 'undefined' && cryptoModule) { - var decrypted = cryptoModule.decrypt(data); + var decrypted = modules.cryptoModule.decrypt(data); return decrypted instanceof ArrayBuffer ? (0, base64_codec_1.encode)(decrypted) : decrypted; } else { diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 951e9576a..1b8870ac9 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -79,16 +79,15 @@ var CryptoModule = /** @class */ (function () { } // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: type detection issue with old Config type assignment - CryptoModule.legacyCryptoModule = function (_a) { - var config = _a.config; + CryptoModule.legacyCryptoModule = function (config) { return new this({ default: new legacyCryptor_1.default({ config: config }), - cryptors: [new aesCbcCryptor_1.default(config.cipherKey)], + cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], }); }; CryptoModule.aesCbcCryptoModule = function (config) { return new this({ - default: new aesCbcCryptor_1.default(config.cipherKey), + default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), cryptors: [new legacyCryptor_1.default({ config: config })], }); }; diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js index 21273869f..78f35385e 100644 --- a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -45,7 +45,7 @@ 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.cryptor = new index_1.default(config); this.fileCryptor = new node_1.default(); } Object.defineProperty(LegacyCryptor.prototype, "identifier", { diff --git a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js index 3b35ddc41..5a16a5d10 100644 --- a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js @@ -35,10 +35,18 @@ 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 }; +}; 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"); +// ts check disabled: CryptoJs does not have types specified 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 () { @@ -54,10 +62,10 @@ var AesCbcCryptor = /** @class */ (function () { enumerable: false, configurable: true }); - AesCbcCryptor.prototype._getIv = function () { + AesCbcCryptor.prototype.getIv = function () { return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE)); }; - AesCbcCryptor.prototype._getKey = function () { + AesCbcCryptor.prototype.getKey = function () { return __awaiter(this, void 0, void 0, function () { var bKey, abHash; return __generator(this, function (_a) { @@ -67,51 +75,72 @@ var AesCbcCryptor = /** @class */ (function () { return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)]; case 1: abHash = _a.sent(); - return [2 /*return*/, crypto.subtle.importKey('raw', abHash, 'AES-CBC', true, ['encrypt', 'decrypt'])]; + 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 dataBytes, abIv, key; + var key, iv; var _a; return __generator(this, function (_b) { switch (_b.label) { - case 0: - dataBytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; - if (dataBytes.byteLength === 0) - throw new Error('encryption error. empty content'); - abIv = this._getIv(); - return [4 /*yield*/, this._getKey()]; + case 0: return [4 /*yield*/, this.getKey()]; case 1: key = _b.sent(); - _a = { - metadata: abIv - }; - return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: abIv }, key, dataBytes)]; + 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.decrypt = function (encryptedData) { + AesCbcCryptor.prototype.decryptFileData = function (encryptedData) { return __awaiter(this, void 0, void 0, function () { - var key, decryptedData; + var key; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this._getKey()]; + case 0: return [4 /*yield*/, this.getKey()]; case 1: key = _a.sent(); - return [4 /*yield*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)]; - case 2: - decryptedData = _a.sent(); - return [2 /*return*/, decryptedData]; + 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(); diff --git a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js index a6ac9416f..1c37c6f42 100644 --- a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js @@ -41,10 +41,11 @@ var __importDefault = (this && this.__importDefault) || function (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.cryptor = new index_1.default(config); this.fileCryptor = new web_1.default(); } Object.defineProperty(LegacyCryptor.prototype, "identifier", { @@ -62,7 +63,8 @@ var LegacyCryptor = /** @class */ (function () { }; }; LegacyCryptor.prototype.decrypt = function (encryptedData) { - return this.cryptor.decrypt(encryptedData.data); + 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; diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index 167337a47..cd5597048 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -65,11 +65,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CryptoModule = exports.AesCbcCryptor = exports.LegacyCryptor = void 0; -var endpoint_1 = require("../../../core/components/endpoint"); 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; @@ -78,16 +78,15 @@ var CryptoModule = /** @class */ (function () { } // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore: type detection issue with old Config type assignment - CryptoModule.legacyCryptoModule = function (_a) { - var config = _a.config; + CryptoModule.legacyCryptoModule = function (config) { return new this({ default: new legacyCryptor_1.default({ config: config }), - cryptors: [new aesCbcCryptor_1.default(config.cipherKey)], + cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], }); }; CryptoModule.aesCbcCryptoModule = function (config) { return new this({ - default: new aesCbcCryptor_1.default(config.cipherKey), + default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), cryptors: [new legacyCryptor_1.default({ config: config })], }); }; @@ -98,96 +97,70 @@ var CryptoModule = /** @class */ (function () { return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); }; CryptoModule.prototype.encrypt = function (data) { - return __awaiter(this, void 0, void 0, function () { - var encrypted, header, headerData, pos; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.defaultCryptor.encrypt(data)]; - case 1: - encrypted = _a.sent(); - if (!encrypted.metadata) - return [2 /*return*/, encrypted.data]; - header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - headerData = new Uint8Array(header.length); - pos = 0; - headerData.set(header.data, pos); - pos += header.length - encrypted.metadata.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - return [2 /*return*/, this.concatArrayBuffer(headerData.buffer, encrypted.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) { - return __awaiter(this, void 0, void 0, function () { - var encryptedData, header, cryptor, metadata; - return __generator(this, function (_a) { - encryptedData = typeof data === 'string' ? new TextEncoder().encode(data) : data; - header = CryptorHeader.tryParse(encryptedData); - cryptor = this.getCryptor(header); - 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 [2 /*return*/, cryptor.decrypt({ - data: encryptedData.slice(header.length), - metadata: metadata, - })]; - }); + 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 _a, _b; - var _c; - return __generator(this, function (_d) { - switch (_d.label) { + var fileData, encrypted; + 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 default cryptor) - */ if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return [2 /*return*/, this.defaultCryptor.encryptFile(file, File)]; - if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; - _b = (_a = File).create; - _c = { - name: file.name, - mimeType: 'application/octet-stream' - }; - return [4 /*yield*/, this.encrypt(file.data)]; - case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), - _c)])]; - case 2: return [2 /*return*/]; + fileData = this.getFileData(file.data); + return [4 /*yield*/, this.defaultCryptor.encryptFileData(fileData)]; + case 1: + 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 header, cryptor, _a, _b; + var header, cryptor, fileData, metadata, _a, _b; var _c; return __generator(this, function (_d) { switch (_d.label) { case 0: - if (!(file.data instanceof ArrayBuffer)) return [3 /*break*/, 2]; 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)]; + fileData = this.getFileData(file.data); + metadata = fileData.slice(header.length - header.metadataLength, header.length); _b = (_a = File).create; _c = { name: file.name }; - return [4 /*yield*/, this.decrypt(file.data)]; + return [4 /*yield*/, this.defaultCryptor.decryptFileData({ + data: file.data.slice(header.length), + metadata: metadata, + })]; case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), _c)])]; - case 2: return [2 /*return*/]; } }); }); @@ -197,7 +170,7 @@ var CryptoModule = /** @class */ (function () { var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; }); if (cryptor) return cryptor; - throw new Error('unknown cryptor'); + throw new Error('unknown cryptor error'); } else if (header instanceof CryptorHeaderV1) { return this.getCryptorFromId(header.identifier); @@ -216,7 +189,29 @@ var CryptoModule = /** @class */ (function () { 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) { + 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 decryption supports only string or ArrayBuffer'); + }; CryptoModule.LEGACY_IDENTIFIER = ''; + CryptoModule.encoder = new TextEncoder(); + CryptoModule.decoder = new TextDecoder(); return CryptoModule; }()); exports.CryptoModule = CryptoModule; @@ -229,12 +224,13 @@ var CryptorHeader = /** @class */ (function () { return; return new CryptorHeaderV1(id, metadata.byteLength); }; - CryptorHeader.tryParse = function (encryptedData) { + CryptorHeader.tryParse = function (data) { + var encryptedData = new Uint8Array(data); var sentinel = ''; var version = null; if (encryptedData.byteLength >= 4) { sentinel = encryptedData.slice(0, 4); - if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL) + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) return ''; } if (encryptedData.byteLength >= 5) { @@ -244,7 +240,7 @@ var CryptorHeader = /** @class */ (function () { throw new Error('decryption error. invalid header version'); } if (version > CryptorHeader.MAX_VERSION) - throw new endpoint_1.PubNubError('unknown cryptor error'); + throw new Error('unknown cryptor error'); var identifier = ''; var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; if (encryptedData.byteLength >= pos) { @@ -265,13 +261,14 @@ var CryptorHeader = /** @class */ (function () { 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); + 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 diff --git a/lib/node/index.js b/lib/node/index.js index 4e8bd742d..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")); @@ -27,38 +28,40 @@ var node_1 = require("../networking/modules/node"); var node_2 = __importDefault(require("../crypto/modules/node")); var node_3 = __importDefault(require("../file/modules/node")); var nodeCryptoModule_1 = require("../crypto/modules/NodeCryptoModule/nodeCryptoModule"); -module.exports = /** @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 })], +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, }); - }; - if (!('ssl' in setup)) { - setup.ssl = true; + 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; } - _this = _super.call(this, setup) || this; - return _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 57954665d..fcda537bb 100644 --- a/lib/web/index.js +++ b/lib/web/index.js @@ -78,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; From cd913be5f527d6097e4cd290d3fd2acd8c0ed370 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 9 Oct 2023 12:18:28 +0530 Subject: [PATCH 29/38] fix: test- customEncrypt function --- dist/web/pubnub.js | 4 ++-- dist/web/pubnub.min.js | 2 +- lib/core/components/cryptography/index.js | 4 ++-- src/core/components/cryptography/index.js | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index cba073996..d376e8613 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -1658,13 +1658,13 @@ return hmacSha256.lib.WordArray.random(16); }; default_1.prototype.encrypt = function (data, customCipherKey, options) { - if (this._config.customEncrypt) { + if (typeof this._config.customEncrypt != 'undefined' && this._config.customEncrypt) { return this._config.customEncrypt(data); } return this.pnEncrypt(data, customCipherKey, options); }; default_1.prototype.decrypt = function (data, customCipherKey, options) { - if (this._config.customDecrypt) { + if (typeof this._config.customDecrypt != 'undefined' && this._config.customDecrypt) { return this._config.customDecrypt(data); } return this.pnDecrypt(data, customCipherKey, options); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index b4cad2705..c6b58fb58 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A(e),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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;return i(this,(function(i){switch(i.label){case 0:return r=bi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(a=this.getFileData(t.data),s=a.slice(r.length-r.metadataLength,r.length),c=(u=n).create,l={name:t.name},[4,this.defaultCryptor.decryptFileData({data:t.data.slice(r.length),metadata:s})]);case 1:return[2,c.apply(u,[(l.data=i.sent(),l)])]}}))}))},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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); +!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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A(e),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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;return i(this,(function(i){switch(i.label){case 0:return r=bi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(a=this.getFileData(t.data),s=a.slice(r.length-r.metadataLength,r.length),c=(u=n).create,l={name:t.name},[4,this.defaultCryptor.decryptFileData({data:t.data.slice(r.length),metadata:s})]);case 1:return[2,c.apply(u,[(l.data=i.sent(),l)])]}}))}))},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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); diff --git a/lib/core/components/cryptography/index.js b/lib/core/components/cryptography/index.js index 19c58e51e..59c65b452 100644 --- a/lib/core/components/cryptography/index.js +++ b/lib/core/components/cryptography/index.js @@ -87,13 +87,13 @@ var default_1 = /** @class */ (function () { return hmac_sha256_1.default.lib.WordArray.random(16); }; default_1.prototype.encrypt = function (data, customCipherKey, options) { - if (this._config.customEncrypt) { + if (typeof this._config.customEncrypt != 'undefined' && this._config.customEncrypt) { return this._config.customEncrypt(data); } return this.pnEncrypt(data, customCipherKey, options); }; default_1.prototype.decrypt = function (data, customCipherKey, options) { - if (this._config.customDecrypt) { + if (typeof this._config.customDecrypt != 'undefined' && this._config.customDecrypt) { return this._config.customDecrypt(data); } return this.pnDecrypt(data, customCipherKey, options); diff --git a/src/core/components/cryptography/index.js b/src/core/components/cryptography/index.js index 1e72663eb..771a72605 100644 --- a/src/core/components/cryptography/index.js +++ b/src/core/components/cryptography/index.js @@ -108,14 +108,14 @@ export default class { } encrypt(data, customCipherKey, options) { - if (this._config.customEncrypt) { + if (typeof this._config.customEncrypt != 'undefined' && this._config.customEncrypt) { return this._config.customEncrypt(data); } return this.pnEncrypt(data, customCipherKey, options); } decrypt(data, customCipherKey, options) { - if (this._config.customDecrypt) { + if (typeof this._config.customDecrypt != 'undefined' && this._config.customDecrypt) { return this._config.customDecrypt(data); } return this.pnDecrypt(data, customCipherKey, options); From ed97050c97f1ada2dacae66a395bdf7762746765 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 9 Oct 2023 12:46:51 +0530 Subject: [PATCH 30/38] fix: legacy crypto init, tests --- dist/web/pubnub.js | 10 +++++----- dist/web/pubnub.min.js | 2 +- lib/core/components/cryptography/index.js | 4 ++-- .../modules/NodeCryptoModule/NodeCryptoModule.js | 4 ++-- lib/crypto/modules/NodeCryptoModule/legacyCryptor.js | 2 +- lib/crypto/modules/WebCryptoModule/legacyCryptor.js | 2 +- lib/crypto/modules/WebCryptoModule/webCryptoModule.js | 4 ++-- src/core/components/cryptography/index.js | 5 ++--- src/crypto/modules/NodeCryptoModule/legacyCryptor.ts | 2 +- .../modules/NodeCryptoModule/nodeCryptoModule.ts | 4 ++-- src/crypto/modules/WebCryptoModule/legacyCryptor.ts | 2 +- src/crypto/modules/WebCryptoModule/webCryptoModule.ts | 4 ++-- 12 files changed, 22 insertions(+), 23 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index d376e8613..602ee2954 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -1658,13 +1658,13 @@ return hmacSha256.lib.WordArray.random(16); }; default_1.prototype.encrypt = function (data, customCipherKey, options) { - if (typeof this._config.customEncrypt != 'undefined' && this._config.customEncrypt) { + if (this._config.customEncrypt) { return this._config.customEncrypt(data); } return this.pnEncrypt(data, customCipherKey, options); }; default_1.prototype.decrypt = function (data, customCipherKey, options) { - if (typeof this._config.customDecrypt != 'undefined' && this._config.customDecrypt) { + if (this._config.customDecrypt) { return this._config.customDecrypt(data); } return this.pnDecrypt(data, customCipherKey, options); @@ -12914,7 +12914,7 @@ var LegacyCryptor = /** @class */ (function () { function LegacyCryptor(config) { this.config = config; - this.cryptor = new default_1$a(config); + this.cryptor = new default_1$a({ config: config }); this.fileCryptor = new WebCryptography(); } Object.defineProperty(LegacyCryptor.prototype, "identifier", { @@ -13073,14 +13073,14 @@ //@ts-ignore: type detection issue with old Config type assignment CryptoModule.legacyCryptoModule = function (config) { return new this({ - default: new LegacyCryptor({ config: config }), + default: new LegacyCryptor(config), cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); }; CryptoModule.aesCbcCryptoModule = function (config) { return new this({ default: new AesCbcCryptor({ cipherKey: config.cipherKey }), - cryptors: [new LegacyCryptor({ config: config })], + cryptors: [new LegacyCryptor(config)], }); }; CryptoModule.withDefaultCryptor = function (defaultCryptor) { diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index c6b58fb58..c84fd40c5 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A(e),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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;return i(this,(function(i){switch(i.label){case 0:return r=bi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(a=this.getFileData(t.data),s=a.slice(r.length-r.metadataLength,r.length),c=(u=n).create,l={name:t.name},[4,this.defaultCryptor.decryptFileData({data:t.data.slice(r.length),metadata:s})]);case 1:return[2,c.apply(u,[(l.data=i.sent(),l)])]}}))}))},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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); +!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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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;return i(this,(function(i){switch(i.label){case 0:return r=bi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(a=this.getFileData(t.data),s=a.slice(r.length-r.metadataLength,r.length),c=(u=n).create,l={name:t.name},[4,this.defaultCryptor.decryptFileData({data:t.data.slice(r.length),metadata:s})]);case 1:return[2,c.apply(u,[(l.data=i.sent(),l)])]}}))}))},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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); diff --git a/lib/core/components/cryptography/index.js b/lib/core/components/cryptography/index.js index 59c65b452..19c58e51e 100644 --- a/lib/core/components/cryptography/index.js +++ b/lib/core/components/cryptography/index.js @@ -87,13 +87,13 @@ var default_1 = /** @class */ (function () { return hmac_sha256_1.default.lib.WordArray.random(16); }; default_1.prototype.encrypt = function (data, customCipherKey, options) { - if (typeof this._config.customEncrypt != 'undefined' && this._config.customEncrypt) { + if (this._config.customEncrypt) { return this._config.customEncrypt(data); } return this.pnEncrypt(data, customCipherKey, options); }; default_1.prototype.decrypt = function (data, customCipherKey, options) { - if (typeof this._config.customDecrypt != 'undefined' && this._config.customDecrypt) { + if (this._config.customDecrypt) { return this._config.customDecrypt(data); } return this.pnDecrypt(data, customCipherKey, options); diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 1b8870ac9..4107519c5 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -81,14 +81,14 @@ var CryptoModule = /** @class */ (function () { // @ts-ignore: type detection issue with old Config type assignment CryptoModule.legacyCryptoModule = function (config) { return new this({ - default: new legacyCryptor_1.default({ config: config }), + default: new legacyCryptor_1.default(config), cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], }); }; CryptoModule.aesCbcCryptoModule = function (config) { return new this({ default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), - cryptors: [new legacyCryptor_1.default({ config: config })], + cryptors: [new legacyCryptor_1.default(config)], }); }; CryptoModule.withDefaultCryptor = function (defaultCryptor) { diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js index 78f35385e..21273869f 100644 --- a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -45,7 +45,7 @@ var node_1 = __importDefault(require("../node")); var LegacyCryptor = /** @class */ (function () { function LegacyCryptor(config) { this.config = config; - this.cryptor = new index_1.default(config); + this.cryptor = new index_1.default({ config: config }); this.fileCryptor = new node_1.default(); } Object.defineProperty(LegacyCryptor.prototype, "identifier", { diff --git a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js index 1c37c6f42..9b318e359 100644 --- a/lib/crypto/modules/WebCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/legacyCryptor.js @@ -45,7 +45,7 @@ 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); + this.cryptor = new index_1.default({ config: config }); this.fileCryptor = new web_1.default(); } Object.defineProperty(LegacyCryptor.prototype, "identifier", { diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index cd5597048..26bd9a3f1 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -80,14 +80,14 @@ var CryptoModule = /** @class */ (function () { //@ts-ignore: type detection issue with old Config type assignment CryptoModule.legacyCryptoModule = function (config) { return new this({ - default: new legacyCryptor_1.default({ config: config }), + default: new legacyCryptor_1.default(config), cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })], }); }; CryptoModule.aesCbcCryptoModule = function (config) { return new this({ default: new aesCbcCryptor_1.default({ cipherKey: config.cipherKey }), - cryptors: [new legacyCryptor_1.default({ config: config })], + cryptors: [new legacyCryptor_1.default(config)], }); }; CryptoModule.withDefaultCryptor = function (defaultCryptor) { diff --git a/src/core/components/cryptography/index.js b/src/core/components/cryptography/index.js index 771a72605..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']; @@ -108,14 +107,14 @@ export default class { } encrypt(data, customCipherKey, options) { - if (typeof this._config.customEncrypt != 'undefined' && this._config.customEncrypt) { + if (this._config.customEncrypt) { return this._config.customEncrypt(data); } return this.pnEncrypt(data, customCipherKey, options); } decrypt(data, customCipherKey, options) { - if (typeof this._config.customDecrypt != 'undefined' && this._config.customDecrypt) { + if (this._config.customDecrypt) { return this._config.customDecrypt(data); } return this.pnDecrypt(data, customCipherKey, options); diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts index 3fadc4125..c8a28fc6b 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -12,7 +12,7 @@ export default class LegacyCryptor implements ILegacyCryptor { constructor(config: any) { this.config = config; - this.cryptor = new Crypto(config); + this.cryptor = new Crypto({ config }); this.fileCryptor = new FileCryptor(); } get identifier() { diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 610fff8b2..5b7975d19 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -29,7 +29,7 @@ export class CryptoModule { // @ts-ignore: type detection issue with old Config type assignment static legacyCryptoModule(config) { return new this({ - default: new LegacyCryptor({ config }), + default: new LegacyCryptor(config), cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); } @@ -37,7 +37,7 @@ export class CryptoModule { static aesCbcCryptoModule(config: any) { return new this({ default: new AesCbcCryptor({ cipherKey: config.cipherKey }), - cryptors: [new LegacyCryptor({ config })], + cryptors: [new LegacyCryptor(config)], }); } static withDefaultCryptor(defaultCryptor: CryptorType) { diff --git a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts index 81fc1b06f..db4b96bed 100644 --- a/src/crypto/modules/WebCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/legacyCryptor.ts @@ -12,7 +12,7 @@ export default class LegacyCryptor implements ILegacyCryptor { constructor(config: any) { this.config = config; - this.cryptor = new Crypto(config); + this.cryptor = new Crypto({ config }); this.fileCryptor = new FileCryptor(); } diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index e292eb426..2a03430fe 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -29,7 +29,7 @@ export class CryptoModule { //@ts-ignore: type detection issue with old Config type assignment static legacyCryptoModule(config) { return new this({ - default: new LegacyCryptor({ config }), + default: new LegacyCryptor(config), cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); } @@ -37,7 +37,7 @@ export class CryptoModule { static aesCbcCryptoModule(config: any) { return new this({ default: new AesCbcCryptor({ cipherKey: config.cipherKey }), - cryptors: [new LegacyCryptor({ config })], + cryptors: [new LegacyCryptor(config)], }); } From acaacad9c9008a13ba8af8e2f4ab1c35aeba8059 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 9 Oct 2023 17:39:48 +0530 Subject: [PATCH 31/38] refactor: typecheck on incoming data for aescbc cryptor --- lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js | 2 +- src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js index 34c964471..675ec6a83 100644 --- a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js @@ -67,7 +67,7 @@ var AesCbcCryptor = /** @class */ (function () { AesCbcCryptor.prototype.encrypt = function (data) { var iv = this.getIv(); var key = this.getKey(); - var plainData = data instanceof ArrayBuffer ? data : new TextEncoder().encode(data); + 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'); diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts index fc84987b2..8d439d110 100644 --- a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts @@ -31,7 +31,7 @@ export default class AesCbcCryptor implements ICryptor { encrypt(data: ArrayBuffer | string) { const iv = this.getIv(); const key = this.getKey(); - const plainData = data instanceof ArrayBuffer ? data : new TextEncoder().encode(data); + 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); From 992c8febaaa9ae17d37951f7341e26cf7ed14588 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Fri, 13 Oct 2023 00:03:01 +0530 Subject: [PATCH 32/38] code cleanup, * fix: broken file cryptography operations on web --- .../endpoints/file_upload/download_file.js | 12 +++++--- src/core/endpoints/file_upload/send_file.js | 9 ++++-- .../modules/WebCryptoModule/ILegacyCryptor.ts | 2 +- .../modules/WebCryptoModule/aesCbcCryptor.ts | 1 - .../WebCryptoModule/webCryptoModule.ts | 10 ++++--- src/crypto/modules/web.js | 28 +++++-------------- 6 files changed, 28 insertions(+), 34 deletions(-) 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/send_file.js b/src/core/endpoints/file_upload/send_file.js index 5eb8be763..f2d2fb810 100644 --- a/src/core/endpoints/file_upload/send_file.js +++ b/src/core/endpoints/file_upload/send_file.js @@ -3,7 +3,7 @@ import { PubNubError, createValidationError } from '../../components/endpoint'; 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) { @@ -27,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; diff --git a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts index 9538fa18a..c9ae022c0 100644 --- a/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/ILegacyCryptor.ts @@ -1,7 +1,7 @@ import { EncryptedDataType } from './ICryptor'; export type PubNubFileType = { - data: ArrayBuffer; + data: File | Blob; name: string; mimeType: string; diff --git a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts index 0fb2600f7..78bda2175 100644 --- a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -2,7 +2,6 @@ import { ICryptor, EncryptedDataType } from './ICryptor'; import cryptoJS from '../../../core/components/cryptography/hmac-sha256'; import { decode } from '../../../core/components/base64_codec'; -// ts check disabled: CryptoJs does not have types specified export default class AesCbcCryptor implements ICryptor { static BLOCK_SIZE = 16; static encoder = new TextEncoder(); diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index 2a03430fe..c82773681 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -84,16 +84,18 @@ export class CryptoModule { } async decryptFile(file: PubNubFileType, File: PubNubFileType) { - const header = CryptorHeader.tryParse(file.data); + const data = await file.data.arrayBuffer(); + const header = CryptorHeader.tryParse(data); const cryptor = this.getCryptor(header); - if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) + if (cryptor?.identifier === CryptoModule.LEGACY_IDENTIFIER) { return (cryptor as ILegacyCryptor).decryptFile(file, File); - const fileData = this.getFileData(file.data); + } + const fileData = 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: file.data.slice(header.length), + data: data.slice(header.length), metadata: metadata, }), }); diff --git a/src/crypto/modules/web.js b/src/crypto/modules/web.js index 90d0280c3..20e1a274b 100644 --- a/src/crypto/modules/web.js +++ b/src/crypto/modules/web.js @@ -9,18 +9,6 @@ function concatArrayBuffer(ab1, ab2) { return tmp.buffer; } -function ab2hex(ab) { - return [...new Uint8Array(ab)].map((x) => x.toString(16).padStart(2, '0')).join(''); -} - -function hex2ab(hex) { - return new Uint8Array( - hex.match(/[\da-f]{2}/gi).map(function (h) { - return parseInt(h, 16); - }), - ); -} - export default class WebCryptography { static IV_LENGTH = 16; static encoder = new TextEncoder(); @@ -44,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); } @@ -58,7 +45,7 @@ export default class WebCryptography { 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); @@ -72,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({ @@ -83,11 +69,11 @@ export default class WebCryptography { } async getKey(key) { - const bKey = WebCryptography.encoder.encode(key); - const abHash = await crypto.subtle.digest('SHA-256', bKey.buffer); - - const abKey = hex2ab(ab2hex(abHash).slice(0, 32)).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']); } From c17fca3c9102bfe5221c4002ff29f264cc180450 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Fri, 13 Oct 2023 00:03:31 +0530 Subject: [PATCH 33/38] lib and dist directories --- dist/web/pubnub.js | 195 +++++++++--------- dist/web/pubnub.min.js | 2 +- .../endpoints/file_upload/download_file.js | 27 ++- lib/core/endpoints/file_upload/send_file.js | 128 ++++++------ .../modules/WebCryptoModule/aesCbcCryptor.js | 1 - .../WebCryptoModule/webCryptoModule.js | 17 +- lib/crypto/modules/web.js | 50 +---- 7 files changed, 209 insertions(+), 211 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 602ee2954..7eea98515 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -4769,13 +4769,13 @@ 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")); @@ -4786,13 +4786,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) { @@ -4801,48 +4809,48 @@ return entry; }); } - _s.label = 4; - case 4: - _s.trys.push([4, 18, , 19]); - 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*/, 19]; + 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(); + 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); @@ -4851,16 +4859,16 @@ else { throw new PubNubError('Upload to bucket failed.', e_1); } - case 19: + case 22: if (result.status !== 204) { throw new PubNubError('Upload to bucket was unsuccessful', result); } retries = config.fileUploadPublishRetryLimit; wasSuccessful = false; publishResult = { timetoken: '0' }; - _s.label = 20; - case 20: - _s.trys.push([20, 22, , 23]); + _t.label = 23; + case 23: + _t.trys.push([23, 25, , 26]); return [4 /*yield*/, publishFile({ channel: channel, message: message, @@ -4870,19 +4878,19 @@ storeInHistory: storeInHistory, ttl: ttl, })]; - case 21: + case 24: /* eslint-disable-next-line no-await-in-loop */ - publishResult = _s.sent(); + publishResult = _t.sent(); wasSuccessful = true; - return [3 /*break*/, 23]; - case 22: - _s.sent(); + return [3 /*break*/, 26]; + case 25: + _t.sent(); retries -= 1; - return [3 /*break*/, 23]; - case 23: - if (!wasSuccessful && retries > 0) return [3 /*break*/, 20]; - _s.label = 24; - case 24: + return [3 /*break*/, 26]; + case 26: + if (!wasSuccessful && retries > 0) return [3 /*break*/, 23]; + _t.label = 27; + case 27: if (!wasSuccessful) { throw new PubNubError('Publish failed. You may want to execute that operation manually using pubnub.publishFile', { channel: channel, @@ -4949,7 +4957,7 @@ return "".concat(networking.getStandardOrigin()).concat(url); }); - /** */ + // Download_file.js var endpoint$g = { getOperation: function () { return OPERATIONS.PNDownloadFileOperation; }, validateParams: function (_, params) { @@ -4977,20 +4985,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, @@ -12607,14 +12623,6 @@ tmp.set(new Uint8Array(ab2), ab1.byteLength); return tmp.buffer; } - function ab2hex(ab) { - return __spreadArray([], __read(new Uint8Array(ab)), false).map(function (x) { return x.toString(16).padStart(2, '0'); }).join(''); - } - function hex2ab(hex) { - return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { - return parseInt(h, 16); - })); - } var WebCryptography = /** @class */ (function () { function WebCryptography() { } @@ -12674,7 +12682,7 @@ 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)]; @@ -12697,7 +12705,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)]; @@ -12713,15 +12721,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 = WebCryptography.encoder.encode(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 = hex2ab(ab2hex(abHash).slice(0, 32)).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'])]; } }); @@ -12957,7 +12966,6 @@ return LegacyCryptor; }()); - // ts check disabled: CryptoJs does not have types specified var AesCbcCryptor = /** @class */ (function () { function AesCbcCryptor(configuration) { this.cipherKey = configuration.cipherKey; @@ -13133,26 +13141,29 @@ }; CryptoModule.prototype.decryptFile = function (file, File) { return __awaiter(this, void 0, void 0, function () { - var header, cryptor, fileData, metadata, _a, _b; + var data, header, cryptor, fileData, metadata, _a, _b; var _c; return __generator(this, function (_d) { switch (_d.label) { - case 0: - header = CryptorHeader.tryParse(file.data); + 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) + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) { return [2 /*return*/, cryptor.decryptFile(file, File)]; - fileData = this.getFileData(file.data); + } + fileData = this.getFileData(data); metadata = fileData.slice(header.length - header.metadataLength, header.length); _b = (_a = File).create; _c = { name: file.name }; return [4 /*yield*/, this.defaultCryptor.decryptFileData({ - data: file.data.slice(header.length), + data: data.slice(header.length), metadata: metadata, })]; - case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + case 2: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), _c)])]; } }); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index c84fd40c5..a7ab4ba61 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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.networking;return function(e){var a=e.channel,p=e.file,f=e.message,h=e.cipherKey,d=e.meta,y=e.ttl,g=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,m,_,O,S,P,w,E,T,A,N,k,C,j,M,R,U,I,x,D,F,G,L,K;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(!p)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(p),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,m=t.data,_=m.id,O=m.name,s.supportsEncryptFile&&(null!=h?h:u.cipherKey)?[4,c.encryptFile(null!=h?h:u.cipherKey,e,s)]:[3,3];case 2:e=i.sent(),i.label=3;case 3:S=v,e.mimeType&&(S=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=4;case 4:return i.trys.push([4,18,,19]),s.supportsFileUri&&p.uri?(E=(w=l).POSTFILE,T=[b,S],[4,e.toFileUri()]):[3,7];case 5:return[4,E.apply(w,T.concat([i.sent()]))];case 6:return P=i.sent(),[3,17];case 7:return s.supportsFile?(N=(A=l).POSTFILE,k=[b,S],[4,e.toFile()]):[3,10];case 8:return[4,N.apply(A,k.concat([i.sent()]))];case 9:return P=i.sent(),[3,17];case 10:return s.supportsBuffer?(j=(C=l).POSTFILE,M=[b,S],[4,e.toBuffer()]):[3,13];case 11:return[4,j.apply(C,M.concat([i.sent()]))];case 12:return P=i.sent(),[3,17];case 13:return s.supportsBlob?(U=(R=l).POSTFILE,I=[b,S],[4,e.toBlob()]):[3,16];case 14:return[4,U.apply(R,I.concat([i.sent()]))];case 15:return P=i.sent(),[3,17];case 16:throw new Error("Unsupported environment");case 17:return[3,19];case 18:throw(x=i.sent()).response&&"string"==typeof x.response.text?(D=x.response.text,F=/(.*)<\/Message>/gi.exec(D),new q(F?"Upload to bucket failed: ".concat(F[1]):"Upload to bucket failed.",x)):new q("Upload to bucket failed.",x);case 19:if(204!==P.status)throw new q("Upload to bucket was unsuccessful",P);G=u.fileUploadPublishRetryLimit,L=!1,K={timetoken:"0"},i.label=20;case 20:return i.trys.push([20,22,,23]),[4,r({channel:a,message:f,fileId:_,fileName:O,meta:d,storeInHistory:g,ttl:y})];case 21:return K=i.sent(),L=!0,[3,23];case 22:return i.sent(),G-=1,[3,23];case 23:if(!L&&G>0)return[3,20];i.label=24;case 24:if(L)return[2,{timetoken:K.timetoken,id:_,name:O}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:_,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;return o(void 0,void 0,void 0,(function(){var e,o,u,c;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(null!==(o=n.cipherKey)&&void 0!==o?o:a.cipherKey)?[4,s.decrypt(null!==(u=n.cipherKey)&&void 0!==u?u:a.cipherKey,e)]:[3,2];case 1:e=i.sent(),i.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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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.toArrayBuffer()];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.toArrayBuffer()];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 n=e.encoder.encode(t),[4,crypto.subtle.digest("SHA-256",n.buffer)];case 1:return r=i.sent(),o=(a=(c=r,u([],s(new Uint8Array(c)),!1).map((function(e){return e.toString(16).padStart(2,"0")})).join("")).slice(0,32),new Uint8Array(a.match(/[\da-f]{2}/gi).map((function(e){return parseInt(e,16)})))).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}var a,c}))}))},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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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;return i(this,(function(i){switch(i.label){case 0:return r=bi.tryParse(t.data),(null==(o=this.getCryptor(r))?void 0:o.identifier)===e.LEGACY_IDENTIFIER?[2,o.decryptFile(t,n)]:(a=this.getFileData(t.data),s=a.slice(r.length-r.metadataLength,r.length),c=(u=n).create,l={name:t.name},[4,this.defaultCryptor.decryptFileData({data:t.data.slice(r.length),metadata:s})]);case 1:return[2,c.apply(u,[(l.data=i.sent(),l)])]}}))}))},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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); +!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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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,_,O,S,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,O=_.id,S=_.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:O,fileName:S,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:O,name:S}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:O,name:S})}}))}))}}(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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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=bi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:(s=this.getFileData(r),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 2: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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); 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/send_file.js b/lib/core/endpoints/file_upload/send_file.js index 729fb7453..34aba2be1 100644 --- a/lib/core/endpoints/file_upload/send_file.js +++ b/lib/core/endpoints/file_upload/send_file.js @@ -39,13 +39,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); var endpoint_1 = require("../../components/endpoint"); 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")); @@ -56,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) { @@ -71,48 +79,48 @@ var sendFile = function (_a) { return entry; }); } - _s.label = 4; - case 4: - _s.trys.push([4, 18, , 19]); - 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*/, 19]; + 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(); + 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); @@ -121,17 +129,17 @@ var sendFile = function (_a) { else { throw new endpoint_1.PubNubError('Upload to bucket failed.', e_1); } - return [3 /*break*/, 19]; - case 19: + return [3 /*break*/, 22]; + case 22: if (result.status !== 204) { throw new endpoint_1.PubNubError('Upload to bucket was unsuccessful', result); } retries = config.fileUploadPublishRetryLimit; wasSuccessful = false; publishResult = { timetoken: '0' }; - _s.label = 20; - case 20: - _s.trys.push([20, 22, , 23]); + _t.label = 23; + case 23: + _t.trys.push([23, 25, , 26]); return [4 /*yield*/, publishFile({ channel: channel, message: message, @@ -141,19 +149,19 @@ var sendFile = function (_a) { storeInHistory: storeInHistory, ttl: ttl, })]; - case 21: + case 24: /* eslint-disable-next-line no-await-in-loop */ - publishResult = _s.sent(); + publishResult = _t.sent(); wasSuccessful = true; - return [3 /*break*/, 23]; - case 22: - e_2 = _s.sent(); + return [3 /*break*/, 26]; + case 25: + e_2 = _t.sent(); retries -= 1; - return [3 /*break*/, 23]; - case 23: - if (!wasSuccessful && retries > 0) return [3 /*break*/, 20]; - _s.label = 24; - case 24: + return [3 /*break*/, 26]; + case 26: + if (!wasSuccessful && retries > 0) return [3 /*break*/, 23]; + _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', { channel: channel, diff --git a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js index 5a16a5d10..d80cbbb15 100644 --- a/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/WebCryptoModule/aesCbcCryptor.js @@ -41,7 +41,6 @@ var __importDefault = (this && this.__importDefault) || function (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"); -// ts check disabled: CryptoJs does not have types specified var AesCbcCryptor = /** @class */ (function () { function AesCbcCryptor(configuration) { this.cipherKey = configuration.cipherKey; diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index 26bd9a3f1..1194a79ac 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -140,26 +140,29 @@ var CryptoModule = /** @class */ (function () { }; CryptoModule.prototype.decryptFile = function (file, File) { return __awaiter(this, void 0, void 0, function () { - var header, cryptor, fileData, metadata, _a, _b; + var data, header, cryptor, fileData, metadata, _a, _b; var _c; return __generator(this, function (_d) { switch (_d.label) { - case 0: - header = CryptorHeader.tryParse(file.data); + 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) + if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) { return [2 /*return*/, cryptor.decryptFile(file, File)]; - fileData = this.getFileData(file.data); + } + fileData = this.getFileData(data); metadata = fileData.slice(header.length - header.metadataLength, header.length); _b = (_a = File).create; _c = { name: file.name }; return [4 /*yield*/, this.defaultCryptor.decryptFileData({ - data: file.data.slice(header.length), + data: data.slice(header.length), metadata: metadata, })]; - case 1: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), + case 2: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(), _c)])]; } }); diff --git a/lib/crypto/modules/web.js b/lib/crypto/modules/web.js index 83501135a..b7bb887ea 100644 --- a/lib/crypto/modules/web.js +++ b/lib/crypto/modules/web.js @@ -36,31 +36,6 @@ 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 __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)); -}; Object.defineProperty(exports, "__esModule", { value: true }); function concatArrayBuffer(ab1, ab2) { var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); @@ -68,14 +43,6 @@ function concatArrayBuffer(ab1, ab2) { tmp.set(new Uint8Array(ab2), ab1.byteLength); return tmp.buffer; } -function ab2hex(ab) { - return __spreadArray([], __read(new Uint8Array(ab)), false).map(function (x) { return x.toString(16).padStart(2, '0'); }).join(''); -} -function hex2ab(hex) { - return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { - return parseInt(h, 16); - })); -} var WebCryptography = /** @class */ (function () { function WebCryptography() { } @@ -135,7 +102,7 @@ var WebCryptography = /** @class */ (function () { 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)]; @@ -158,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)]; @@ -174,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 = WebCryptography.encoder.encode(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 = hex2ab(ab2hex(abHash).slice(0, 32)).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'])]; } }); From 915d355ac2eb405f462187aec875c34cbe716ea0 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Sun, 15 Oct 2023 23:38:12 +0530 Subject: [PATCH 34/38] refactor: crypto initialiser apis default value initialisation --- dist/web/pubnub.js | 14 ++++++++++++-- dist/web/pubnub.min.js | 2 +- .../modules/NodeCryptoModule/NodeCryptoModule.js | 16 +++++++++++++--- .../modules/NodeCryptoModule/aesCbcCryptor.js | 2 +- .../modules/WebCryptoModule/webCryptoModule.js | 14 ++++++++++++-- .../modules/NodeCryptoModule/aesCbcCryptor.ts | 2 +- .../modules/NodeCryptoModule/nodeCryptoModule.ts | 14 +++++++++++--- .../modules/WebCryptoModule/webCryptoModule.ts | 12 ++++++++++-- 8 files changed, 61 insertions(+), 15 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 7eea98515..5029d6a28 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -13080,15 +13080,25 @@ // 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(config), + 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(config)], + cryptors: [ + new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], }); }; CryptoModule.withDefaultCryptor = function (defaultCryptor) { diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index a7ab4ba61..ac9deb34e 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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,_,O,S,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,O=_.id,S=_.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:O,fileName:S,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:O,name:S}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:O,name:S})}}))}))}}(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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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=bi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:(s=this.getFileData(r),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 2: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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); +!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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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,_,O,S,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,O=_.id,S=_.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:O,fileName:S,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:O,name:S}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:O,name:S})}}))}))}}(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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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=bi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:(s=this.getFileData(r),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 2: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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); diff --git a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js index 4107519c5..fdaef2d94 100644 --- a/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/NodeCryptoModule.js @@ -80,15 +80,25 @@ var CryptoModule = /** @class */ (function () { // 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(config), + 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(config)], + cryptors: [ + new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], }); }; CryptoModule.withDefaultCryptor = function (defaultCryptor) { @@ -110,7 +120,7 @@ var CryptoModule = /** @class */ (function () { headerData.set(header.data, pos); pos = header.length - encrypted.metadata.length; headerData.set(encrypted.metadata, pos); - return Buffer.concat([headerData, Buffer.from(encrypted.data)]).buffer; + 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); diff --git a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js index 675ec6a83..613e8cfec 100644 --- a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js @@ -82,7 +82,7 @@ var AesCbcCryptor = /** @class */ (function () { 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()])); + return Uint8Array.from(Buffer.concat([aes.update(data), aes.final()])).buffer; }; AesCbcCryptor.prototype.encryptStream = function (stream) { return __awaiter(this, void 0, void 0, function () { diff --git a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js index 1194a79ac..e511da1ea 100644 --- a/lib/crypto/modules/WebCryptoModule/webCryptoModule.js +++ b/lib/crypto/modules/WebCryptoModule/webCryptoModule.js @@ -79,15 +79,25 @@ var CryptoModule = /** @class */ (function () { // 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(config), + 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(config)], + cryptors: [ + new legacyCryptor_1.default({ + cipherKey: config.cipherKey, + useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true, + }), + ], }); }; CryptoModule.withDefaultCryptor = function (defaultCryptor) { diff --git a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts index 8d439d110..68cfb89a6 100644 --- a/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/aesCbcCryptor.ts @@ -47,7 +47,7 @@ export default class AesCbcCryptor implements ICryptor { 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()])); + return Uint8Array.from(Buffer.concat([aes.update(data), aes.final()])).buffer; } async encryptStream(stream: NodeJS.ReadableStream) { diff --git a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts index 5b7975d19..a1d218946 100644 --- a/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts +++ b/src/crypto/modules/NodeCryptoModule/nodeCryptoModule.ts @@ -29,7 +29,10 @@ export class CryptoModule { // @ts-ignore: type detection issue with old Config type assignment static legacyCryptoModule(config) { return new this({ - default: new LegacyCryptor(config), + default: new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); } @@ -37,7 +40,12 @@ export class CryptoModule { static aesCbcCryptoModule(config: any) { return new this({ default: new AesCbcCryptor({ cipherKey: config.cipherKey }), - cryptors: [new LegacyCryptor(config)], + cryptors: [ + new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), + ], }); } static withDefaultCryptor(defaultCryptor: CryptorType) { @@ -63,7 +71,7 @@ export class CryptoModule { headerData.set(header!.data, pos); pos = header!.length - encrypted.metadata.length; headerData.set(encrypted.metadata, pos); - return Buffer.concat([headerData, Buffer.from(encrypted.data)]).buffer; + return Buffer.concat([headerData, Buffer.from(encrypted.data)]); } decrypt(data: ArrayBuffer | string) { diff --git a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts index c82773681..38ca192ce 100644 --- a/src/crypto/modules/WebCryptoModule/webCryptoModule.ts +++ b/src/crypto/modules/WebCryptoModule/webCryptoModule.ts @@ -29,7 +29,10 @@ export class CryptoModule { //@ts-ignore: type detection issue with old Config type assignment static legacyCryptoModule(config) { return new this({ - default: new LegacyCryptor(config), + default: new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })], }); } @@ -37,7 +40,12 @@ export class CryptoModule { static aesCbcCryptoModule(config: any) { return new this({ default: new AesCbcCryptor({ cipherKey: config.cipherKey }), - cryptors: [new LegacyCryptor(config)], + cryptors: [ + new LegacyCryptor({ + cipherKey: config.cipherKey, + useRandomIVs: config.useRandomIVs ?? true, + }), + ], }); } From 11351ec45d96bcf46cee50efd308825de7fbac8c Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 16 Oct 2023 16:07:18 +0530 Subject: [PATCH 35/38] LICENSE --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 3f2064658..06cf44e78 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "contract:refresh": "rimraf dist/contract && git clone --branch master git@github.com:pubnub/service-contract-mock.git dist/contract && npm install --prefix dist/contract && npm run refresh-files --prefix dist/contract", "contract:server": "npm start --prefix dist/contract consumer", "contract:build": "cd test/contract && tsc", + "crypto:test": "cucumber-js --require dist/cucumber dist/contract/contract/features/encryption", "contract:test": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags 'not @na=js and not @beta'", "contract:test-beta": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags 'not @na=js and @beta'", "contract:test-access": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags '@featureSet=access and not @na=js and not @beta'", From e007216d369a243666eacf5d7762e7b97cfa46d9 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 16 Oct 2023 16:09:24 +0530 Subject: [PATCH 36/38] reverted last commit 11351ec --- package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package.json b/package.json index 06cf44e78..175901348 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,6 @@ "contract:refresh": "rimraf dist/contract && git clone --branch master git@github.com:pubnub/service-contract-mock.git dist/contract && npm install --prefix dist/contract && npm run refresh-files --prefix dist/contract", "contract:server": "npm start --prefix dist/contract consumer", "contract:build": "cd test/contract && tsc", - "crypto:test": "cucumber-js --require dist/cucumber dist/contract/contract/features/encryption", "contract:test": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags 'not @na=js and not @beta'", "contract:test-beta": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags 'not @na=js and @beta'", "contract:test-access": "cucumber-js --require dist/cucumber dist/contract/contract/features --tags '@featureSet=access and not @na=js and not @beta'", @@ -103,4 +102,4 @@ "engine": { "node": ">=0.8" } -} +} \ No newline at end of file From 0a8a4a60591c5458696dbe7a803186ee8c22259b Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 16 Oct 2023 16:09:51 +0530 Subject: [PATCH 37/38] update LICENSE --- LICENSE | 48 +++++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 23 deletions(-) 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 From c8d347a7d6418bed6f7ced1319ba58a019ff30b8 Mon Sep 17 00:00:00 2001 From: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com> Date: Mon, 16 Oct 2023 11:09:25 +0000 Subject: [PATCH 38/38] PubNub SDK v7.4.0 release. --- .pubnub.yml | 13 +- CHANGELOG.md | 9 + README.md | 4 +- dist/web/pubnub.js | 2 +- dist/web/pubnub.min.js | 2 +- lib/core/components/config.js | 2 +- .../NodeCryptoModule/nodeCryptoModule.js | 446 ++++++++++++++++++ package.json | 2 +- src/core/components/config.js | 2 +- 9 files changed, 472 insertions(+), 10 deletions(-) create mode 100644 lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js diff --git a/.pubnub.yml b/.pubnub.yml index 29a468cf7..875765985 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,12 @@ --- changelog: + - 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: @@ -895,7 +902,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '7.3.3' +version: '7.4.0' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -911,7 +918,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v7.3.3.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v7.4.0.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1582,7 +1589,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v7.3.3/pubnub.7.3.3.js + location: https://github.com/pubnub/javascript/releases/download/v7.4.0/pubnub.7.4.0.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index ef5b21172..70bffca12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## 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 diff --git a/README.md b/README.md index 82bc5ba3d..f05a4a6d6 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ Watch [Getting Started with PubNub JS SDK](https://app.dashcam.io/replay/64ee0d2 npm install pubnub ``` * or download one of our builds from our CDN: - * https://cdn.pubnub.com/sdk/javascript/pubnub.7.3.3.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.7.3.3.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.0.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.0.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 5029d6a28..46c438cf1 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -791,7 +791,7 @@ return this; }; default_1.prototype.getVersion = function () { - return '7.3.3'; + return '7.4.0'; }; default_1.prototype._addPnsdkSuffix = function (name, suffix) { this._PNSDKSuffix[name] = suffix; diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index ac9deb34e..4a3519b2e 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -14,4 +14,4 @@ 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&&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;)O+=f,_.push(c(f));var S=new Uint8Array(O),P=0;for(o=0;o<_.length;++o)S.set(_[o],P),P+=_[o].length;return S}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.3.3"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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,_,O,S,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,O=_.id,S=_.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:O,fileName:S,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:O,name:S}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:O,name:S})}}))}))}}(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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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=bi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:(s=this.getFileData(r),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 2: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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); +!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.0"},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,_,O,S,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 S.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],O=e[i+13],S=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,O,12,c[13]),T=t(T,E,w,A,S,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,S,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,O,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,S,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,O,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,S,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,O,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],O=257*h[b]^16843008*b;i[y]=O<<24|O>>>8,a[y]=O<<16|O>>>16,s[y]=O<<8|O>>>24,u[y]=O,O=16843009*_^65537*m^257*v^16843008*y,c[b]=O<<24|O>>>8,l[b]=O<<16|O>>>16,p[b]=O<<8|O>>>24,f[b]=O,y?(y=v^h[h[h[_^v]]],g^=h[h[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),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^=S[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,console&&console.log&&console.log("decryption error",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,console&&console.log&&console.log("decryption error",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,_,O,S,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,O=_.id,S=_.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:O,fileName:S,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:O,name:S}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:O,name:S})}}))}))}}(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})]}}))}))}},Oe={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}}},Se={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"UUID 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={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===(i=null===(o=t.include)||void 0===o?void 0:o.UUIDFields)||void 0===i||i)&&y.include.push("uuid")),y.include=y.include.join(","),(null===(a=null==t?void 0:t.include)||void 0===a?void 0:a.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===(f=t.page)||void 0===f?void 0:f.prev),(null==t?void 0:t.filter)&&(y.filter=t.filter),y.limit=null!==(h=null==t?void 0:t.limit)&&void 0!==h?h:100,(null==t?void 0:t.sort)&&(y.sort=Object.entries(null!==(d=t.sort)&&void 0!==d?d:{}).map((function(e){var t=s(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}}},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={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===(o=t.include)||void 0===o?void 0:o.channelFields)&&d.include.push("channel")),d.include=d.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(d.count=null===(a=t.include)||void 0===a?void 0:a.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!==(f=null==t?void 0:t.limit)&&void 0!==f?f:100,(null==t?void 0:t.sort)&&(d.sort=Object.entries(null!==(h=t.sort)&&void 0!==h?h:{}).map((function(e){var t=s(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 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,O=t.authKeys,S=void 0===O?[]:O,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(",")),S.length>0&&(w.auth=S.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]}}});function qe(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}var ze=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={timetoken:t.timetoken,entry:qe(e,t.message)};t.meta&&(r.meta=t.meta),n.messages.push(r)})),n}});var Ve=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 We=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 Je=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={};o.channel=r,o.timetoken=t.timetoken,o.message=function(e,t){if(!e.cryptoModule)return t;try{var n=e.cryptoModule.decrypt(t);return n instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(n)):n}catch(e){return console&&console.log&&console.log("decryption error",e.message),t}}(e,t.message),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),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var $e=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 Qe=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}}}),Xe={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}}},Ye={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}}}},Ze=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}(),et=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}(),tt=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new et(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 O=a(this.currentState.enterEffects),S=O.next();!S.done;S=O.next()){g=S.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{S&&!S.done&&(u=O.return)&&u.call(O)}finally{if(i)throw i.error}}}},n}(Ze),nt=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 rt(e,t){var n=function(){for(var n=[],r=0;r0&&console.log(e),[2]}))}))}))),r.on(yt.type,pt((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(Ct())];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(Nt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(kt(o))]:[3,5];case 5:return[2]}}))}))}))),r.on(gt.type,pt((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(wt())];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(Pt(o))]:[3,5];case 5:return[2]}}))}))}))),r}return t(n,e),n}(nt),Rt=new et("STOPPED");Rt.on(bt.type,(function(e,t){return Rt.with({channels:t.payload.channels,groups:t.payload.groups})})),Rt.on(mt.type,(function(e){return Lt.with(n({},e))}));var Ut=new et("HANDSHAKE_FAILURE");Ut.on(Et.type,(function(e){return Gt.with(n(n({},e),{attempts:0}))})),Ut.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var It=new et("STOPPED");It.on(bt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),It.on(mt.type,(function(e){return Ft.with(n({},e))}));var xt=new et("RECEIVE_FAILURE");xt.on(jt.type,(function(e){return Dt.with(n(n({},e),{attempts:0}))})),xt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Dt=new et("RECEIVE_RECONNECTING");Dt.onEnter((function(e){return yt(e)})),Dt.onExit((function(){return yt.cancel})),Dt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Dt.on(kt.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(Ct.type,(function(e){return xt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:e.reason})})),Dt.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Ft=new et("RECEIVING");Ft.onEnter((function(e){return ht(e.channels,e.groups,e.cursor)})),Ft.onExit((function(){return ht.cancel})),Ft.on(Tt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor}),[dt(t.payload.events)])})),Ft.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Ft.with(n(n({},e),{channels:t.payload.channels,groups:t.payload.groups}))})),Ft.on(At.type,(function(e,t){return Dt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Ft.on(vt.type,(function(e){return It.with({channels:e.channels,groups:e.groups,cursor:e.cursor})}));var Gt=new et("HANDSHAKE_RECONNECTING");Gt.onEnter((function(e){return gt(e)})),Gt.onExit((function(){return yt.cancel})),Gt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[dt(t.payload.events)])})),Gt.on(kt.type,(function(e,t){return Gt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Gt.on(Ct.type,(function(e){return Ut.with({groups:e.groups,channels:e.channels,reason:e.reason})})),Gt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Lt=new et("HANDSHAKING");Lt.onEnter((function(e){return ft(e.channels,e.groups)})),Lt.onExit((function(){return ft.cancel})),Lt.on(bt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Kt.with(void 0):Lt.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(_t.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload})})),Lt.on(Ot.type,(function(e,t){return Gt.with(n(n({},e),{attempts:0,reason:t.payload}))})),Lt.on(vt.type,(function(e){return Rt.with({channels:e.channels,groups:e.groups})}));var Kt=new et("UNSUBSCRIBED");Kt.on(bt.type,(function(e,t){return Lt.with({channels:t.payload.channels,groups:t.payload.groups})}));var Bt=function(){function e(e){var t=this;this.engine=new tt,this.channels=[],this.groups=[],this.dispatcher=new Mt(this.engine,e),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=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(bt(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(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.engine.transition(bt(this.channels.slice(0),this.groups.slice(0)))},e.prototype.reconnect=function(){this.engine.transition(mt())},e.prototype.disconnect=function(){this.engine.transition(vt())},e}(),Ht=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,$e),y=Q.bind(this,h,ae),b=Q.bind(this,h,ue),m=Q.bind(this,h,le),_=Q.bind(this,h,Qe),O=new B;if(this._listenerManager=O,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,Xe),this.receiveMessages=Q.bind(this,h,Ye),!0===i.enableSubscribeBeta){var S=new Bt({handshake:this.handshake,receiveEvents:this.receiveMessages});this.subscribe=S.subscribe.bind(S),this.unsubscribe=S.unsubscribe.bind(S),this.eventEngine=S}else{var P=new U({timeEndpoint:d,leaveEndpoint:y,heartbeatEndpoint:b,setStateEndpoint:m,subscribeEndpoint:_,crypto:h.crypto,config:h.config,listenerManager:O,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=O.addListener.bind(O),this.removeListener=O.removeListener.bind(O),this.removeAllListeners=O.removeAllListeners.bind(O),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,ze),this.deleteMessages=Q.bind(this,h,Ve),this.messageCounts=Q.bind(this,h,We),this.fetchMessages=Q.bind(this,h,Je),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,Oe),this.objects={getAllUUIDMetadata:Q.bind(this,h,Se),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 zt(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)?zt(a):a})),n}var Vt=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}(),Wt={exports:{}},Jt={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 nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function an(e,t,n,r){void 0===r&&(r=en());var o,i=sn(e,"",0,[],void 0,0,r)||e;try{o=0===Zt.length?JSON.stringify(i,t,n):JSON.stringify(i,un(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Yt.length;){var a=Yt.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function sn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void nn(Qt,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void nn(Qt,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new On('"allowMissing" argument must be a boolean');var n=Kn(e),r=n.length>0?n[0]:"",o=Bn("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],xn(n,In([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Pn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=Un(a,p),a=a[p];l&&!s&&(Cn[i]=a)}}return a},qn={exports:{}};!function(e){var t=bn,n=Hn,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}(qn);var zn=Hn,Vn=qn.exports,Wn=Vn(zn("String.prototype.indexOf")),Jn=l(Object.freeze({__proto__:null,default:{}})),$n="function"==typeof Map&&Map.prototype,Qn=Object.getOwnPropertyDescriptor&&$n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Xn=$n&&Qn&&"function"==typeof Qn.get?Qn.get:null,Yn=$n&&Map.prototype.forEach,Zn="function"==typeof Set&&Set.prototype,er=Object.getOwnPropertyDescriptor&&Zn?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,tr=Zn&&er&&"function"==typeof er.get?er.get:null,nr=Zn&&Set.prototype.forEach,rr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,or="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ir="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ar=Boolean.prototype.valueOf,sr=Object.prototype.toString,ur=Function.prototype.toString,cr=String.prototype.match,lr=String.prototype.slice,pr=String.prototype.replace,fr=String.prototype.toUpperCase,hr=String.prototype.toLowerCase,dr=RegExp.prototype.test,yr=Array.prototype.concat,gr=Array.prototype.join,br=Array.prototype.slice,vr=Math.floor,mr="function"==typeof BigInt?BigInt.prototype.valueOf:null,_r=Object.getOwnPropertySymbols,Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Sr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Pr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Sr||"symbol")?Symbol.toStringTag:null,wr=Object.prototype.propertyIsEnumerable,Er=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Tr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||dr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-vr(-e):vr(e);if(r!==e){var o=String(r),i=lr.call(t,o.length+1);return pr.call(o,n,"$&_")+"."+pr.call(pr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pr.call(t,n,"$&_")}var Ar=Jn,Nr=Ar.custom,kr=Ur(Nr)?Nr:null;function Cr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function jr(e){return pr.call(String(e),/"/g,""")}function Mr(e){return!("[object Array]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Rr(e){return!("[object RegExp]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}function Ur(e){if(Sr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Or)return!1;try{return Or.call(e),!0}catch(e){}return!1}var Ir=Object.prototype.hasOwnProperty||function(e){return e in this};function xr(e,t){return Ir.call(e,t)}function Dr(e){return sr.call(e)}function Fr(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 Gr(lr.call(e,0,t.maxStringLength),t)+r}return Cr(pr.call(pr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Lr),"single",t)}function Lr(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":"")+fr.call(t.toString(16))}function Kr(e){return"Object("+e+")"}function Br(e){return e+" { ? }"}function Hr(e,t,n,r){return e+" ("+t+") {"+(r?qr(n,r):gr.call(n,", "))+"}"}function qr(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+gr.call(e,","+n)+"\n"+t.prev}function zr(e,t){var n=Mr(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Vn(n):n},Jr=function e(t,n,r,o){var i=n||{};if(xr(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(xr(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=!xr(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(xr(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(xr(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 Gr(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Tr(t,u):u}if("bigint"==typeof t){var c=String(t)+"n";return s?Tr(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 Mr(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=gr.call(Array(e.indent+1)," ")}return{base:n,prev:gr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(Fr(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=br.call(o)).push(n),a){var s={depth:i.depth};return xr(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!Rr(t)){var h=function(e){if(e.name)return e.name;var t=cr.call(ur.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),d=zr(t,f);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(d.length>0?" { "+gr.call(d,", ")+" }":"")}if(Ur(t)){var y=Sr?pr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Or.call(t);return"object"!=typeof t||Sr?y:Kr(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="<"+hr.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(Mr(t)){if(0===t.length)return"[]";var m=zr(t,f);return p&&!function(e){for(var t=0;t=0)return!1;return!0}(m)?"["+qr(m,p)+"]":"[ "+gr.call(m,", ")+" ]"}if(function(e){return!("[object Error]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)){var _=zr(t,f);return"cause"in Error.prototype||!("cause"in t)||wr.call(t,"cause")?0===_.length?"["+String(t)+"]":"{ ["+String(t)+"] "+gr.call(_,", ")+" }":"{ ["+String(t)+"] "+gr.call(yr.call("[cause]: "+f(t.cause),_),", ")+" }"}if("object"==typeof t&&a){if(kr&&"function"==typeof t[kr]&&Ar)return Ar(t,{depth:l-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Xn||!e||"object"!=typeof e)return!1;try{Xn.call(e);try{tr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var O=[];return Yn&&Yn.call(t,(function(e,n){O.push(f(n,t,!0)+" => "+f(e,t))})),Hr("Map",Xn.call(t),O,p)}if(function(e){if(!tr||!e||"object"!=typeof e)return!1;try{tr.call(e);try{Xn.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var S=[];return nr&&nr.call(t,(function(e){S.push(f(e,t))})),Hr("Set",tr.call(t),S,p)}if(function(e){if(!rr||!e||"object"!=typeof e)return!1;try{rr.call(e,rr);try{or.call(e,or)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Br("WeakMap");if(function(e){if(!or||!e||"object"!=typeof e)return!1;try{or.call(e,or);try{rr.call(e,rr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Br("WeakSet");if(function(e){if(!ir||!e||"object"!=typeof e)return!1;try{return ir.call(e),!0}catch(e){}return!1}(t))return Br("WeakRef");if(function(e){return!("[object Number]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!mr)return!1;try{return mr.call(e),!0}catch(e){}return!1}(t))return Kr(f(mr.call(t)));if(function(e){return!("[object Boolean]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(ar.call(t));if(function(e){return!("[object String]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t))return Kr(f(String(t)));if(!function(e){return!("[object Date]"!==Dr(e)||Pr&&"object"==typeof e&&Pr in e)}(t)&&!Rr(t)){var P=zr(t,f),w=Er?Er(t)===Object.prototype:t instanceof Object||t.constructor===Object,E=t instanceof Object?"":"null prototype",T=!w&&Pr&&Object(t)===t&&Pr in t?lr.call(Dr(t),8,-1):E?"Object":"",A=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||E?"["+gr.call(yr.call([],T||[],E||[]),": ")+"] ":"");return 0===P.length?A+"{}":p?A+"{"+qr(P,p)+"}":A+"{ "+gr.call(P,", ")+" }"}return String(t)},$r=Vr("%TypeError%"),Qr=Vr("%WeakMap%",!0),Xr=Vr("%Map%",!0),Yr=Wr("WeakMap.prototype.get",!0),Zr=Wr("WeakMap.prototype.set",!0),eo=Wr("WeakMap.prototype.has",!0),to=Wr("Map.prototype.get",!0),no=Wr("Map.prototype.set",!0),ro=Wr("Map.prototype.has",!0),oo=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},io=String.prototype.replace,ao=/%20/g,so="RFC3986",uo={default:so,formatters:{RFC1738:function(e){return io.call(e,ao,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:so},co=uo,lo=Object.prototype.hasOwnProperty,po=Array.isArray,fo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ho=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(po(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===co.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=fo[u]:u<2048?a+=fo[192|u>>6]+fo[128|63&u]:u<55296||u>=57344?a+=fo[224|u>>12]+fo[128|u>>6&63]+fo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=fo[240|u>>18]+fo[128|u>>12&63]+fo[128|u>>6&63]+fo[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(po(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Oo(u))P=u;else{var E=Object.keys(v);P=c?E.sort(c):E}for(var T=o&&Oo(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},Io=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&&Co.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)}},xo=function(e,t){var n,r=e,o=function(e){if(!e)return To;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||To.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=vo.default;if(void 0!==e.format){if(!mo.call(vo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=vo.formatters[n],o=To.filter;return("function"==typeof e.filter||Oo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:To.addQueryPrefix,allowDots:void 0===e.allowDots?To.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:To.charsetSentinel,delimiter:void 0===e.delimiter?To.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:To.encode,encoder:"function"==typeof e.encoder?e.encoder:To.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:To.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:To.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:To.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:To.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Oo(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in _o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=_o[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=go(),l=0;l0?h+f:""},Do={formats:uo,parse:function(e,t){var n=function(e){if(!e)return Mo;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?Mo.charset:e.charset;return{allowDots:void 0===e.allowDots?Mo.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Mo.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Mo.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Mo.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Mo.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Mo.comma,decoder:"function"==typeof e.decoder?e.decoder:Mo.decoder,delimiter:"string"==typeof e.delimiter||ko.isRegExp(e.delimiter)?e.delimiter:Mo.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Mo.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Mo.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Mo.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Mo.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Mo.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=jo(l)?[l]:l),Co.call(r,c)?r[c]=ko.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])}}(Fo);const Go=Jn,Lo=Fo.isObject,Ko=Fo.hasOwn;var Bo=Ho;function Ho(){}Ho.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},Ho.prototype.parse=function(e){return this._parser=e,this},Ho.prototype.responseType=function(e){return this._responseType=e,this},Ho.prototype.serialize=function(e){return this._serializer=e,this},Ho.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(Ko(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},Ho.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 qo=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),zo=new Set([408,413,429,500,502,503,504,521,522,524]);Ho.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&&zo.has(t.status))return!0;if(e){if(e.code&&qo.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},Ho.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()},Ho.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)},Ho.prototype.catch=function(e){return this.then(void 0,e)},Ho.prototype.use=function(e){return e(this),this},Ho.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},Ho.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},Ho.prototype.get=function(e){return this._header[e.toLowerCase()]},Ho.prototype.getHeader=Ho.prototype.get,Ho.prototype.set=function(e,t){if(Lo(e)){for(const t in e)Ko(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},Ho.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},Ho.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(Lo(e)){for(const t in e)Ko(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)Ko(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},Ho.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(Go.gte(process.version,"v13.0.0")&&Go.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},Ho.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},Ho.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},Ho.prototype.redirects=function(e){return this._maxRedirects=e,this},Ho.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},Ho.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},Ho.prototype.send=function(e){const t=Lo(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&&Lo(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");Ko(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},Ho.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},Ho.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("&")}}},Ho.prototype._appendQueryString=()=>{console.warn("Unsupported")},Ho.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)},Ho.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 Vo=Fo;var Wo=Jo;function Jo(){}function $o(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 Qo(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 Qo(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 Qo(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 O(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(O.prototype,f.prototype),O.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)},O.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=O,i(S.prototype),l(S.prototype,u.prototype),S.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},S.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},S.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)},S.prototype.query=function(e){return"string"!=typeof e&&(e=b(e)),e&&this._query.push(e),this},S.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},S.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},S.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)},S.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)},S.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},S.prototype.ca=S.prototype.agent,S.prototype.buffer=S.prototype.ca,S.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},S.prototype.pipe=S.prototype.write,S.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},S.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()},S.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},S.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}}(Wt,Wt.exports);var ti=Wt.exports;function ni(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 ri(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(ni)),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 oi(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=ti.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 ii(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function ai(e,t,n){var r=ti.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function si(e,t,n,r){var o=ti.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ui(e,t,n,r){var o=ti.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ri.call(this,o,n,r)}function ci(e,t,n){var r=ti.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ri.call(this,r,t,n)}function li(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 pi,fi=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=li,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=li(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}(),hi=(pi=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}(),pi.supportsFile="undefined"!=typeof File,pi.supportsBlob="undefined"!=typeof Blob,pi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,pi.supportsBuffer=!1,pi.supportsStream=!1,pi.supportsString=!0,pi.supportsEncryptFile=!0,pi.supportsFileUri=!1,pi),di=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new fi}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}(),yi=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===bi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:(n=this.getFileData(e.data),[4,this.defaultCryptor.encryptFileData(n)]);case 1: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=bi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:(s=this.getFileData(r),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 2: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 vi)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=bi.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){if(t instanceof ArrayBuffer)return t;if("string"==typeof t)return e.encoder.encode(t);throw new Error("Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer")},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),bi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new vi(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 vi(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}(),vi=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 bi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return bi.SENTINEL.length+1+bi.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(bi.SENTINEL)),t[e+=bi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=bi.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 mi(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var _i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new qt({del:ci,get:ai,post:si,patch:ui,sendBeacon:mi,getfile:ii,postfile:oi}),t.cbor=new Vt((function(e){return zt(f.decode(e))}),b),t.PubNubFile=hi,t.cryptography=new fi,t.initCryptoModule=function(e){return new gi({default:new di({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new yi({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=gi,n}(Ht);return _i})); diff --git a/lib/core/components/config.js b/lib/core/components/config.js index 3512450ed..628d414f4 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -177,7 +177,7 @@ var default_1 = /** @class */ (function () { return this; }; default_1.prototype.getVersion = function () { - return '7.3.3'; + return '7.4.0'; }; default_1.prototype._addPnsdkSuffix = function (name, suffix) { this._PNSDKSuffix[name] = suffix; 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/package.json b/package.json index 175901348..78f1466c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "7.3.3", + "version": "7.4.0", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/config.js b/src/core/components/config.js index ef1fcfea7..883f86c2f 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -350,7 +350,7 @@ export default class { } getVersion() { - return '7.3.3'; + return '7.4.0'; } _addPnsdkSuffix(name, suffix) {